blob: 3c757b33611698e3c1b6a4258172f00757275541 [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
144 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145}
146
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530147void AudioPolicyService::unloadAudioPolicyManager()
148{
149 ALOGV("%s ", __func__);
150 if (mLibraryHandle != nullptr) {
151 dlclose(mLibraryHandle);
152 }
153 mLibraryHandle = nullptr;
154 mCreateAudioPolicyManager = nullptr;
155 mDestroyAudioPolicyManager = nullptr;
156}
157
Mathias Agopian65ab4712010-07-14 17:59:35 -0700158AudioPolicyService::~AudioPolicyService()
159{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700161 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700162
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530163 mDestroyAudioPolicyManager(mAudioPolicyManager);
164 unloadAudioPolicyManager();
165
Eric Laurentdce54a12014-03-10 12:19:46 -0700166 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700167
168 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800169 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800170
171 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800172 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000173
174 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800175 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700176}
177
178// A notification client is always registered by AudioSystem when the client process
179// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800180Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700181{
Eric Laurent12590252015-08-21 18:40:20 -0700182 if (client == 0) {
183 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800184 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700185 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800186 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700187
188 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800189 pid_t pid = IPCThreadState::self()->getCallingPid();
190 int64_t token = ((int64_t)uid<<32) | pid;
191
192 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700193 sp<NotificationClient> notificationClient = new NotificationClient(this,
194 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800195 uid,
196 pid);
197 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700198
luochaojiang908c7d72018-06-21 14:58:04 +0800199 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700200
Marco Nelissenf8880202014-11-14 07:58:25 -0800201 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700202 binder->linkToDeath(notificationClient);
203 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800204 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700205}
206
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800207Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700208{
209 Mutex::Autolock _l(mNotificationClientsLock);
210
211 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800212 pid_t pid = IPCThreadState::self()->getCallingPid();
213 int64_t token = ((int64_t)uid<<32) | pid;
214
215 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800216 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700217 }
luochaojiang908c7d72018-06-21 14:58:04 +0800218 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800219 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700220}
221
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800222Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100223{
224 Mutex::Autolock _l(mNotificationClientsLock);
225
226 uid_t uid = IPCThreadState::self()->getCallingUid();
227 pid_t pid = IPCThreadState::self()->getCallingPid();
228 int64_t token = ((int64_t)uid<<32) | pid;
229
230 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800231 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100232 }
233 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800234 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100235}
236
Eric Laurentb52c1522014-05-20 11:27:36 -0700237// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800238void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700239{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000240 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800241 {
242 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800243 int64_t token = ((int64_t)uid<<32) | pid;
244 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800245 for (size_t i = 0; i < mNotificationClients.size(); i++) {
246 if (mNotificationClients.valueAt(i)->uid() == uid) {
247 hasSameUid = true;
248 break;
249 }
250 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000251 }
252 {
253 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800254 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700255 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700256 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700257 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800258 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700259}
260
261void AudioPolicyService::onAudioPortListUpdate()
262{
263 mOutputCommandThread->updateAudioPortListCommand();
264}
265
266void AudioPolicyService::doOnAudioPortListUpdate()
267{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800268 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700269 for (size_t i = 0; i < mNotificationClients.size(); i++) {
270 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
271 }
272}
273
274void AudioPolicyService::onAudioPatchListUpdate()
275{
276 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277}
278
Eric Laurentb52c1522014-05-20 11:27:36 -0700279void AudioPolicyService::doOnAudioPatchListUpdate()
280{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800281 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700282 for (size_t i = 0; i < mNotificationClients.size(); i++) {
283 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
284 }
285}
286
François Gaffiecfe17322018-11-07 13:41:29 +0100287void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
288{
289 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
290}
291
292void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
293{
294 Mutex::Autolock _l(mNotificationClientsLock);
295 for (size_t i = 0; i < mNotificationClients.size(); i++) {
296 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
297 }
298}
299
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700300void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700301{
302 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
303 regId.string(), state);
304 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
305}
306
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700307void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700308{
309 Mutex::Autolock _l(mNotificationClientsLock);
310 for (size_t i = 0; i < mNotificationClients.size(); i++) {
311 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
312 }
313}
314
Eric Laurenta9f86652018-11-28 17:23:11 -0800315void AudioPolicyService::onRecordingConfigurationUpdate(
316 int event,
317 const record_client_info_t *clientInfo,
318 const audio_config_base_t *clientConfig,
319 std::vector<effect_descriptor_t> clientEffects,
320 const audio_config_base_t *deviceConfig,
321 std::vector<effect_descriptor_t> effects,
322 audio_patch_handle_t patchHandle,
323 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800324{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800325 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800326 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800327}
328
Eric Laurenta9f86652018-11-28 17:23:11 -0800329void AudioPolicyService::doOnRecordingConfigurationUpdate(
330 int event,
331 const record_client_info_t *clientInfo,
332 const audio_config_base_t *clientConfig,
333 std::vector<effect_descriptor_t> clientEffects,
334 const audio_config_base_t *deviceConfig,
335 std::vector<effect_descriptor_t> effects,
336 audio_patch_handle_t patchHandle,
337 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800338{
339 Mutex::Autolock _l(mNotificationClientsLock);
340 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800341 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800342 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800343 }
344}
345
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700346void AudioPolicyService::onRoutingUpdated()
347{
348 mOutputCommandThread->routingChangedCommand();
349}
350
351void AudioPolicyService::doOnRoutingUpdated()
352{
353 Mutex::Autolock _l(mNotificationClientsLock);
354 for (size_t i = 0; i < mNotificationClients.size(); i++) {
355 mNotificationClients.valueAt(i)->onRoutingUpdated();
356 }
357}
358
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800359status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
360 audio_patch_handle_t *handle,
361 int delayMs)
362{
363 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
364}
365
366status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
367 int delayMs)
368{
369 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
370}
371
Eric Laurente1715a42014-05-20 11:30:42 -0700372status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
373 int delayMs)
374{
375 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
376}
377
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800378AudioPolicyService::NotificationClient::NotificationClient(
379 const sp<AudioPolicyService>& service,
380 const sp<media::IAudioPolicyServiceClient>& client,
381 uid_t uid,
382 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800383 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100384 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700385{
386}
387
388AudioPolicyService::NotificationClient::~NotificationClient()
389{
390}
391
392void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
393{
394 sp<NotificationClient> keep(this);
395 sp<AudioPolicyService> service = mService.promote();
396 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800397 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700398 }
399}
400
401void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
402{
Eric Laurente8726fe2015-06-26 09:39:24 -0700403 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700404 mAudioPolicyServiceClient->onAudioPortListUpdate();
405 }
406}
407
408void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
409{
Eric Laurente8726fe2015-06-26 09:39:24 -0700410 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700411 mAudioPolicyServiceClient->onAudioPatchListUpdate();
412 }
413}
Eric Laurent57dae992011-07-24 13:36:09 -0700414
François Gaffiecfe17322018-11-07 13:41:29 +0100415void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
416 int flags)
417{
418 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
419 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
420 }
421}
422
423
Jean-Michel Trivide801052015-04-14 19:10:14 -0700424void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700425 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700426{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700427 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800428 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
429 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800430 }
431}
432
433void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800434 int event,
435 const record_client_info_t *clientInfo,
436 const audio_config_base_t *clientConfig,
437 std::vector<effect_descriptor_t> clientEffects,
438 const audio_config_base_t *deviceConfig,
439 std::vector<effect_descriptor_t> effects,
440 audio_patch_handle_t patchHandle,
441 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800442{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700443 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800444 status_t status = [&]() -> status_t {
445 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
446 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
447 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
448 media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
449 legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig));
450 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
451 convertContainer<std::vector<media::EffectDescriptor>>(
452 clientEffects,
453 legacy2aidl_effect_descriptor_t_EffectDescriptor));
454 media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
455 legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig));
456 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
457 convertContainer<std::vector<media::EffectDescriptor>>(
458 effects,
459 legacy2aidl_effect_descriptor_t_EffectDescriptor));
460 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
461 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
462 media::AudioSourceType sourceAidl = VALUE_OR_RETURN_STATUS(
463 legacy2aidl_audio_source_t_AudioSourceType(source));
464 return aidl_utils::statusTFromBinderStatus(
465 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
466 clientInfoAidl,
467 clientConfigAidl,
468 clientEffectsAidl,
469 deviceConfigAidl,
470 effectsAidl,
471 patchHandleAidl,
472 sourceAidl));
473 }();
474 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700475 }
476}
477
Eric Laurente8726fe2015-06-26 09:39:24 -0700478void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
479{
480 mAudioPortCallbacksEnabled = enabled;
481}
482
François Gaffiecfe17322018-11-07 13:41:29 +0100483void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
484{
485 mAudioVolumeGroupCallbacksEnabled = enabled;
486}
Eric Laurente8726fe2015-06-26 09:39:24 -0700487
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700488void AudioPolicyService::NotificationClient::onRoutingUpdated()
489{
490 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
491 mAudioPolicyServiceClient->onRoutingUpdated();
492 }
493}
494
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700496 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700497 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498}
499
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000500static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000502 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
503}
504
505static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
506{
507 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508}
509
510status_t AudioPolicyService::dumpInternals(int fd)
511{
512 const size_t SIZE = 256;
513 char buffer[SIZE];
514 String8 result;
515
Eric Laurentdce54a12014-03-10 12:19:46 -0700516 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517 result.append(buffer);
518 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
519 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520
Hayden Gomes524159d2019-12-23 14:41:47 -0800521 snprintf(buffer, SIZE, "Supported System Usages:\n");
522 result.append(buffer);
523 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
524 it != mSupportedSystemUsages.end(); ++it) {
525 snprintf(buffer, SIZE, "\t%d\n", *it);
526 result.append(buffer);
527 }
528
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 write(fd, result.string(), result.size());
530 return NO_ERROR;
531}
532
Eric Laurente8c8b432018-10-17 10:08:02 -0700533void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800534{
Eric Laurente8c8b432018-10-17 10:08:02 -0700535 Mutex::Autolock _l(mLock);
536 updateUidStates_l();
537}
538
539void AudioPolicyService::updateUidStates_l()
540{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800541// Go over all active clients and allow capture (does not force silence) in the
542// following cases:
Evan Severson1f700cd2021-02-10 13:10:37 -0800543// The client is the assistant
544// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700545// AND the source is VOICE_RECOGNITION or HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800546// OR uses VOICE_RECOGNITION AND is on TOP
547// OR uses HOTWORD
548// AND there is no active privacy sensitive capture or call
549// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
550// OR The client is an accessibility service
551// AND Is on TOP
552// AND the source is VOICE_RECOGNITION or HOTWORD
553// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700554// AND there is no active privacy sensitive capture or call
555// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800556// AND is on TOP
557// AND the source is VOICE_RECOGNITION or HOTWORD
558// OR the client source is virtual (remote submix, call audio TX or RX...)
559// OR the client source is HOTWORD
560// AND is on TOP
561// OR all active clients are using HOTWORD source
562// AND no call is active
563// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
564// OR the client is the current InputMethodService
565// AND a RTT call is active AND the source is VOICE_RECOGNITION
566// OR Any client
567// AND The assistant is not on TOP
568// AND is on TOP or latest started
569// AND there is no active privacy sensitive capture or call
570// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800571
Eric Laurent4e947da2019-10-17 15:24:06 -0700572
Eric Laurent4eb58f12018-12-07 16:41:02 -0800573 sp<AudioRecordClient> topActive;
574 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800575 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700576 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700577
Eric Laurenta46bedb2018-12-07 18:01:26 -0800578 nsecs_t topStartNs = 0;
579 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800580 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800581 nsecs_t latestSensitiveStartNs = 0;
582 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
583 bool isAssistantOnTop = false;
584 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700585 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800586 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
587 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700588 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700589 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700590 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800591
Michael Groovercfd28302018-12-11 19:16:46 -0800592 // if Sensor Privacy is enabled then all recordings should be silenced.
593 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
594 silenceAllRecordings_l();
595 return;
596 }
597
Eric Laurente8c8b432018-10-17 10:08:02 -0700598 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
599 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000600 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
601 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800602 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700603 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800604 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700605
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700606 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700607 // clients which app is in IDLE state are not eligible for top active or
608 // latest active
609 if (appState == APP_STATE_IDLE) {
610 continue;
611 }
612
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700613 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700614 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800615 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700616 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700617 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800618 bool isPrivacySensitive =
619 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700620
Eric Laurentc21d5692020-02-25 10:24:36 -0800621 if (appState == APP_STATE_TOP) {
622 if (isPrivacySensitive) {
623 if (current->startTimeNs > topSensitiveStartNs) {
624 topSensitiveActive = current;
625 topSensitiveStartNs = current->startTimeNs;
626 }
627 } else {
628 if (current->startTimeNs > topStartNs) {
629 topActive = current;
630 topStartNs = current->startTimeNs;
631 }
632 }
633 if (isAssistant) {
634 isAssistantOnTop = true;
635 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800636 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800637 // Clients capturing for HOTWORD are not considered
638 // for latest active to avoid masking regular clients started before
639 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
640 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
641 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700642 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
643 // is marked latest sensitive active even if another app qualifies.
644 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700645 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700646 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700647 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000648 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700649 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700650 latestSensitiveActiveOrComm = current;
651 latestSensitiveStartNs = current->startTimeNs;
652 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800653 }
654 isSensitiveActive = true;
655 } else {
656 if (current->startTimeNs > latestStartNs) {
657 latestActive = current;
658 latestStartNs = current->startTimeNs;
659 }
660 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800661 }
662 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700663 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
664 onlyHotwordActive = false;
665 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700666 if (currentUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700667 isPhoneStateOwnerActive = true;
668 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800669 }
670
Eric Laurent1ff16a72019-03-14 18:35:04 -0700671 // if no active client with UI on Top, consider latest active as top
672 if (topActive == nullptr) {
673 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800674 topStartNs = latestStartNs;
675 }
676 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700677 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800678 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700679 } else if (latestSensitiveActiveOrComm != nullptr) {
680 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
681 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700682 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000683 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700684 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700685 topSensitiveActive = latestSensitiveActiveOrComm;
686 topSensitiveStartNs = latestSensitiveStartNs;
687 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800688 }
689
690 // If both privacy sensitive and regular capture are active:
691 // if the regular capture is privileged
692 // allow concurrency
693 // else
694 // favor the privacy sensitive case
695 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700696 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800697 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800698 }
699
700 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
701 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700702 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000703 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700704 if (!current->active) {
705 continue;
706 }
707
Eric Laurent4eb58f12018-12-07 16:41:02 -0800708 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700709 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000710 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700711 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000712 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800713
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000714 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700715 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000716 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700717 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700718 bool canCaptureCommunication = recordClient->canCaptureOutput
719 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700720 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700721 return !(isInCall && !canCaptureCall)
722 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800723 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700724
725 // By default allow capture if:
726 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700727 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700728 // AND there is no active privacy sensitive capture or call
729 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
730 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800731 && (isTopOrLatestActive || isTopOrLatestSensitive)
732 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700733 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800734 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800735
Eric Laurented726cc2021-07-01 14:26:41 +0200736 if (!current->hasOp()) {
737 // Never allow capture if app op is denied
738 allowCapture = false;
739 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700740 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
741 allowCapture = true;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700742 } else if (mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700743 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700744 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700745 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700746 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700747 // OR uses HOTWORD
748 // AND there is no active privacy sensitive capture or call
749 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700750 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800751 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700752 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800753 }
754 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700755 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800756 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700757 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800758 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700759 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800760 }
761 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700762 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700763 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700764 // The assistant is not on TOP
765 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700766 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700767 // OR
768 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
769 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700770 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800771 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700772 allowCapture = true;
773 }
Eric Laurent589171c2019-07-25 18:04:29 -0700774 if (isA11yOnTop) {
775 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
776 allowCapture = true;
777 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800778 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700779 } else if (source == AUDIO_SOURCE_HOTWORD) {
780 // For HOTWORD source allow capture when not on TOP if:
781 // All active clients are using HOTWORD source
782 // AND no call is active
783 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800784 if (onlyHotwordActive
785 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700786 allowCapture = true;
787 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700788 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700789 // For current InputMethodService allow capture if:
790 // A RTT call is active AND the source is VOICE_RECOGNITION
791 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
792 allowCapture = true;
793 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800794 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200795 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700796 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700797 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700798 }
799}
800
Michael Groovercfd28302018-12-11 19:16:46 -0800801void AudioPolicyService::silenceAllRecordings_l() {
802 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
803 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700804 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200805 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700806 }
Michael Groovercfd28302018-12-11 19:16:46 -0800807 }
808}
809
Eric Laurente8c8b432018-10-17 10:08:02 -0700810/* static */
811app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700812
813 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700814 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700815 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
816 // include persistent services
817 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700818 }
819 return APP_STATE_FOREGROUND;
820}
821
Eric Laurent4eb58f12018-12-07 16:41:02 -0800822/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800823bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800824{
825 switch (source) {
826 case AUDIO_SOURCE_VOICE_UPLINK:
827 case AUDIO_SOURCE_VOICE_DOWNLINK:
828 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800829 case AUDIO_SOURCE_REMOTE_SUBMIX:
830 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700831 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800832 return true;
833 default:
834 break;
835 }
836 return false;
837}
838
Eric Laurented726cc2021-07-01 14:26:41 +0200839/* static */
840bool AudioPolicyService::isAppOpSource(audio_source_t source)
841{
842 switch (source) {
843 case AUDIO_SOURCE_FM_TUNER:
844 case AUDIO_SOURCE_ECHO_REFERENCE:
845 return false;
846 default:
847 break;
848 }
849 return true;
850}
851
Eric Laurent8c7ef892021-06-10 13:32:16 +0200852void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700853{
854 AutoCallerClear acc;
855
856 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200857 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700858 }
859 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
860 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700861 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +0200862 if (client->silenced != silenced) {
863 if (client->active) {
864 if (silenced) {
865 finishRecording(client->attributionSource, client->attributes.source);
866 } else {
867 std::stringstream msg;
868 msg << "Audio recording un-silenced on session " << client->session;
869 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
870 client->attributes.source)) {
871 silenced = true;
872 }
873 }
874 }
875 af->setRecordSilenced(client->portId, silenced);
876 client->silenced = silenced;
877 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700878 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800879}
880
Glenn Kasten0f11b512014-01-31 16:18:54 -0800881status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882{
Glenn Kasten44deb052012-02-05 18:09:08 -0800883 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 dumpPermissionDenial(fd);
885 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000886 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887 if (!locked) {
888 String8 result(kDeadlockedString);
889 write(fd, result.string(), result.size());
890 }
891
892 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800893 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894 mAudioCommandThread->dump(fd);
895 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896
Eric Laurentdce54a12014-03-10 12:19:46 -0700897 if (mAudioPolicyManager) {
898 mAudioPolicyManager->dump(fd);
899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900
Kevin Rocard8be94972019-02-22 13:26:25 -0800901 mPackageManager.dump(fd);
902
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000903 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 }
905 return NO_ERROR;
906}
907
908status_t AudioPolicyService::dumpPermissionDenial(int fd)
909{
910 const size_t SIZE = 256;
911 char buffer[SIZE];
912 String8 result;
913 snprintf(buffer, SIZE, "Permission Denial: "
914 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
915 IPCThreadState::self()->getCallingPid(),
916 IPCThreadState::self()->getCallingUid());
917 result.append(buffer);
918 write(fd, result.string(), result.size());
919 return NO_ERROR;
920}
921
922status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800923 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800924 // make sure transactions reserved to AudioFlinger do not come from other processes
925 switch (code) {
926 case TRANSACTION_startOutput:
927 case TRANSACTION_stopOutput:
928 case TRANSACTION_releaseOutput:
929 case TRANSACTION_getInputForAttr:
930 case TRANSACTION_startInput:
931 case TRANSACTION_stopInput:
932 case TRANSACTION_releaseInput:
933 case TRANSACTION_getOutputForEffect:
934 case TRANSACTION_registerEffect:
935 case TRANSACTION_unregisterEffect:
936 case TRANSACTION_setEffectEnabled:
937 case TRANSACTION_getStrategyForStream:
938 case TRANSACTION_getOutputForAttr:
939 case TRANSACTION_moveEffectsToIo:
940 ALOGW("%s: transaction %d received from PID %d",
941 __func__, code, IPCThreadState::self()->getCallingPid());
942 return INVALID_OPERATION;
943 default:
944 break;
945 }
946
947 // make sure the following transactions come from system components
948 switch (code) {
949 case TRANSACTION_setDeviceConnectionState:
950 case TRANSACTION_handleDeviceConfigChange:
951 case TRANSACTION_setPhoneState:
952//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
953// case TRANSACTION_setForceUse:
954 case TRANSACTION_initStreamVolume:
955 case TRANSACTION_setStreamVolumeIndex:
956 case TRANSACTION_setVolumeIndexForAttributes:
957 case TRANSACTION_getStreamVolumeIndex:
958 case TRANSACTION_getVolumeIndexForAttributes:
959 case TRANSACTION_getMinVolumeIndexForAttributes:
960 case TRANSACTION_getMaxVolumeIndexForAttributes:
961 case TRANSACTION_isStreamActive:
962 case TRANSACTION_isStreamActiveRemotely:
963 case TRANSACTION_isSourceActive:
964 case TRANSACTION_getDevicesForStream:
965 case TRANSACTION_registerPolicyMixes:
966 case TRANSACTION_setMasterMono:
967 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +0100968 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800969 case TRANSACTION_setSurroundFormatEnabled:
970 case TRANSACTION_setAssistantUid:
971 case TRANSACTION_setA11yServicesUids:
972 case TRANSACTION_setUidDeviceAffinities:
973 case TRANSACTION_removeUidDeviceAffinities:
974 case TRANSACTION_setUserIdDeviceAffinities:
975 case TRANSACTION_removeUserIdDeviceAffinities:
976 case TRANSACTION_getHwOffloadEncodingFormatsSupportedForA2DP:
977 case TRANSACTION_listAudioVolumeGroups:
978 case TRANSACTION_getVolumeGroupFromAudioAttributes:
979 case TRANSACTION_acquireSoundTriggerSession:
980 case TRANSACTION_releaseSoundTriggerSession:
981 case TRANSACTION_setRttEnabled:
982 case TRANSACTION_isCallScreenModeSupported:
983 case TRANSACTION_setDevicesRoleForStrategy:
984 case TRANSACTION_setSupportedSystemUsages:
985 case TRANSACTION_removeDevicesRoleForStrategy:
986 case TRANSACTION_getDevicesForRoleAndStrategy:
987 case TRANSACTION_getDevicesForAttributes:
988 case TRANSACTION_setAllowedCapturePolicy:
989 case TRANSACTION_onNewAudioModulesAvailable:
990 case TRANSACTION_setCurrentImeUid:
991 case TRANSACTION_registerSoundTriggerCaptureStateListener:
992 case TRANSACTION_setDevicesRoleForCapturePreset:
993 case TRANSACTION_addDevicesRoleForCapturePreset:
994 case TRANSACTION_removeDevicesRoleForCapturePreset:
995 case TRANSACTION_clearDevicesRoleForCapturePreset:
996 case TRANSACTION_getDevicesForRoleAndCapturePreset: {
997 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
998 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
999 __func__, code, IPCThreadState::self()->getCallingPid(),
1000 IPCThreadState::self()->getCallingUid());
1001 return INVALID_OPERATION;
1002 }
1003 } break;
1004 default:
1005 break;
1006 }
1007
1008 std::string tag("IAudioPolicyService command " + std::to_string(code));
1009 TimeCheck check(tag.c_str());
1010
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001011 switch (code) {
1012 case SHELL_COMMAND_TRANSACTION: {
1013 int in = data.readFileDescriptor();
1014 int out = data.readFileDescriptor();
1015 int err = data.readFileDescriptor();
1016 int argc = data.readInt32();
1017 Vector<String16> args;
1018 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1019 args.add(data.readString16());
1020 }
1021 sp<IBinder> unusedCallback;
1022 sp<IResultReceiver> resultReceiver;
1023 status_t status;
1024 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1025 return status;
1026 }
1027 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1028 return status;
1029 }
1030 status = shellCommand(in, out, err, args);
1031 if (resultReceiver != nullptr) {
1032 resultReceiver->send(status);
1033 }
1034 return NO_ERROR;
1035 }
1036 }
1037
Mathias Agopian65ab4712010-07-14 17:59:35 -07001038 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1039}
1040
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001041// ------------------- Shell command implementation -------------------
1042
1043// NOTE: This is a remote API - make sure all args are validated
1044status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1045 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1046 return PERMISSION_DENIED;
1047 }
1048 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1049 return BAD_VALUE;
1050 }
jovanakbe066e12019-09-02 11:54:39 -07001051 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001052 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001053 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001054 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001055 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001056 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001057 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1058 purgePermissionCache();
1059 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001060 } else if (args.size() == 1 && args[0] == String16("help")) {
1061 printHelp(out);
1062 return NO_ERROR;
1063 }
1064 printHelp(err);
1065 return BAD_VALUE;
1066}
1067
jovanakbe066e12019-09-02 11:54:39 -07001068static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1069 if (userId < 0) {
1070 ALOGE("Invalid user: %d", userId);
1071 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001072 return BAD_VALUE;
1073 }
jovanakbe066e12019-09-02 11:54:39 -07001074
1075 PermissionController pc;
1076 uid = pc.getPackageUid(packageName, 0);
1077 if (uid <= 0) {
1078 ALOGE("Unknown package: '%s'", String8(packageName).string());
1079 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1080 return BAD_VALUE;
1081 }
1082
1083 uid = multiuser_get_uid(userId, uid);
1084 return NO_ERROR;
1085}
1086
1087status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1088 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1089 if (!(args.size() == 3 || args.size() == 5)) {
1090 printHelp(err);
1091 return BAD_VALUE;
1092 }
1093
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001094 bool active = false;
1095 if (args[2] == String16("active")) {
1096 active = true;
1097 } else if ((args[2] != String16("idle"))) {
1098 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1099 return BAD_VALUE;
1100 }
jovanakbe066e12019-09-02 11:54:39 -07001101
1102 int userId = 0;
1103 if (args.size() >= 5 && args[3] == String16("--user")) {
1104 userId = atoi(String8(args[4]));
1105 }
1106
1107 uid_t uid;
1108 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1109 return BAD_VALUE;
1110 }
1111
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001112 sp<UidPolicy> uidPolicy;
1113 {
1114 Mutex::Autolock _l(mLock);
1115 uidPolicy = mUidPolicy;
1116 }
1117 if (uidPolicy) {
1118 uidPolicy->addOverrideUid(uid, active);
1119 return NO_ERROR;
1120 }
1121 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001122}
1123
1124status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001125 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1126 if (!(args.size() == 2 || args.size() == 4)) {
1127 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001128 return BAD_VALUE;
1129 }
jovanakbe066e12019-09-02 11:54:39 -07001130
1131 int userId = 0;
1132 if (args.size() >= 4 && args[2] == String16("--user")) {
1133 userId = atoi(String8(args[3]));
1134 }
1135
1136 uid_t uid;
1137 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1138 return BAD_VALUE;
1139 }
1140
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001141 sp<UidPolicy> uidPolicy;
1142 {
1143 Mutex::Autolock _l(mLock);
1144 uidPolicy = mUidPolicy;
1145 }
1146 if (uidPolicy) {
1147 uidPolicy->removeOverrideUid(uid);
1148 return NO_ERROR;
1149 }
1150 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001151}
1152
1153status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001154 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1155 if (!(args.size() == 2 || args.size() == 4)) {
1156 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001157 return BAD_VALUE;
1158 }
jovanakbe066e12019-09-02 11:54:39 -07001159
1160 int userId = 0;
1161 if (args.size() >= 4 && args[2] == String16("--user")) {
1162 userId = atoi(String8(args[3]));
1163 }
1164
1165 uid_t uid;
1166 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1167 return BAD_VALUE;
1168 }
1169
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001170 sp<UidPolicy> uidPolicy;
1171 {
1172 Mutex::Autolock _l(mLock);
1173 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001174 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001175 if (uidPolicy) {
1176 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1177 }
1178 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001179}
1180
1181status_t AudioPolicyService::printHelp(int out) {
1182 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001183 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1184 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1185 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001186 " help print this message\n");
1187}
1188
1189// ----------- AudioPolicyService::UidPolicy implementation ----------
1190
1191void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001192 status_t res = mAm.linkToDeath(this);
1193 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001194 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001195 | ActivityManager::UID_OBSERVER_ACTIVE
1196 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001197 ActivityManager::PROCESS_STATE_UNKNOWN,
1198 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001199 if (!res) {
1200 Mutex::Autolock _l(mLock);
1201 mObserverRegistered = true;
1202 } else {
1203 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001204
Steven Moreland2f348142019-07-02 15:59:07 -07001205 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001206 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001207}
1208
1209void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001210 mAm.unlinkToDeath(this);
1211 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001212 Mutex::Autolock _l(mLock);
1213 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001214}
1215
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001216void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1217 Mutex::Autolock _l(mLock);
1218 mCachedUids.clear();
1219 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001220}
1221
Eric Laurente8c8b432018-10-17 10:08:02 -07001222void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001223 bool needToReregister = false;
1224 {
1225 Mutex::Autolock _l(mLock);
1226 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001227 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001228 if (needToReregister) {
1229 // Looks like ActivityManager has died previously, attempt to re-register.
1230 registerSelf();
1231 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001232}
1233
1234bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1235 if (isServiceUid(uid)) return true;
1236 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001237 {
1238 Mutex::Autolock _l(mLock);
1239 auto overrideIter = mOverrideUids.find(uid);
1240 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001241 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001242 }
1243 // In an absense of the ActivityManager, assume everything to be active.
1244 if (!mObserverRegistered) return true;
1245 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001246 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001247 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001248 }
1249 }
1250 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001251 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001252 {
1253 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001254 mCachedUids.insert(std::pair<uid_t,
1255 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1256 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001257 }
1258 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001259}
1260
Eric Laurente8c8b432018-10-17 10:08:02 -07001261int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1262 if (isServiceUid(uid)) {
1263 return ActivityManager::PROCESS_STATE_TOP;
1264 }
1265 checkRegistered();
1266 {
1267 Mutex::Autolock _l(mLock);
1268 auto overrideIter = mOverrideUids.find(uid);
1269 if (overrideIter != mOverrideUids.end()) {
1270 if (overrideIter->second.first) {
1271 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1272 return overrideIter->second.second;
1273 } else {
1274 auto cacheIter = mCachedUids.find(uid);
1275 if (cacheIter != mCachedUids.end()) {
1276 return cacheIter->second.second;
1277 }
1278 }
1279 }
1280 return ActivityManager::PROCESS_STATE_UNKNOWN;
1281 }
1282 // In an absense of the ActivityManager, assume everything to be active.
1283 if (!mObserverRegistered) {
1284 return ActivityManager::PROCESS_STATE_TOP;
1285 }
1286 auto cacheIter = mCachedUids.find(uid);
1287 if (cacheIter != mCachedUids.end()) {
1288 if (cacheIter->second.first) {
1289 return cacheIter->second.second;
1290 } else {
1291 return ActivityManager::PROCESS_STATE_UNKNOWN;
1292 }
1293 }
1294 }
1295 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001296 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001297 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1298 if (active) {
1299 state = am.getUidProcessState(uid, String16("audioserver"));
1300 }
1301 {
1302 Mutex::Autolock _l(mLock);
1303 mCachedUids.insert(std::pair<uid_t,
1304 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1305 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001306
Eric Laurente8c8b432018-10-17 10:08:02 -07001307 return state;
1308}
1309
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001310void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001311 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001312}
1313
1314void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001315 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001316}
1317
1318void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001319 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001320}
1321
Eric Laurente8c8b432018-10-17 10:08:02 -07001322void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1323 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001324 int64_t procStateSeq __unused,
1325 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001326 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1327 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001328 }
1329}
1330
1331void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001332 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1333}
1334
1335void AudioPolicyService::UidPolicy::notifyService() {
1336 sp<AudioPolicyService> service = mService.promote();
1337 if (service != nullptr) {
1338 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001339 }
1340}
1341
Eric Laurente8c8b432018-10-17 10:08:02 -07001342void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1343 std::pair<bool, int>> *uids,
1344 uid_t uid,
1345 bool active,
1346 int state,
1347 bool insert) {
1348 if (isServiceUid(uid)) {
1349 return;
1350 }
1351 bool wasActive = isUidActive(uid);
1352 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001353 {
1354 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001355 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001356 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001357 if (wasActive != isUidActive(uid) || state != previousState) {
1358 notifyService();
1359 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001360}
1361
Eric Laurente8c8b432018-10-17 10:08:02 -07001362void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1363 std::pair<bool, int>> *uids,
1364 uid_t uid,
1365 bool active,
1366 int state,
1367 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001368 auto it = uids->find(uid);
1369 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001370 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001371 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1372 it->second.first = active;
1373 }
1374 if (it->second.first) {
1375 it->second.second = state;
1376 } else {
1377 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1378 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001379 } else {
1380 uids->erase(it);
1381 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001382 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1383 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1384 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001385 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001386}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387
Eric Laurent4eb58f12018-12-07 16:41:02 -08001388bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1389 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001390 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001391 continue;
1392 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001393 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1394 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001395 return true;
1396 }
1397 }
1398 return false;
1399}
1400
Eric Laurentb78763e2018-10-17 10:08:02 -07001401bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1402{
1403 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1404 return it != mA11yUids.end();
1405}
1406
Michael Groovercfd28302018-12-11 19:16:46 -08001407// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1408void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1409 SensorPrivacyManager spm;
1410 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1411 spm.addSensorPrivacyListener(this);
1412}
1413
Evan Severson241d9592021-01-08 12:16:02 -08001414void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
1415 SensorPrivacyManager spm;
1416 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
1417 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
1418 spm.addIndividualSensorPrivacyListener(userId,
1419 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
1420}
1421
Michael Groovercfd28302018-12-11 19:16:46 -08001422void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1423 SensorPrivacyManager spm;
1424 spm.removeSensorPrivacyListener(this);
1425}
1426
1427bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1428 return mSensorPrivacyEnabled;
1429}
1430
1431binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1432 mSensorPrivacyEnabled = enabled;
1433 sp<AudioPolicyService> service = mService.promote();
1434 if (service != nullptr) {
1435 service->updateUidStates();
1436 }
1437 return binder::Status::ok();
1438}
1439
Eric Laurented726cc2021-07-01 14:26:41 +02001440// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1441
1442// static
1443sp<AudioPolicyService::OpRecordAudioMonitor>
1444AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1445 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1446 wp<AudioCommandThread> commandThread)
1447{
Eric Laurent987ce102021-07-05 12:11:51 +02001448 if (isAudioServerOrRootUid(attributionSource.uid)) {
1449 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001450 attributionSource.toString().c_str());
1451 return nullptr;
1452 }
1453
1454 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1455 ALOGD("not monitoring app op for uid %d and source %d",
1456 attributionSource.uid, attr.source);
1457 return nullptr;
1458 }
1459
1460 if (!attributionSource.packageName.has_value()
1461 || attributionSource.packageName.value().size() == 0) {
1462 return nullptr;
1463 }
1464 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1465}
1466
1467AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1468 const AttributionSourceState& attributionSource, int32_t appOp,
1469 wp<AudioCommandThread> commandThread) :
1470 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1471 mCommandThread(commandThread)
1472{
1473}
1474
1475AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1476{
1477 if (mOpCallback != 0) {
1478 mAppOpsManager.stopWatchingMode(mOpCallback);
1479 }
1480 mOpCallback.clear();
1481}
1482
1483void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1484{
1485 checkOp();
1486 mOpCallback = new RecordAudioOpCallback(this);
1487 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1488 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1489 // since it controls the mic permission for legacy apps.
1490 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1491 mAttributionSource.packageName.value_or(""))),
1492 mOpCallback);
1493}
1494
1495bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1496 return mHasOp.load();
1497}
1498
1499// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1500// is updated in AppOp callback and in onFirstRef()
1501// Note this method is never called (and never to be) for audio server / root track
1502// due to the UID in createIfNeeded(). As a result for those record track, it's:
1503// - not called from constructor,
1504// - not called from RecordAudioOpCallback because the callback is not installed in this case
1505void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1506{
1507 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1508 // since it controls the mic permission for legacy apps.
1509 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1510 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1511 mAttributionSource.packageName.value_or(""))));
1512 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1513 // verbose logging only log when appOp changed
1514 ALOGI_IF(hasIt != mHasOp.load(),
1515 "App op %d missing, %ssilencing record %s",
1516 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1517 mHasOp.store(hasIt);
1518
1519 if (updateUidStates) {
1520 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1521 if (commandThread != nullptr) {
1522 commandThread->updateUidStatesCommand();
1523 }
1524 }
1525}
1526
1527AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1528 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1529{ }
1530
1531void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1532 const String16& packageName __unused) {
1533 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1534 if (monitor != NULL) {
1535 if (op != monitor->getOp()) {
1536 return;
1537 }
1538 monitor->checkOp(true);
1539 }
1540}
1541
1542
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1544
Eric Laurentbfb1b832013-01-07 09:53:42 -08001545AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1546 const wp<AudioPolicyService>& service)
1547 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549}
1550
1551
1552AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1553{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001554 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 release_wake_lock(mName.string());
1556 }
1557 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558}
1559
1560void AudioPolicyService::AudioCommandThread::onFirstRef()
1561{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001562 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563}
1564
1565bool AudioPolicyService::AudioCommandThread::threadLoop()
1566{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001567 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568
1569 mLock.lock();
1570 while (!exitPending())
1571 {
Eric Laurent59a89232014-06-08 14:14:17 -07001572 sp<AudioPolicyService> svc;
1573 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 nsecs_t curTime = systemTime();
1575 // commands are sorted by increasing time stamp: execute them from index 0 and up
1576 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001577 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001579 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580
1581 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001583 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001584 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001585 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001586 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001587 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1588 data->mVolume,
1589 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001590 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 }break;
1592 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001593 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001594 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1595 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001596 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001597 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001598 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001599 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001601 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001602 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001603 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001604 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001606 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001608 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001609 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001610 ALOGV("AudioCommandThread() processing stop output portId %d",
1611 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001612 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001613 if (svc == 0) {
1614 break;
1615 }
1616 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001617 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001618 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619 }break;
1620 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001621 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001622 ALOGV("AudioCommandThread() processing release output portId %d",
1623 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001624 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001625 if (svc == 0) {
1626 break;
1627 }
1628 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001629 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001630 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001631 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001632 case CREATE_AUDIO_PATCH: {
1633 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1634 ALOGV("AudioCommandThread() processing create audio patch");
1635 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1636 if (af == 0) {
1637 command->mStatus = PERMISSION_DENIED;
1638 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001639 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001640 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001641 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001642 }
1643 } break;
1644 case RELEASE_AUDIO_PATCH: {
1645 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1646 ALOGV("AudioCommandThread() processing release audio patch");
1647 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1648 if (af == 0) {
1649 command->mStatus = PERMISSION_DENIED;
1650 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001651 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001652 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001653 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001654 }
1655 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001656 case UPDATE_AUDIOPORT_LIST: {
1657 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001658 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001659 if (svc == 0) {
1660 break;
1661 }
1662 mLock.unlock();
1663 svc->doOnAudioPortListUpdate();
1664 mLock.lock();
1665 }break;
1666 case UPDATE_AUDIOPATCH_LIST: {
1667 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001668 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001669 if (svc == 0) {
1670 break;
1671 }
1672 mLock.unlock();
1673 svc->doOnAudioPatchListUpdate();
1674 mLock.lock();
1675 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001676 case CHANGED_AUDIOVOLUMEGROUP: {
1677 AudioVolumeGroupData *data =
1678 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1679 ALOGV("AudioCommandThread() processing update audio volume group");
1680 svc = mService.promote();
1681 if (svc == 0) {
1682 break;
1683 }
1684 mLock.unlock();
1685 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1686 mLock.lock();
1687 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001688 case SET_AUDIOPORT_CONFIG: {
1689 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1690 ALOGV("AudioCommandThread() processing set port config");
1691 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1692 if (af == 0) {
1693 command->mStatus = PERMISSION_DENIED;
1694 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001695 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001696 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001697 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001698 }
1699 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001700 case DYN_POLICY_MIX_STATE_UPDATE: {
1701 DynPolicyMixStateUpdateData *data =
1702 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001703 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1704 data->mRegId.string(), data->mState);
1705 svc = mService.promote();
1706 if (svc == 0) {
1707 break;
1708 }
1709 mLock.unlock();
1710 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1711 mLock.lock();
1712 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001713 case RECORDING_CONFIGURATION_UPDATE: {
1714 RecordingConfigurationUpdateData *data =
1715 (RecordingConfigurationUpdateData *)command->mParam.get();
1716 ALOGV("AudioCommandThread() processing recording configuration update");
1717 svc = mService.promote();
1718 if (svc == 0) {
1719 break;
1720 }
1721 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001722 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001723 &data->mClientConfig, data->mClientEffects,
1724 &data->mDeviceConfig, data->mEffects,
1725 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001726 mLock.lock();
1727 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001728 case SET_EFFECT_SUSPENDED: {
1729 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1730 ALOGV("AudioCommandThread() processing set effect suspended");
1731 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1732 if (af != 0) {
1733 mLock.unlock();
1734 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1735 mLock.lock();
1736 }
1737 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001738 case AUDIO_MODULES_UPDATE: {
1739 ALOGV("AudioCommandThread() processing audio modules update");
1740 svc = mService.promote();
1741 if (svc == 0) {
1742 break;
1743 }
1744 mLock.unlock();
1745 svc->doOnNewAudioModulesAvailable();
1746 mLock.lock();
1747 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001748 case ROUTING_UPDATED: {
1749 ALOGV("AudioCommandThread() processing routing update");
1750 svc = mService.promote();
1751 if (svc == 0) {
1752 break;
1753 }
1754 mLock.unlock();
1755 svc->doOnRoutingUpdated();
1756 mLock.lock();
1757 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001758
Eric Laurented726cc2021-07-01 14:26:41 +02001759 case UPDATE_UID_STATES: {
1760 ALOGV("AudioCommandThread() processing updateUID states");
1761 svc = mService.promote();
1762 if (svc == 0) {
1763 break;
1764 }
1765 mLock.unlock();
1766 svc->updateUidStates();
1767 mLock.lock();
1768 } break;
1769
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001771 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001773 {
1774 Mutex::Autolock _l(command->mLock);
1775 if (command->mWaitStatus) {
1776 command->mWaitStatus = false;
1777 command->mCond.signal();
1778 }
1779 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001780 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001781 // release mLock before releasing strong reference on the service as
1782 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1783 // acquires mLock.
1784 mLock.unlock();
1785 svc.clear();
1786 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 } else {
1788 waitTime = mAudioCommands[0]->mTime - curTime;
1789 break;
1790 }
1791 }
Zach Janga754b4f2015-10-27 01:29:34 +00001792
1793 // release delayed commands wake lock if the queue is empty
1794 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001795 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001796 }
1797
1798 // At this stage we have either an empty command queue or the first command in the queue
1799 // has a finite delay. So unless we are exiting it is safe to wait.
1800 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001801 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001802 if (waitTime == -1) {
1803 mWaitWorkCV.wait(mLock);
1804 } else {
1805 mWaitWorkCV.waitRelative(mLock, waitTime);
1806 }
Eric Laurent59a89232014-06-08 14:14:17 -07001807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001809 // release delayed commands wake lock before quitting
1810 if (!mAudioCommands.isEmpty()) {
1811 release_wake_lock(mName.string());
1812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 mLock.unlock();
1814 return false;
1815}
1816
1817status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1818{
1819 const size_t SIZE = 256;
1820 char buffer[SIZE];
1821 String8 result;
1822
1823 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1824 result.append(buffer);
1825 write(fd, result.string(), result.size());
1826
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001827 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 if (!locked) {
1829 String8 result2(kCmdDeadlockedString);
1830 write(fd, result2.string(), result2.size());
1831 }
1832
1833 snprintf(buffer, SIZE, "- Commands:\n");
1834 result = String8(buffer);
1835 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001836 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 mAudioCommands[i]->dump(buffer, SIZE);
1838 result.append(buffer);
1839 }
1840 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001841 if (mLastCommand != 0) {
1842 mLastCommand->dump(buffer, SIZE);
1843 result.append(buffer);
1844 } else {
1845 result.append(" none\n");
1846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847
1848 write(fd, result.string(), result.size());
1849
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001850 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851
1852 return NO_ERROR;
1853}
1854
Glenn Kastenfff6d712012-01-12 16:38:12 -08001855status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001856 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001857 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001858 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859{
Eric Laurent0ede8922014-05-09 18:04:42 -07001860 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001862 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 data->mStream = stream;
1864 data->mVolume = volume;
1865 data->mIO = output;
1866 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001867 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001868 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001869 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001870 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871}
1872
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001873status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001874 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001875 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876{
Eric Laurent0ede8922014-05-09 18:04:42 -07001877 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001879 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001881 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001883 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001884 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001885 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001886 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887}
1888
1889status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1890{
Eric Laurent0ede8922014-05-09 18:04:42 -07001891 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001893 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 data->mVolume = volume;
1895 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001896 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001897 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001898 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899}
1900
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001901void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1902 audio_session_t sessionId,
1903 bool suspended)
1904{
1905 sp<AudioCommand> command = new AudioCommand();
1906 command->mCommand = SET_EFFECT_SUSPENDED;
1907 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1908 data->mEffectId = effectId;
1909 data->mSessionId = sessionId;
1910 data->mSuspended = suspended;
1911 command->mParam = data;
1912 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1913 effectId, sessionId, suspended);
1914 sendCommand(command);
1915}
1916
1917
Eric Laurentd7fe0862018-07-14 16:48:01 -07001918void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001919{
Eric Laurent0ede8922014-05-09 18:04:42 -07001920 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001921 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001922 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001923 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001924 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001925 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001926 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001927}
1928
Eric Laurentd7fe0862018-07-14 16:48:01 -07001929void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001930{
Eric Laurent0ede8922014-05-09 18:04:42 -07001931 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001933 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001934 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001935 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001936 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001937 sendCommand(command);
1938}
1939
Eric Laurent951f4552014-05-20 10:48:17 -07001940status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1941 const struct audio_patch *patch,
1942 audio_patch_handle_t *handle,
1943 int delayMs)
1944{
1945 status_t status = NO_ERROR;
1946
1947 sp<AudioCommand> command = new AudioCommand();
1948 command->mCommand = CREATE_AUDIO_PATCH;
1949 CreateAudioPatchData *data = new CreateAudioPatchData();
1950 data->mPatch = *patch;
1951 data->mHandle = *handle;
1952 command->mParam = data;
1953 command->mWaitStatus = true;
1954 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1955 status = sendCommand(command, delayMs);
1956 if (status == NO_ERROR) {
1957 *handle = data->mHandle;
1958 }
1959 return status;
1960}
1961
1962status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1963 int delayMs)
1964{
1965 sp<AudioCommand> command = new AudioCommand();
1966 command->mCommand = RELEASE_AUDIO_PATCH;
1967 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1968 data->mHandle = handle;
1969 command->mParam = data;
1970 command->mWaitStatus = true;
1971 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1972 return sendCommand(command, delayMs);
1973}
1974
Eric Laurentb52c1522014-05-20 11:27:36 -07001975void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1976{
1977 sp<AudioCommand> command = new AudioCommand();
1978 command->mCommand = UPDATE_AUDIOPORT_LIST;
1979 ALOGV("AudioCommandThread() adding update audio port list");
1980 sendCommand(command);
1981}
1982
Eric Laurented726cc2021-07-01 14:26:41 +02001983void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
1984{
1985 sp<AudioCommand> command = new AudioCommand();
1986 command->mCommand = UPDATE_UID_STATES;
1987 ALOGV("AudioCommandThread() adding update UID states");
1988 sendCommand(command);
1989}
1990
Eric Laurentb52c1522014-05-20 11:27:36 -07001991void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1992{
1993 sp<AudioCommand>command = new AudioCommand();
1994 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1995 ALOGV("AudioCommandThread() adding update audio patch list");
1996 sendCommand(command);
1997}
1998
François Gaffiecfe17322018-11-07 13:41:29 +01001999void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2000 int flags)
2001{
2002 sp<AudioCommand>command = new AudioCommand();
2003 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2004 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2005 data->mGroup = group;
2006 data->mFlags = flags;
2007 command->mParam = data;
2008 ALOGV("AudioCommandThread() adding audio volume group changed");
2009 sendCommand(command);
2010}
2011
Eric Laurente1715a42014-05-20 11:30:42 -07002012status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2013 const struct audio_port_config *config, int delayMs)
2014{
2015 sp<AudioCommand> command = new AudioCommand();
2016 command->mCommand = SET_AUDIOPORT_CONFIG;
2017 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2018 data->mConfig = *config;
2019 command->mParam = data;
2020 command->mWaitStatus = true;
2021 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2022 return sendCommand(command, delayMs);
2023}
2024
Jean-Michel Trivide801052015-04-14 19:10:14 -07002025void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002026 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002027{
2028 sp<AudioCommand> command = new AudioCommand();
2029 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2030 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2031 data->mRegId = regId;
2032 data->mState = state;
2033 command->mParam = data;
2034 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2035 regId.string(), state);
2036 sendCommand(command);
2037}
2038
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002039void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002040 int event,
2041 const record_client_info_t *clientInfo,
2042 const audio_config_base_t *clientConfig,
2043 std::vector<effect_descriptor_t> clientEffects,
2044 const audio_config_base_t *deviceConfig,
2045 std::vector<effect_descriptor_t> effects,
2046 audio_patch_handle_t patchHandle,
2047 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002048{
2049 sp<AudioCommand>command = new AudioCommand();
2050 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2051 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2052 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002053 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002054 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002055 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002056 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002057 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002058 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002059 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002060 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002061 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2062 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002063 sendCommand(command);
2064}
2065
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002066void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2067{
2068 sp<AudioCommand> command = new AudioCommand();
2069 command->mCommand = AUDIO_MODULES_UPDATE;
2070 sendCommand(command);
2071}
2072
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002073void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2074{
2075 sp<AudioCommand>command = new AudioCommand();
2076 command->mCommand = ROUTING_UPDATED;
2077 ALOGV("AudioCommandThread() adding routing update");
2078 sendCommand(command);
2079}
2080
Eric Laurent0ede8922014-05-09 18:04:42 -07002081status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2082{
2083 {
2084 Mutex::Autolock _l(mLock);
2085 insertCommand_l(command, delayMs);
2086 mWaitWorkCV.signal();
2087 }
2088 Mutex::Autolock _l(command->mLock);
2089 while (command->mWaitStatus) {
2090 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2091 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2092 command->mStatus = TIMED_OUT;
2093 command->mWaitStatus = false;
2094 }
2095 }
2096 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002097}
2098
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002100void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002102 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002103 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 command->mTime = systemTime() + milliseconds(delayMs);
2105
2106 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002107 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2109 }
2110
2111 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002112 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002113 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2115 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002116
2117 // create audio patch or release audio patch commands are equivalent
2118 // with regard to filtering
2119 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2120 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2121 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2122 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2123 continue;
2124 }
2125 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126
2127 switch (command->mCommand) {
2128 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002129 ParametersData *data = (ParametersData *)command->mParam.get();
2130 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002132 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002133 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2135 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2136 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002137 String8 key;
2138 String8 value;
2139 param.getAt(j, key, value);
2140 for (size_t k = 0; k < param2.size(); k++) {
2141 String8 key2;
2142 String8 value2;
2143 param2.getAt(k, key2, value2);
2144 if (key2 == key) {
2145 param2.remove(key2);
2146 ALOGV("Filtering out parameter %s", key2.string());
2147 break;
2148 }
2149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 }
2151 // if all keys have been filtered out, remove the command.
2152 // otherwise, update the key value pairs
2153 if (param2.size() == 0) {
2154 removedCommands.add(command2);
2155 } else {
2156 data2->mKeyValuePairs = param2.toString();
2157 }
Eric Laurent21e54562013-09-23 12:08:05 -07002158 command->mTime = command2->mTime;
2159 // force delayMs to non 0 so that code below does not request to wait for
2160 // command status as the command is now delayed
2161 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002162 } break;
2163
2164 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002165 VolumeData *data = (VolumeData *)command->mParam.get();
2166 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 if (data->mIO != data2->mIO) break;
2168 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002169 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002170 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002172 command->mTime = command2->mTime;
2173 // force delayMs to non 0 so that code below does not request to wait for
2174 // command status as the command is now delayed
2175 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002177
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002178 case SET_VOICE_VOLUME: {
2179 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2180 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2181 ALOGV("Filtering out voice volume command value %f replaced by %f",
2182 data2->mVolume, data->mVolume);
2183 removedCommands.add(command2);
2184 command->mTime = command2->mTime;
2185 // force delayMs to non 0 so that code below does not request to wait for
2186 // command status as the command is now delayed
2187 delayMs = 1;
2188 } break;
2189
Eric Laurente45b48a2014-09-04 16:40:57 -07002190 case CREATE_AUDIO_PATCH:
2191 case RELEASE_AUDIO_PATCH: {
2192 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002193 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002194 if (command->mCommand == CREATE_AUDIO_PATCH) {
2195 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002196 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002197 } else {
2198 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002199 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002200 }
2201 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002202 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002203 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2204 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002205 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002206 } else {
2207 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002208 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002209 }
2210 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002211 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2212 same output. */
2213 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2214 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2215 bool isOutputDiff = false;
2216 if (patch.num_sources == patch2.num_sources) {
2217 for (unsigned count = 0; count < patch.num_sources; count++) {
2218 if (patch.sources[count].id != patch2.sources[count].id) {
2219 isOutputDiff = true;
2220 break;
2221 }
2222 }
2223 if (isOutputDiff)
2224 break;
2225 }
2226 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002227 ALOGV("Filtering out %s audio patch command for handle %d",
2228 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2229 removedCommands.add(command2);
2230 command->mTime = command2->mTime;
2231 // force delayMs to non 0 so that code below does not request to wait for
2232 // command status as the command is now delayed
2233 delayMs = 1;
2234 } break;
2235
Jean-Michel Trivide801052015-04-14 19:10:14 -07002236 case DYN_POLICY_MIX_STATE_UPDATE: {
2237
2238 } break;
2239
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002240 case RECORDING_CONFIGURATION_UPDATE: {
2241
2242 } break;
2243
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002244 case ROUTING_UPDATED: {
2245
2246 } break;
2247
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 default:
2249 break;
2250 }
2251 }
2252
2253 // remove filtered commands
2254 for (size_t j = 0; j < removedCommands.size(); j++) {
2255 // removed commands always have time stamps greater than current command
2256 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002257 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002258 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 mAudioCommands.removeAt(k);
2260 break;
2261 }
2262 }
2263 }
2264 removedCommands.clear();
2265
Eric Laurentaa79bef2015-01-15 14:33:51 -08002266 // Disable wait for status if delay is not 0.
2267 // Except for create audio patch command because the returned patch handle
2268 // is needed by audio policy manager
2269 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002270 command->mWaitStatus = false;
2271 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002272
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002274 ALOGV("inserting command: %d at index %zd, num commands %zu",
2275 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 mAudioCommands.insertAt(command, i + 1);
2277}
2278
2279void AudioPolicyService::AudioCommandThread::exit()
2280{
Steve Block3856b092011-10-20 11:56:00 +01002281 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 {
2283 AutoMutex _l(mLock);
2284 requestExit();
2285 mWaitWorkCV.signal();
2286 }
Zach Janga754b4f2015-10-27 01:29:34 +00002287 // Note that we can call it from the thread loop if all other references have been released
2288 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 requestExitAndWait();
2290}
2291
2292void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2293{
2294 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2295 mCommand,
2296 (int)ns2s(mTime),
2297 (int)ns2ms(mTime)%1000,
2298 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002299 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300}
2301
Dima Zavinfce7a472011-04-19 22:30:36 -07002302/******* helpers for the service_ops callbacks defined below *********/
2303void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2304 const char *keyValuePairs,
2305 int delayMs)
2306{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002307 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002308 delayMs);
2309}
2310
2311int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2312 float volume,
2313 audio_io_handle_t output,
2314 int delayMs)
2315{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002316 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002317 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002318}
2319
Dima Zavinfce7a472011-04-19 22:30:36 -07002320int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2321{
2322 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2323}
2324
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002325void AudioPolicyService::setEffectSuspended(int effectId,
2326 audio_session_t sessionId,
2327 bool suspended)
2328{
2329 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2330}
2331
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002332Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002333{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002334 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002335 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002336}
2337
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002338
Dima Zavinfce7a472011-04-19 22:30:36 -07002339extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002340audio_module_handle_t aps_load_hw_module(void *service __unused,
2341 const char *name);
2342audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002343 audio_devices_t *pDevices,
2344 uint32_t *pSamplingRate,
2345 audio_format_t *pFormat,
2346 audio_channel_mask_t *pChannelMask,
2347 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002348 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002349
Eric Laurent2d388ec2014-03-07 13:25:54 -08002350audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002351 audio_module_handle_t module,
2352 audio_devices_t *pDevices,
2353 uint32_t *pSamplingRate,
2354 audio_format_t *pFormat,
2355 audio_channel_mask_t *pChannelMask,
2356 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002357 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002358 const audio_offload_info_t *offloadInfo);
2359audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002360 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002361 audio_io_handle_t output2);
2362int aps_close_output(void *service __unused, audio_io_handle_t output);
2363int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2364int aps_restore_output(void *service __unused, audio_io_handle_t output);
2365audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002366 audio_devices_t *pDevices,
2367 uint32_t *pSamplingRate,
2368 audio_format_t *pFormat,
2369 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002370 audio_in_acoustics_t acoustics __unused);
2371audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002372 audio_module_handle_t module,
2373 audio_devices_t *pDevices,
2374 uint32_t *pSamplingRate,
2375 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002376 audio_channel_mask_t *pChannelMask);
2377int aps_close_input(void *service __unused, audio_io_handle_t input);
2378int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002379int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002380 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002381 audio_io_handle_t dst_output);
2382char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2383 const char *keys);
2384void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2385 const char *kv_pairs, int delay_ms);
2386int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002387 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002388 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002389int aps_set_voice_volume(void *service, float volume, int delay_ms);
2390};
Dima Zavinfce7a472011-04-19 22:30:36 -07002391
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002392} // namespace android