blob: 90ad81ee2a60cd4bb3e019d168a674cb291127c0 [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 }
bryant_liuba2b4392014-06-11 16:49:30 +0800130 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000131 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
132 sp<UidPolicy> uidPolicy = new UidPolicy(this);
133 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700134 {
135 Mutex::Autolock _l(mLock);
136 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000137 mUidPolicy = uidPolicy;
138 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700139 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000140 uidPolicy->registerSelf();
141 sensorPrivacyPolicy->registerSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700142}
143
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530144void AudioPolicyService::unloadAudioPolicyManager()
145{
146 ALOGV("%s ", __func__);
147 if (mLibraryHandle != nullptr) {
148 dlclose(mLibraryHandle);
149 }
150 mLibraryHandle = nullptr;
151 mCreateAudioPolicyManager = nullptr;
152 mDestroyAudioPolicyManager = nullptr;
153}
154
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155AudioPolicyService::~AudioPolicyService()
156{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700158 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700159
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530160 mDestroyAudioPolicyManager(mAudioPolicyManager);
161 unloadAudioPolicyManager();
162
Eric Laurentdce54a12014-03-10 12:19:46 -0700163 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700164
165 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800166 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800167
168 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800169 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000170
171 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800172 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700173}
174
175// A notification client is always registered by AudioSystem when the client process
176// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800177Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700178{
Eric Laurent12590252015-08-21 18:40:20 -0700179 if (client == 0) {
180 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800181 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700182 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800183 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700184
185 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800186 pid_t pid = IPCThreadState::self()->getCallingPid();
187 int64_t token = ((int64_t)uid<<32) | pid;
188
189 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700190 sp<NotificationClient> notificationClient = new NotificationClient(this,
191 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800192 uid,
193 pid);
194 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700195
luochaojiang908c7d72018-06-21 14:58:04 +0800196 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700197
Marco Nelissenf8880202014-11-14 07:58:25 -0800198 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700199 binder->linkToDeath(notificationClient);
200 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800201 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700202}
203
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800204Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700205{
206 Mutex::Autolock _l(mNotificationClientsLock);
207
208 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800209 pid_t pid = IPCThreadState::self()->getCallingPid();
210 int64_t token = ((int64_t)uid<<32) | pid;
211
212 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800213 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700214 }
luochaojiang908c7d72018-06-21 14:58:04 +0800215 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800216 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700217}
218
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800219Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100220{
221 Mutex::Autolock _l(mNotificationClientsLock);
222
223 uid_t uid = IPCThreadState::self()->getCallingUid();
224 pid_t pid = IPCThreadState::self()->getCallingPid();
225 int64_t token = ((int64_t)uid<<32) | pid;
226
227 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800228 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100229 }
230 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800231 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100232}
233
Eric Laurentb52c1522014-05-20 11:27:36 -0700234// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800235void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700236{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000237 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800238 {
239 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800240 int64_t token = ((int64_t)uid<<32) | pid;
241 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800242 for (size_t i = 0; i < mNotificationClients.size(); i++) {
243 if (mNotificationClients.valueAt(i)->uid() == uid) {
244 hasSameUid = true;
245 break;
246 }
247 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000248 }
249 {
250 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800251 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700252 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700253 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700254 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800255 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700256}
257
258void AudioPolicyService::onAudioPortListUpdate()
259{
260 mOutputCommandThread->updateAudioPortListCommand();
261}
262
263void AudioPolicyService::doOnAudioPortListUpdate()
264{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800265 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700266 for (size_t i = 0; i < mNotificationClients.size(); i++) {
267 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
268 }
269}
270
271void AudioPolicyService::onAudioPatchListUpdate()
272{
273 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274}
275
Eric Laurentb52c1522014-05-20 11:27:36 -0700276void AudioPolicyService::doOnAudioPatchListUpdate()
277{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800278 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700279 for (size_t i = 0; i < mNotificationClients.size(); i++) {
280 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
281 }
282}
283
François Gaffiecfe17322018-11-07 13:41:29 +0100284void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
285{
286 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
287}
288
289void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
290{
291 Mutex::Autolock _l(mNotificationClientsLock);
292 for (size_t i = 0; i < mNotificationClients.size(); i++) {
293 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
294 }
295}
296
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700297void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700298{
299 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
300 regId.string(), state);
301 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
302}
303
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700304void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700305{
306 Mutex::Autolock _l(mNotificationClientsLock);
307 for (size_t i = 0; i < mNotificationClients.size(); i++) {
308 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
309 }
310}
311
Eric Laurenta9f86652018-11-28 17:23:11 -0800312void AudioPolicyService::onRecordingConfigurationUpdate(
313 int event,
314 const record_client_info_t *clientInfo,
315 const audio_config_base_t *clientConfig,
316 std::vector<effect_descriptor_t> clientEffects,
317 const audio_config_base_t *deviceConfig,
318 std::vector<effect_descriptor_t> effects,
319 audio_patch_handle_t patchHandle,
320 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800321{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800322 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800323 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800324}
325
Eric Laurenta9f86652018-11-28 17:23:11 -0800326void AudioPolicyService::doOnRecordingConfigurationUpdate(
327 int event,
328 const record_client_info_t *clientInfo,
329 const audio_config_base_t *clientConfig,
330 std::vector<effect_descriptor_t> clientEffects,
331 const audio_config_base_t *deviceConfig,
332 std::vector<effect_descriptor_t> effects,
333 audio_patch_handle_t patchHandle,
334 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800335{
336 Mutex::Autolock _l(mNotificationClientsLock);
337 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800338 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800339 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800340 }
341}
342
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700343void AudioPolicyService::onRoutingUpdated()
344{
345 mOutputCommandThread->routingChangedCommand();
346}
347
348void AudioPolicyService::doOnRoutingUpdated()
349{
350 Mutex::Autolock _l(mNotificationClientsLock);
351 for (size_t i = 0; i < mNotificationClients.size(); i++) {
352 mNotificationClients.valueAt(i)->onRoutingUpdated();
353 }
354}
355
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800356status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
357 audio_patch_handle_t *handle,
358 int delayMs)
359{
360 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
361}
362
363status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
364 int delayMs)
365{
366 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
367}
368
Eric Laurente1715a42014-05-20 11:30:42 -0700369status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
370 int delayMs)
371{
372 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
373}
374
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800375AudioPolicyService::NotificationClient::NotificationClient(
376 const sp<AudioPolicyService>& service,
377 const sp<media::IAudioPolicyServiceClient>& client,
378 uid_t uid,
379 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800380 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100381 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700382{
383}
384
385AudioPolicyService::NotificationClient::~NotificationClient()
386{
387}
388
389void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
390{
391 sp<NotificationClient> keep(this);
392 sp<AudioPolicyService> service = mService.promote();
393 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800394 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700395 }
396}
397
398void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
399{
Eric Laurente8726fe2015-06-26 09:39:24 -0700400 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700401 mAudioPolicyServiceClient->onAudioPortListUpdate();
402 }
403}
404
405void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
406{
Eric Laurente8726fe2015-06-26 09:39:24 -0700407 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700408 mAudioPolicyServiceClient->onAudioPatchListUpdate();
409 }
410}
Eric Laurent57dae992011-07-24 13:36:09 -0700411
François Gaffiecfe17322018-11-07 13:41:29 +0100412void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
413 int flags)
414{
415 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
416 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
417 }
418}
419
420
Jean-Michel Trivide801052015-04-14 19:10:14 -0700421void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700422 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700423{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700424 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800425 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
426 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800427 }
428}
429
430void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800431 int event,
432 const record_client_info_t *clientInfo,
433 const audio_config_base_t *clientConfig,
434 std::vector<effect_descriptor_t> clientEffects,
435 const audio_config_base_t *deviceConfig,
436 std::vector<effect_descriptor_t> effects,
437 audio_patch_handle_t patchHandle,
438 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800439{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700440 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800441 status_t status = [&]() -> status_t {
442 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
443 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
444 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
445 media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
446 legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig));
447 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
448 convertContainer<std::vector<media::EffectDescriptor>>(
449 clientEffects,
450 legacy2aidl_effect_descriptor_t_EffectDescriptor));
451 media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
452 legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig));
453 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
454 convertContainer<std::vector<media::EffectDescriptor>>(
455 effects,
456 legacy2aidl_effect_descriptor_t_EffectDescriptor));
457 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
458 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
459 media::AudioSourceType sourceAidl = VALUE_OR_RETURN_STATUS(
460 legacy2aidl_audio_source_t_AudioSourceType(source));
461 return aidl_utils::statusTFromBinderStatus(
462 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
463 clientInfoAidl,
464 clientConfigAidl,
465 clientEffectsAidl,
466 deviceConfigAidl,
467 effectsAidl,
468 patchHandleAidl,
469 sourceAidl));
470 }();
471 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700472 }
473}
474
Eric Laurente8726fe2015-06-26 09:39:24 -0700475void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
476{
477 mAudioPortCallbacksEnabled = enabled;
478}
479
François Gaffiecfe17322018-11-07 13:41:29 +0100480void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
481{
482 mAudioVolumeGroupCallbacksEnabled = enabled;
483}
Eric Laurente8726fe2015-06-26 09:39:24 -0700484
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700485void AudioPolicyService::NotificationClient::onRoutingUpdated()
486{
487 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
488 mAudioPolicyServiceClient->onRoutingUpdated();
489 }
490}
491
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700493 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700494 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495}
496
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000497static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000499 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
500}
501
502static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
503{
504 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505}
506
507status_t AudioPolicyService::dumpInternals(int fd)
508{
509 const size_t SIZE = 256;
510 char buffer[SIZE];
511 String8 result;
512
Eric Laurentdce54a12014-03-10 12:19:46 -0700513 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514 result.append(buffer);
515 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
516 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517
Hayden Gomes524159d2019-12-23 14:41:47 -0800518 snprintf(buffer, SIZE, "Supported System Usages:\n");
519 result.append(buffer);
520 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
521 it != mSupportedSystemUsages.end(); ++it) {
522 snprintf(buffer, SIZE, "\t%d\n", *it);
523 result.append(buffer);
524 }
525
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526 write(fd, result.string(), result.size());
527 return NO_ERROR;
528}
529
Eric Laurente8c8b432018-10-17 10:08:02 -0700530void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800531{
Eric Laurente8c8b432018-10-17 10:08:02 -0700532 Mutex::Autolock _l(mLock);
533 updateUidStates_l();
534}
535
536void AudioPolicyService::updateUidStates_l()
537{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800538// Go over all active clients and allow capture (does not force silence) in the
539// following cases:
Evan Severson371c7fe2021-01-20 12:21:41 -0800540// The client source is virtual (remote submix, call audio TX or RX...)
541// OR The user the client is running in has microphone sensor privacy disabled
542// AND The client is the assistant
543// AND an accessibility service is on TOP or a RTT call is active
544// AND the source is VOICE_RECOGNITION or HOTWORD
545// OR uses VOICE_RECOGNITION AND is on TOP
546// OR uses HOTWORD
547// AND there is no active privacy sensitive capture or call
548// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
549// OR The client is an accessibility service
550// AND Is on TOP
551// AND the source is VOICE_RECOGNITION or HOTWORD
552// OR The assistant is not on TOP
553// AND there is no active privacy sensitive capture or call
554// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
555// AND is on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700556// AND the source is VOICE_RECOGNITION or HOTWORD
Evan Severson371c7fe2021-01-20 12:21:41 -0800557// OR the client source is HOTWORD
558// AND is on TOP
559// OR all active clients are using HOTWORD source
560// AND no call is active
561// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
562// OR the client is the current InputMethodService
563// AND a RTT call is active AND the source is VOICE_RECOGNITION
564// OR Any client
565// AND The assistant is not on TOP
566// AND is on TOP or latest started
Eric Laurent589171c2019-07-25 18:04:29 -0700567// AND there is no active privacy sensitive capture or call
568// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800569
Eric Laurent4e947da2019-10-17 15:24:06 -0700570
Eric Laurent4eb58f12018-12-07 16:41:02 -0800571 sp<AudioRecordClient> topActive;
572 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800573 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700574 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700575
Eric Laurenta46bedb2018-12-07 18:01:26 -0800576 nsecs_t topStartNs = 0;
577 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800578 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800579 nsecs_t latestSensitiveStartNs = 0;
580 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
581 bool isAssistantOnTop = false;
582 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700583 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800584 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
585 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700586 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700587 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700588 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800589
Michael Groovercfd28302018-12-11 19:16:46 -0800590 // if Sensor Privacy is enabled then all recordings should be silenced.
591 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
592 silenceAllRecordings_l();
593 return;
594 }
595
Eric Laurente8c8b432018-10-17 10:08:02 -0700596 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
597 sp<AudioRecordClient> current = mAudioRecordClients[i];
Evan Severson371c7fe2021-01-20 12:21:41 -0800598 if (!current->active || (!isVirtualSource(current->attributes.source)
599 && isUserSensorPrivacyEnabledForUid(current->uid))) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700600 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800601 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700602
603 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
604 // clients which app is in IDLE state are not eligible for top active or
605 // latest active
606 if (appState == APP_STATE_IDLE) {
607 continue;
608 }
609
Eric Laurent589171c2019-07-25 18:04:29 -0700610 bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
Eric Laurent14a88632020-07-16 12:28:30 -0700611 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800612 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700613 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800614 bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
615 bool isPrivacySensitive =
616 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700617
Eric Laurentc21d5692020-02-25 10:24:36 -0800618 if (appState == APP_STATE_TOP) {
619 if (isPrivacySensitive) {
620 if (current->startTimeNs > topSensitiveStartNs) {
621 topSensitiveActive = current;
622 topSensitiveStartNs = current->startTimeNs;
623 }
624 } else {
625 if (current->startTimeNs > topStartNs) {
626 topActive = current;
627 topStartNs = current->startTimeNs;
628 }
629 }
630 if (isAssistant) {
631 isAssistantOnTop = true;
632 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800633 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800634 // Clients capturing for HOTWORD are not considered
635 // for latest active to avoid masking regular clients started before
636 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
637 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
638 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700639 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
640 // is marked latest sensitive active even if another app qualifies.
641 if (current->startTimeNs > latestSensitiveStartNs
642 || (isInCommunication && current->uid == mPhoneStateOwnerUid)) {
643 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
644 || latestSensitiveActiveOrComm->uid != mPhoneStateOwnerUid) {
645 latestSensitiveActiveOrComm = current;
646 latestSensitiveStartNs = current->startTimeNs;
647 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800648 }
649 isSensitiveActive = true;
650 } else {
651 if (current->startTimeNs > latestStartNs) {
652 latestActive = current;
653 latestStartNs = current->startTimeNs;
654 }
655 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800656 }
657 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700658 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
659 onlyHotwordActive = false;
660 }
Eric Laurentb809a752020-06-29 09:53:13 -0700661 if (current->uid == mPhoneStateOwnerUid) {
662 isPhoneStateOwnerActive = true;
663 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800664 }
665
Eric Laurent1ff16a72019-03-14 18:35:04 -0700666 // if no active client with UI on Top, consider latest active as top
667 if (topActive == nullptr) {
668 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800669 topStartNs = latestStartNs;
670 }
671 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700672 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800673 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700674 } else if (latestSensitiveActiveOrComm != nullptr) {
675 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
676 // foreground UI in case both are capturing with privacy sensitive flag.
677 if (isInCommunication && latestSensitiveActiveOrComm->uid == mPhoneStateOwnerUid) {
678 topSensitiveActive = latestSensitiveActiveOrComm;
679 topSensitiveStartNs = latestSensitiveStartNs;
680 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800681 }
682
683 // If both privacy sensitive and regular capture are active:
684 // if the regular capture is privileged
685 // allow concurrency
686 // else
687 // favor the privacy sensitive case
688 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700689 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800690 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800691 }
692
693 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
694 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700695 if (!current->active) {
696 continue;
697 }
698
Eric Laurent4eb58f12018-12-07 16:41:02 -0800699 audio_source_t source = current->attributes.source;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700700 bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800701 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ?
702 false : current->uid == topSensitiveActive->uid;
703
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000704 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700705 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700706 bool canCaptureCommunication = recordClient->canCaptureOutput
707 || !isPhoneStateOwnerActive
708 || recordClient->uid == mPhoneStateOwnerUid;
709 return !(isInCall && !canCaptureCall)
710 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800711 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700712
713 // By default allow capture if:
714 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700715 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700716 // AND there is no active privacy sensitive capture or call
717 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
718 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800719 && (isTopOrLatestActive || isTopOrLatestSensitive)
720 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700721 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800722 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800723
724 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700725 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
726 allowCapture = true;
Evan Severson371c7fe2021-01-20 12:21:41 -0800727 } else if (isUserSensorPrivacyEnabledForUid(current->uid)) {
728 // If sensor privacy is enabled, don't allow capture
729 allowCapture = false;
Eric Laurent2dc962b2019-03-01 08:25:25 -0800730 } else if (mUidPolicy->isAssistantUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700731 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700732 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700733 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700734 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700735 // OR uses HOTWORD
736 // AND there is no active privacy sensitive capture or call
737 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700738 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800739 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700740 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800741 }
742 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700743 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800744 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700745 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800746 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700747 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800748 }
749 }
750 } else if (mUidPolicy->isA11yUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700751 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700752 // The assistant is not on TOP
753 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700754 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700755 // OR
756 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
757 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700758 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800759 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700760 allowCapture = true;
761 }
Eric Laurent589171c2019-07-25 18:04:29 -0700762 if (isA11yOnTop) {
763 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
764 allowCapture = true;
765 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800766 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700767 } else if (source == AUDIO_SOURCE_HOTWORD) {
768 // For HOTWORD source allow capture when not on TOP if:
769 // All active clients are using HOTWORD source
770 // AND no call is active
771 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800772 if (onlyHotwordActive
773 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700774 allowCapture = true;
775 }
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700776 } else if (mUidPolicy->isCurrentImeUid(current->uid)) {
777 // For current InputMethodService allow capture if:
778 // A RTT call is active AND the source is VOICE_RECOGNITION
779 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
780 allowCapture = true;
781 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800782 }
Eric Laurent5ada82e2019-08-29 17:53:54 -0700783 setAppState_l(current->portId,
Eric Laurent1ff16a72019-03-14 18:35:04 -0700784 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
785 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700786 }
787}
788
Michael Groovercfd28302018-12-11 19:16:46 -0800789void AudioPolicyService::silenceAllRecordings_l() {
790 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
791 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700792 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700793 setAppState_l(current->portId, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700794 }
Michael Groovercfd28302018-12-11 19:16:46 -0800795 }
796}
797
Eric Laurente8c8b432018-10-17 10:08:02 -0700798/* static */
799app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700800
801 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700802 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700803 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
804 // include persistent services
805 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700806 }
807 return APP_STATE_FOREGROUND;
808}
809
Eric Laurent4eb58f12018-12-07 16:41:02 -0800810/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800811bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800812{
813 switch (source) {
814 case AUDIO_SOURCE_VOICE_UPLINK:
815 case AUDIO_SOURCE_VOICE_DOWNLINK:
816 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800817 case AUDIO_SOURCE_REMOTE_SUBMIX:
818 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700819 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800820 return true;
821 default:
822 break;
823 }
824 return false;
825}
826
Eric Laurent5ada82e2019-08-29 17:53:54 -0700827void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700828{
829 AutoCallerClear acc;
830
831 if (mAudioPolicyManager) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700832 mAudioPolicyManager->setAppState(portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700833 }
834 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
835 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700836 bool silenced = state == APP_STATE_IDLE;
Eric Laurent5ada82e2019-08-29 17:53:54 -0700837 af->setRecordSilenced(portId, silenced);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700838 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800839}
840
Glenn Kasten0f11b512014-01-31 16:18:54 -0800841status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842{
Glenn Kasten44deb052012-02-05 18:09:08 -0800843 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 dumpPermissionDenial(fd);
845 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000846 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 if (!locked) {
848 String8 result(kDeadlockedString);
849 write(fd, result.string(), result.size());
850 }
851
852 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800853 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 mAudioCommandThread->dump(fd);
855 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856
Eric Laurentdce54a12014-03-10 12:19:46 -0700857 if (mAudioPolicyManager) {
858 mAudioPolicyManager->dump(fd);
859 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700860
Kevin Rocard8be94972019-02-22 13:26:25 -0800861 mPackageManager.dump(fd);
862
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000863 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 }
865 return NO_ERROR;
866}
867
868status_t AudioPolicyService::dumpPermissionDenial(int fd)
869{
870 const size_t SIZE = 256;
871 char buffer[SIZE];
872 String8 result;
873 snprintf(buffer, SIZE, "Permission Denial: "
874 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
875 IPCThreadState::self()->getCallingPid(),
876 IPCThreadState::self()->getCallingUid());
877 result.append(buffer);
878 write(fd, result.string(), result.size());
879 return NO_ERROR;
880}
881
882status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800883 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800884 // make sure transactions reserved to AudioFlinger do not come from other processes
885 switch (code) {
886 case TRANSACTION_startOutput:
887 case TRANSACTION_stopOutput:
888 case TRANSACTION_releaseOutput:
889 case TRANSACTION_getInputForAttr:
890 case TRANSACTION_startInput:
891 case TRANSACTION_stopInput:
892 case TRANSACTION_releaseInput:
893 case TRANSACTION_getOutputForEffect:
894 case TRANSACTION_registerEffect:
895 case TRANSACTION_unregisterEffect:
896 case TRANSACTION_setEffectEnabled:
897 case TRANSACTION_getStrategyForStream:
898 case TRANSACTION_getOutputForAttr:
899 case TRANSACTION_moveEffectsToIo:
900 ALOGW("%s: transaction %d received from PID %d",
901 __func__, code, IPCThreadState::self()->getCallingPid());
902 return INVALID_OPERATION;
903 default:
904 break;
905 }
906
907 // make sure the following transactions come from system components
908 switch (code) {
909 case TRANSACTION_setDeviceConnectionState:
910 case TRANSACTION_handleDeviceConfigChange:
911 case TRANSACTION_setPhoneState:
912//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
913// case TRANSACTION_setForceUse:
914 case TRANSACTION_initStreamVolume:
915 case TRANSACTION_setStreamVolumeIndex:
916 case TRANSACTION_setVolumeIndexForAttributes:
917 case TRANSACTION_getStreamVolumeIndex:
918 case TRANSACTION_getVolumeIndexForAttributes:
919 case TRANSACTION_getMinVolumeIndexForAttributes:
920 case TRANSACTION_getMaxVolumeIndexForAttributes:
921 case TRANSACTION_isStreamActive:
922 case TRANSACTION_isStreamActiveRemotely:
923 case TRANSACTION_isSourceActive:
924 case TRANSACTION_getDevicesForStream:
925 case TRANSACTION_registerPolicyMixes:
926 case TRANSACTION_setMasterMono:
927 case TRANSACTION_getSurroundFormats:
928 case TRANSACTION_setSurroundFormatEnabled:
929 case TRANSACTION_setAssistantUid:
930 case TRANSACTION_setA11yServicesUids:
931 case TRANSACTION_setUidDeviceAffinities:
932 case TRANSACTION_removeUidDeviceAffinities:
933 case TRANSACTION_setUserIdDeviceAffinities:
934 case TRANSACTION_removeUserIdDeviceAffinities:
935 case TRANSACTION_getHwOffloadEncodingFormatsSupportedForA2DP:
936 case TRANSACTION_listAudioVolumeGroups:
937 case TRANSACTION_getVolumeGroupFromAudioAttributes:
938 case TRANSACTION_acquireSoundTriggerSession:
939 case TRANSACTION_releaseSoundTriggerSession:
940 case TRANSACTION_setRttEnabled:
941 case TRANSACTION_isCallScreenModeSupported:
942 case TRANSACTION_setDevicesRoleForStrategy:
943 case TRANSACTION_setSupportedSystemUsages:
944 case TRANSACTION_removeDevicesRoleForStrategy:
945 case TRANSACTION_getDevicesForRoleAndStrategy:
946 case TRANSACTION_getDevicesForAttributes:
947 case TRANSACTION_setAllowedCapturePolicy:
948 case TRANSACTION_onNewAudioModulesAvailable:
949 case TRANSACTION_setCurrentImeUid:
950 case TRANSACTION_registerSoundTriggerCaptureStateListener:
951 case TRANSACTION_setDevicesRoleForCapturePreset:
952 case TRANSACTION_addDevicesRoleForCapturePreset:
953 case TRANSACTION_removeDevicesRoleForCapturePreset:
954 case TRANSACTION_clearDevicesRoleForCapturePreset:
955 case TRANSACTION_getDevicesForRoleAndCapturePreset: {
956 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
957 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
958 __func__, code, IPCThreadState::self()->getCallingPid(),
959 IPCThreadState::self()->getCallingUid());
960 return INVALID_OPERATION;
961 }
962 } break;
963 default:
964 break;
965 }
966
967 std::string tag("IAudioPolicyService command " + std::to_string(code));
968 TimeCheck check(tag.c_str());
969
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800970 switch (code) {
971 case SHELL_COMMAND_TRANSACTION: {
972 int in = data.readFileDescriptor();
973 int out = data.readFileDescriptor();
974 int err = data.readFileDescriptor();
975 int argc = data.readInt32();
976 Vector<String16> args;
977 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
978 args.add(data.readString16());
979 }
980 sp<IBinder> unusedCallback;
981 sp<IResultReceiver> resultReceiver;
982 status_t status;
983 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
984 return status;
985 }
986 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
987 return status;
988 }
989 status = shellCommand(in, out, err, args);
990 if (resultReceiver != nullptr) {
991 resultReceiver->send(status);
992 }
993 return NO_ERROR;
994 }
995 }
996
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 return BnAudioPolicyService::onTransact(code, data, reply, flags);
998}
999
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001000// ------------------- Shell command implementation -------------------
1001
1002// NOTE: This is a remote API - make sure all args are validated
1003status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1004 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1005 return PERMISSION_DENIED;
1006 }
1007 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1008 return BAD_VALUE;
1009 }
jovanakbe066e12019-09-02 11:54:39 -07001010 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001011 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001012 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001013 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001014 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001015 return handleGetUidState(args, out, err);
1016 } else if (args.size() == 1 && args[0] == String16("help")) {
1017 printHelp(out);
1018 return NO_ERROR;
1019 }
1020 printHelp(err);
1021 return BAD_VALUE;
1022}
1023
jovanakbe066e12019-09-02 11:54:39 -07001024static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1025 if (userId < 0) {
1026 ALOGE("Invalid user: %d", userId);
1027 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001028 return BAD_VALUE;
1029 }
jovanakbe066e12019-09-02 11:54:39 -07001030
1031 PermissionController pc;
1032 uid = pc.getPackageUid(packageName, 0);
1033 if (uid <= 0) {
1034 ALOGE("Unknown package: '%s'", String8(packageName).string());
1035 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1036 return BAD_VALUE;
1037 }
1038
1039 uid = multiuser_get_uid(userId, uid);
1040 return NO_ERROR;
1041}
1042
1043status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1044 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1045 if (!(args.size() == 3 || args.size() == 5)) {
1046 printHelp(err);
1047 return BAD_VALUE;
1048 }
1049
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001050 bool active = false;
1051 if (args[2] == String16("active")) {
1052 active = true;
1053 } else if ((args[2] != String16("idle"))) {
1054 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1055 return BAD_VALUE;
1056 }
jovanakbe066e12019-09-02 11:54:39 -07001057
1058 int userId = 0;
1059 if (args.size() >= 5 && args[3] == String16("--user")) {
1060 userId = atoi(String8(args[4]));
1061 }
1062
1063 uid_t uid;
1064 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1065 return BAD_VALUE;
1066 }
1067
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001068 sp<UidPolicy> uidPolicy;
1069 {
1070 Mutex::Autolock _l(mLock);
1071 uidPolicy = mUidPolicy;
1072 }
1073 if (uidPolicy) {
1074 uidPolicy->addOverrideUid(uid, active);
1075 return NO_ERROR;
1076 }
1077 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001078}
1079
1080status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001081 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1082 if (!(args.size() == 2 || args.size() == 4)) {
1083 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001084 return BAD_VALUE;
1085 }
jovanakbe066e12019-09-02 11:54:39 -07001086
1087 int userId = 0;
1088 if (args.size() >= 4 && args[2] == String16("--user")) {
1089 userId = atoi(String8(args[3]));
1090 }
1091
1092 uid_t uid;
1093 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1094 return BAD_VALUE;
1095 }
1096
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001097 sp<UidPolicy> uidPolicy;
1098 {
1099 Mutex::Autolock _l(mLock);
1100 uidPolicy = mUidPolicy;
1101 }
1102 if (uidPolicy) {
1103 uidPolicy->removeOverrideUid(uid);
1104 return NO_ERROR;
1105 }
1106 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001107}
1108
1109status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001110 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1111 if (!(args.size() == 2 || args.size() == 4)) {
1112 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001113 return BAD_VALUE;
1114 }
jovanakbe066e12019-09-02 11:54:39 -07001115
1116 int userId = 0;
1117 if (args.size() >= 4 && args[2] == String16("--user")) {
1118 userId = atoi(String8(args[3]));
1119 }
1120
1121 uid_t uid;
1122 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1123 return BAD_VALUE;
1124 }
1125
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001126 sp<UidPolicy> uidPolicy;
1127 {
1128 Mutex::Autolock _l(mLock);
1129 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001130 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001131 if (uidPolicy) {
1132 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1133 }
1134 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001135}
1136
Evan Severson241d9592021-01-08 12:16:02 -08001137bool AudioPolicyService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
1138 userid_t userId = multiuser_get_user_id(uid);
1139 if (mMicrophoneSensorPrivacyPolicies.find(userId) == mMicrophoneSensorPrivacyPolicies.end()) {
1140 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
1141 userPolicy->registerSelfForMicrophoneOnly(userId);
1142 mMicrophoneSensorPrivacyPolicies[userId] = userPolicy;
1143 }
1144 return mMicrophoneSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
1145}
1146
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001147status_t AudioPolicyService::printHelp(int out) {
1148 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001149 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1150 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1151 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001152 " help print this message\n");
1153}
1154
1155// ----------- AudioPolicyService::UidPolicy implementation ----------
1156
1157void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001158 status_t res = mAm.linkToDeath(this);
1159 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001160 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001161 | ActivityManager::UID_OBSERVER_ACTIVE
1162 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001163 ActivityManager::PROCESS_STATE_UNKNOWN,
1164 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001165 if (!res) {
1166 Mutex::Autolock _l(mLock);
1167 mObserverRegistered = true;
1168 } else {
1169 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001170
Steven Moreland2f348142019-07-02 15:59:07 -07001171 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001172 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001173}
1174
1175void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001176 mAm.unlinkToDeath(this);
1177 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001178 Mutex::Autolock _l(mLock);
1179 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001180}
1181
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001182void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1183 Mutex::Autolock _l(mLock);
1184 mCachedUids.clear();
1185 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001186}
1187
Eric Laurente8c8b432018-10-17 10:08:02 -07001188void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001189 bool needToReregister = false;
1190 {
1191 Mutex::Autolock _l(mLock);
1192 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001193 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001194 if (needToReregister) {
1195 // Looks like ActivityManager has died previously, attempt to re-register.
1196 registerSelf();
1197 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001198}
1199
1200bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1201 if (isServiceUid(uid)) return true;
1202 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001203 {
1204 Mutex::Autolock _l(mLock);
1205 auto overrideIter = mOverrideUids.find(uid);
1206 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001207 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001208 }
1209 // In an absense of the ActivityManager, assume everything to be active.
1210 if (!mObserverRegistered) return true;
1211 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001212 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001213 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001214 }
1215 }
1216 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001217 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001218 {
1219 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001220 mCachedUids.insert(std::pair<uid_t,
1221 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1222 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001223 }
1224 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001225}
1226
Eric Laurente8c8b432018-10-17 10:08:02 -07001227int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1228 if (isServiceUid(uid)) {
1229 return ActivityManager::PROCESS_STATE_TOP;
1230 }
1231 checkRegistered();
1232 {
1233 Mutex::Autolock _l(mLock);
1234 auto overrideIter = mOverrideUids.find(uid);
1235 if (overrideIter != mOverrideUids.end()) {
1236 if (overrideIter->second.first) {
1237 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1238 return overrideIter->second.second;
1239 } else {
1240 auto cacheIter = mCachedUids.find(uid);
1241 if (cacheIter != mCachedUids.end()) {
1242 return cacheIter->second.second;
1243 }
1244 }
1245 }
1246 return ActivityManager::PROCESS_STATE_UNKNOWN;
1247 }
1248 // In an absense of the ActivityManager, assume everything to be active.
1249 if (!mObserverRegistered) {
1250 return ActivityManager::PROCESS_STATE_TOP;
1251 }
1252 auto cacheIter = mCachedUids.find(uid);
1253 if (cacheIter != mCachedUids.end()) {
1254 if (cacheIter->second.first) {
1255 return cacheIter->second.second;
1256 } else {
1257 return ActivityManager::PROCESS_STATE_UNKNOWN;
1258 }
1259 }
1260 }
1261 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001262 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001263 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1264 if (active) {
1265 state = am.getUidProcessState(uid, String16("audioserver"));
1266 }
1267 {
1268 Mutex::Autolock _l(mLock);
1269 mCachedUids.insert(std::pair<uid_t,
1270 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1271 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001272
Eric Laurente8c8b432018-10-17 10:08:02 -07001273 return state;
1274}
1275
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001276void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001277 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001278}
1279
1280void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001281 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001282}
1283
1284void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001285 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001286}
1287
Eric Laurente8c8b432018-10-17 10:08:02 -07001288void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1289 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001290 int64_t procStateSeq __unused,
1291 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001292 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1293 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001294 }
1295}
1296
1297void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001298 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1299}
1300
1301void AudioPolicyService::UidPolicy::notifyService() {
1302 sp<AudioPolicyService> service = mService.promote();
1303 if (service != nullptr) {
1304 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001305 }
1306}
1307
Eric Laurente8c8b432018-10-17 10:08:02 -07001308void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1309 std::pair<bool, int>> *uids,
1310 uid_t uid,
1311 bool active,
1312 int state,
1313 bool insert) {
1314 if (isServiceUid(uid)) {
1315 return;
1316 }
1317 bool wasActive = isUidActive(uid);
1318 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001319 {
1320 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001321 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001322 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001323 if (wasActive != isUidActive(uid) || state != previousState) {
1324 notifyService();
1325 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001326}
1327
Eric Laurente8c8b432018-10-17 10:08:02 -07001328void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1329 std::pair<bool, int>> *uids,
1330 uid_t uid,
1331 bool active,
1332 int state,
1333 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001334 auto it = uids->find(uid);
1335 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001336 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001337 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1338 it->second.first = active;
1339 }
1340 if (it->second.first) {
1341 it->second.second = state;
1342 } else {
1343 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1344 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001345 } else {
1346 uids->erase(it);
1347 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001348 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1349 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1350 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001351 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001352}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353
Eric Laurent4eb58f12018-12-07 16:41:02 -08001354bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1355 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001356 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001357 continue;
1358 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001359 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1360 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001361 return true;
1362 }
1363 }
1364 return false;
1365}
1366
Eric Laurentb78763e2018-10-17 10:08:02 -07001367bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1368{
1369 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1370 return it != mA11yUids.end();
1371}
1372
Michael Groovercfd28302018-12-11 19:16:46 -08001373// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1374void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1375 SensorPrivacyManager spm;
1376 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1377 spm.addSensorPrivacyListener(this);
1378}
1379
Evan Severson241d9592021-01-08 12:16:02 -08001380void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
1381 SensorPrivacyManager spm;
1382 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
1383 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
1384 spm.addIndividualSensorPrivacyListener(userId,
1385 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
1386}
1387
Michael Groovercfd28302018-12-11 19:16:46 -08001388void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1389 SensorPrivacyManager spm;
1390 spm.removeSensorPrivacyListener(this);
1391}
1392
1393bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1394 return mSensorPrivacyEnabled;
1395}
1396
1397binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1398 mSensorPrivacyEnabled = enabled;
1399 sp<AudioPolicyService> service = mService.promote();
1400 if (service != nullptr) {
1401 service->updateUidStates();
1402 }
1403 return binder::Status::ok();
1404}
1405
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1407
Eric Laurentbfb1b832013-01-07 09:53:42 -08001408AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1409 const wp<AudioPolicyService>& service)
1410 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412}
1413
1414
1415AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1416{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001417 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418 release_wake_lock(mName.string());
1419 }
1420 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421}
1422
1423void AudioPolicyService::AudioCommandThread::onFirstRef()
1424{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001425 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426}
1427
1428bool AudioPolicyService::AudioCommandThread::threadLoop()
1429{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001430 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431
1432 mLock.lock();
1433 while (!exitPending())
1434 {
Eric Laurent59a89232014-06-08 14:14:17 -07001435 sp<AudioPolicyService> svc;
1436 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 nsecs_t curTime = systemTime();
1438 // commands are sorted by increasing time stamp: execute them from index 0 and up
1439 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001440 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001442 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443
1444 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001446 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001448 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001449 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001450 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1451 data->mVolume,
1452 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001453 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454 }break;
1455 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001456 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001457 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1458 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001459 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001460 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001461 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001462 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001464 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001465 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001466 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001467 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001469 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001471 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001472 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001473 ALOGV("AudioCommandThread() processing stop output portId %d",
1474 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001475 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001476 if (svc == 0) {
1477 break;
1478 }
1479 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001480 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001481 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001482 }break;
1483 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001484 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001485 ALOGV("AudioCommandThread() processing release output portId %d",
1486 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001487 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001488 if (svc == 0) {
1489 break;
1490 }
1491 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001492 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001493 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001494 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001495 case CREATE_AUDIO_PATCH: {
1496 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1497 ALOGV("AudioCommandThread() processing create audio patch");
1498 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1499 if (af == 0) {
1500 command->mStatus = PERMISSION_DENIED;
1501 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001502 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001503 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001504 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001505 }
1506 } break;
1507 case RELEASE_AUDIO_PATCH: {
1508 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1509 ALOGV("AudioCommandThread() processing release audio patch");
1510 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1511 if (af == 0) {
1512 command->mStatus = PERMISSION_DENIED;
1513 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001514 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001515 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001516 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001517 }
1518 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001519 case UPDATE_AUDIOPORT_LIST: {
1520 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001521 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001522 if (svc == 0) {
1523 break;
1524 }
1525 mLock.unlock();
1526 svc->doOnAudioPortListUpdate();
1527 mLock.lock();
1528 }break;
1529 case UPDATE_AUDIOPATCH_LIST: {
1530 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001531 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001532 if (svc == 0) {
1533 break;
1534 }
1535 mLock.unlock();
1536 svc->doOnAudioPatchListUpdate();
1537 mLock.lock();
1538 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001539 case CHANGED_AUDIOVOLUMEGROUP: {
1540 AudioVolumeGroupData *data =
1541 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1542 ALOGV("AudioCommandThread() processing update audio volume group");
1543 svc = mService.promote();
1544 if (svc == 0) {
1545 break;
1546 }
1547 mLock.unlock();
1548 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1549 mLock.lock();
1550 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001551 case SET_AUDIOPORT_CONFIG: {
1552 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1553 ALOGV("AudioCommandThread() processing set port config");
1554 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1555 if (af == 0) {
1556 command->mStatus = PERMISSION_DENIED;
1557 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001558 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001559 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001560 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001561 }
1562 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001563 case DYN_POLICY_MIX_STATE_UPDATE: {
1564 DynPolicyMixStateUpdateData *data =
1565 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001566 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1567 data->mRegId.string(), data->mState);
1568 svc = mService.promote();
1569 if (svc == 0) {
1570 break;
1571 }
1572 mLock.unlock();
1573 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1574 mLock.lock();
1575 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001576 case RECORDING_CONFIGURATION_UPDATE: {
1577 RecordingConfigurationUpdateData *data =
1578 (RecordingConfigurationUpdateData *)command->mParam.get();
1579 ALOGV("AudioCommandThread() processing recording configuration update");
1580 svc = mService.promote();
1581 if (svc == 0) {
1582 break;
1583 }
1584 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001585 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001586 &data->mClientConfig, data->mClientEffects,
1587 &data->mDeviceConfig, data->mEffects,
1588 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001589 mLock.lock();
1590 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001591 case SET_EFFECT_SUSPENDED: {
1592 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1593 ALOGV("AudioCommandThread() processing set effect suspended");
1594 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1595 if (af != 0) {
1596 mLock.unlock();
1597 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1598 mLock.lock();
1599 }
1600 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001601 case AUDIO_MODULES_UPDATE: {
1602 ALOGV("AudioCommandThread() processing audio modules update");
1603 svc = mService.promote();
1604 if (svc == 0) {
1605 break;
1606 }
1607 mLock.unlock();
1608 svc->doOnNewAudioModulesAvailable();
1609 mLock.lock();
1610 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001611 case ROUTING_UPDATED: {
1612 ALOGV("AudioCommandThread() processing routing update");
1613 svc = mService.promote();
1614 if (svc == 0) {
1615 break;
1616 }
1617 mLock.unlock();
1618 svc->doOnRoutingUpdated();
1619 mLock.lock();
1620 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001621
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001623 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001625 {
1626 Mutex::Autolock _l(command->mLock);
1627 if (command->mWaitStatus) {
1628 command->mWaitStatus = false;
1629 command->mCond.signal();
1630 }
1631 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001632 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001633 // release mLock before releasing strong reference on the service as
1634 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1635 // acquires mLock.
1636 mLock.unlock();
1637 svc.clear();
1638 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 } else {
1640 waitTime = mAudioCommands[0]->mTime - curTime;
1641 break;
1642 }
1643 }
Zach Janga754b4f2015-10-27 01:29:34 +00001644
1645 // release delayed commands wake lock if the queue is empty
1646 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001647 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001648 }
1649
1650 // At this stage we have either an empty command queue or the first command in the queue
1651 // has a finite delay. So unless we are exiting it is safe to wait.
1652 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001653 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001654 if (waitTime == -1) {
1655 mWaitWorkCV.wait(mLock);
1656 } else {
1657 mWaitWorkCV.waitRelative(mLock, waitTime);
1658 }
Eric Laurent59a89232014-06-08 14:14:17 -07001659 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001661 // release delayed commands wake lock before quitting
1662 if (!mAudioCommands.isEmpty()) {
1663 release_wake_lock(mName.string());
1664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 mLock.unlock();
1666 return false;
1667}
1668
1669status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1670{
1671 const size_t SIZE = 256;
1672 char buffer[SIZE];
1673 String8 result;
1674
1675 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1676 result.append(buffer);
1677 write(fd, result.string(), result.size());
1678
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001679 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 if (!locked) {
1681 String8 result2(kCmdDeadlockedString);
1682 write(fd, result2.string(), result2.size());
1683 }
1684
1685 snprintf(buffer, SIZE, "- Commands:\n");
1686 result = String8(buffer);
1687 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001688 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 mAudioCommands[i]->dump(buffer, SIZE);
1690 result.append(buffer);
1691 }
1692 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001693 if (mLastCommand != 0) {
1694 mLastCommand->dump(buffer, SIZE);
1695 result.append(buffer);
1696 } else {
1697 result.append(" none\n");
1698 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699
1700 write(fd, result.string(), result.size());
1701
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001702 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703
1704 return NO_ERROR;
1705}
1706
Glenn Kastenfff6d712012-01-12 16:38:12 -08001707status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001708 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001709 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001710 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711{
Eric Laurent0ede8922014-05-09 18:04:42 -07001712 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001714 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 data->mStream = stream;
1716 data->mVolume = volume;
1717 data->mIO = output;
1718 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001719 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001720 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001721 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001722 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723}
1724
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001725status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001726 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001727 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728{
Eric Laurent0ede8922014-05-09 18:04:42 -07001729 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001731 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001733 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001735 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001736 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001737 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001738 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739}
1740
1741status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1742{
Eric Laurent0ede8922014-05-09 18:04:42 -07001743 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001745 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 data->mVolume = volume;
1747 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001748 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001749 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001750 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751}
1752
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001753void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1754 audio_session_t sessionId,
1755 bool suspended)
1756{
1757 sp<AudioCommand> command = new AudioCommand();
1758 command->mCommand = SET_EFFECT_SUSPENDED;
1759 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1760 data->mEffectId = effectId;
1761 data->mSessionId = sessionId;
1762 data->mSuspended = suspended;
1763 command->mParam = data;
1764 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1765 effectId, sessionId, suspended);
1766 sendCommand(command);
1767}
1768
1769
Eric Laurentd7fe0862018-07-14 16:48:01 -07001770void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001771{
Eric Laurent0ede8922014-05-09 18:04:42 -07001772 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001773 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001774 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001775 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001776 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001777 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001778 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001779}
1780
Eric Laurentd7fe0862018-07-14 16:48:01 -07001781void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782{
Eric Laurent0ede8922014-05-09 18:04:42 -07001783 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001784 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001785 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001786 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001787 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001788 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001789 sendCommand(command);
1790}
1791
Eric Laurent951f4552014-05-20 10:48:17 -07001792status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1793 const struct audio_patch *patch,
1794 audio_patch_handle_t *handle,
1795 int delayMs)
1796{
1797 status_t status = NO_ERROR;
1798
1799 sp<AudioCommand> command = new AudioCommand();
1800 command->mCommand = CREATE_AUDIO_PATCH;
1801 CreateAudioPatchData *data = new CreateAudioPatchData();
1802 data->mPatch = *patch;
1803 data->mHandle = *handle;
1804 command->mParam = data;
1805 command->mWaitStatus = true;
1806 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1807 status = sendCommand(command, delayMs);
1808 if (status == NO_ERROR) {
1809 *handle = data->mHandle;
1810 }
1811 return status;
1812}
1813
1814status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1815 int delayMs)
1816{
1817 sp<AudioCommand> command = new AudioCommand();
1818 command->mCommand = RELEASE_AUDIO_PATCH;
1819 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1820 data->mHandle = handle;
1821 command->mParam = data;
1822 command->mWaitStatus = true;
1823 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1824 return sendCommand(command, delayMs);
1825}
1826
Eric Laurentb52c1522014-05-20 11:27:36 -07001827void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1828{
1829 sp<AudioCommand> command = new AudioCommand();
1830 command->mCommand = UPDATE_AUDIOPORT_LIST;
1831 ALOGV("AudioCommandThread() adding update audio port list");
1832 sendCommand(command);
1833}
1834
1835void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1836{
1837 sp<AudioCommand>command = new AudioCommand();
1838 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1839 ALOGV("AudioCommandThread() adding update audio patch list");
1840 sendCommand(command);
1841}
1842
François Gaffiecfe17322018-11-07 13:41:29 +01001843void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1844 int flags)
1845{
1846 sp<AudioCommand>command = new AudioCommand();
1847 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1848 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1849 data->mGroup = group;
1850 data->mFlags = flags;
1851 command->mParam = data;
1852 ALOGV("AudioCommandThread() adding audio volume group changed");
1853 sendCommand(command);
1854}
1855
Eric Laurente1715a42014-05-20 11:30:42 -07001856status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1857 const struct audio_port_config *config, int delayMs)
1858{
1859 sp<AudioCommand> command = new AudioCommand();
1860 command->mCommand = SET_AUDIOPORT_CONFIG;
1861 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1862 data->mConfig = *config;
1863 command->mParam = data;
1864 command->mWaitStatus = true;
1865 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1866 return sendCommand(command, delayMs);
1867}
1868
Jean-Michel Trivide801052015-04-14 19:10:14 -07001869void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001870 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001871{
1872 sp<AudioCommand> command = new AudioCommand();
1873 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1874 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1875 data->mRegId = regId;
1876 data->mState = state;
1877 command->mParam = data;
1878 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1879 regId.string(), state);
1880 sendCommand(command);
1881}
1882
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001883void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001884 int event,
1885 const record_client_info_t *clientInfo,
1886 const audio_config_base_t *clientConfig,
1887 std::vector<effect_descriptor_t> clientEffects,
1888 const audio_config_base_t *deviceConfig,
1889 std::vector<effect_descriptor_t> effects,
1890 audio_patch_handle_t patchHandle,
1891 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001892{
1893 sp<AudioCommand>command = new AudioCommand();
1894 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1895 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1896 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001897 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001898 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001899 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001900 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001901 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001902 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001903 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001904 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001905 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1906 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001907 sendCommand(command);
1908}
1909
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001910void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1911{
1912 sp<AudioCommand> command = new AudioCommand();
1913 command->mCommand = AUDIO_MODULES_UPDATE;
1914 sendCommand(command);
1915}
1916
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001917void AudioPolicyService::AudioCommandThread::routingChangedCommand()
1918{
1919 sp<AudioCommand>command = new AudioCommand();
1920 command->mCommand = ROUTING_UPDATED;
1921 ALOGV("AudioCommandThread() adding routing update");
1922 sendCommand(command);
1923}
1924
Eric Laurent0ede8922014-05-09 18:04:42 -07001925status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1926{
1927 {
1928 Mutex::Autolock _l(mLock);
1929 insertCommand_l(command, delayMs);
1930 mWaitWorkCV.signal();
1931 }
1932 Mutex::Autolock _l(command->mLock);
1933 while (command->mWaitStatus) {
1934 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1935 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1936 command->mStatus = TIMED_OUT;
1937 command->mWaitStatus = false;
1938 }
1939 }
1940 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941}
1942
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001944void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001946 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001947 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 command->mTime = systemTime() + milliseconds(delayMs);
1949
1950 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1953 }
1954
1955 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001956 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001957 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1959 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001960
1961 // create audio patch or release audio patch commands are equivalent
1962 // with regard to filtering
1963 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1964 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1965 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1966 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1967 continue;
1968 }
1969 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970
1971 switch (command->mCommand) {
1972 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001973 ParametersData *data = (ParametersData *)command->mParam.get();
1974 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001976 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001977 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1979 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1980 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001981 String8 key;
1982 String8 value;
1983 param.getAt(j, key, value);
1984 for (size_t k = 0; k < param2.size(); k++) {
1985 String8 key2;
1986 String8 value2;
1987 param2.getAt(k, key2, value2);
1988 if (key2 == key) {
1989 param2.remove(key2);
1990 ALOGV("Filtering out parameter %s", key2.string());
1991 break;
1992 }
1993 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 }
1995 // if all keys have been filtered out, remove the command.
1996 // otherwise, update the key value pairs
1997 if (param2.size() == 0) {
1998 removedCommands.add(command2);
1999 } else {
2000 data2->mKeyValuePairs = param2.toString();
2001 }
Eric Laurent21e54562013-09-23 12:08:05 -07002002 command->mTime = command2->mTime;
2003 // force delayMs to non 0 so that code below does not request to wait for
2004 // command status as the command is now delayed
2005 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 } break;
2007
2008 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002009 VolumeData *data = (VolumeData *)command->mParam.get();
2010 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 if (data->mIO != data2->mIO) break;
2012 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002013 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002014 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002016 command->mTime = command2->mTime;
2017 // force delayMs to non 0 so that code below does not request to wait for
2018 // command status as the command is now delayed
2019 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002021
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002022 case SET_VOICE_VOLUME: {
2023 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2024 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2025 ALOGV("Filtering out voice volume command value %f replaced by %f",
2026 data2->mVolume, data->mVolume);
2027 removedCommands.add(command2);
2028 command->mTime = command2->mTime;
2029 // force delayMs to non 0 so that code below does not request to wait for
2030 // command status as the command is now delayed
2031 delayMs = 1;
2032 } break;
2033
Eric Laurente45b48a2014-09-04 16:40:57 -07002034 case CREATE_AUDIO_PATCH:
2035 case RELEASE_AUDIO_PATCH: {
2036 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002037 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002038 if (command->mCommand == CREATE_AUDIO_PATCH) {
2039 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002040 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002041 } else {
2042 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002043 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002044 }
2045 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002046 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002047 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2048 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002049 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002050 } else {
2051 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002052 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002053 }
2054 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002055 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2056 same output. */
2057 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2058 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2059 bool isOutputDiff = false;
2060 if (patch.num_sources == patch2.num_sources) {
2061 for (unsigned count = 0; count < patch.num_sources; count++) {
2062 if (patch.sources[count].id != patch2.sources[count].id) {
2063 isOutputDiff = true;
2064 break;
2065 }
2066 }
2067 if (isOutputDiff)
2068 break;
2069 }
2070 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002071 ALOGV("Filtering out %s audio patch command for handle %d",
2072 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2073 removedCommands.add(command2);
2074 command->mTime = command2->mTime;
2075 // force delayMs to non 0 so that code below does not request to wait for
2076 // command status as the command is now delayed
2077 delayMs = 1;
2078 } break;
2079
Jean-Michel Trivide801052015-04-14 19:10:14 -07002080 case DYN_POLICY_MIX_STATE_UPDATE: {
2081
2082 } break;
2083
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002084 case RECORDING_CONFIGURATION_UPDATE: {
2085
2086 } break;
2087
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002088 case ROUTING_UPDATED: {
2089
2090 } break;
2091
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 default:
2093 break;
2094 }
2095 }
2096
2097 // remove filtered commands
2098 for (size_t j = 0; j < removedCommands.size(); j++) {
2099 // removed commands always have time stamps greater than current command
2100 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002101 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002102 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103 mAudioCommands.removeAt(k);
2104 break;
2105 }
2106 }
2107 }
2108 removedCommands.clear();
2109
Eric Laurentaa79bef2015-01-15 14:33:51 -08002110 // Disable wait for status if delay is not 0.
2111 // Except for create audio patch command because the returned patch handle
2112 // is needed by audio policy manager
2113 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002114 command->mWaitStatus = false;
2115 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002116
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002118 ALOGV("inserting command: %d at index %zd, num commands %zu",
2119 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 mAudioCommands.insertAt(command, i + 1);
2121}
2122
2123void AudioPolicyService::AudioCommandThread::exit()
2124{
Steve Block3856b092011-10-20 11:56:00 +01002125 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 {
2127 AutoMutex _l(mLock);
2128 requestExit();
2129 mWaitWorkCV.signal();
2130 }
Zach Janga754b4f2015-10-27 01:29:34 +00002131 // Note that we can call it from the thread loop if all other references have been released
2132 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133 requestExitAndWait();
2134}
2135
2136void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2137{
2138 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2139 mCommand,
2140 (int)ns2s(mTime),
2141 (int)ns2ms(mTime)%1000,
2142 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002143 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144}
2145
Dima Zavinfce7a472011-04-19 22:30:36 -07002146/******* helpers for the service_ops callbacks defined below *********/
2147void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2148 const char *keyValuePairs,
2149 int delayMs)
2150{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002151 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002152 delayMs);
2153}
2154
2155int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2156 float volume,
2157 audio_io_handle_t output,
2158 int delayMs)
2159{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002160 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002161 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002162}
2163
Dima Zavinfce7a472011-04-19 22:30:36 -07002164int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2165{
2166 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2167}
2168
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002169void AudioPolicyService::setEffectSuspended(int effectId,
2170 audio_session_t sessionId,
2171 bool suspended)
2172{
2173 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2174}
2175
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002176Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002177{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002178 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002179 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002180}
2181
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002182
Dima Zavinfce7a472011-04-19 22:30:36 -07002183extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002184audio_module_handle_t aps_load_hw_module(void *service __unused,
2185 const char *name);
2186audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002187 audio_devices_t *pDevices,
2188 uint32_t *pSamplingRate,
2189 audio_format_t *pFormat,
2190 audio_channel_mask_t *pChannelMask,
2191 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002192 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002193
Eric Laurent2d388ec2014-03-07 13:25:54 -08002194audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002195 audio_module_handle_t module,
2196 audio_devices_t *pDevices,
2197 uint32_t *pSamplingRate,
2198 audio_format_t *pFormat,
2199 audio_channel_mask_t *pChannelMask,
2200 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002201 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002202 const audio_offload_info_t *offloadInfo);
2203audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002204 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002205 audio_io_handle_t output2);
2206int aps_close_output(void *service __unused, audio_io_handle_t output);
2207int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2208int aps_restore_output(void *service __unused, audio_io_handle_t output);
2209audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002210 audio_devices_t *pDevices,
2211 uint32_t *pSamplingRate,
2212 audio_format_t *pFormat,
2213 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002214 audio_in_acoustics_t acoustics __unused);
2215audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002216 audio_module_handle_t module,
2217 audio_devices_t *pDevices,
2218 uint32_t *pSamplingRate,
2219 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002220 audio_channel_mask_t *pChannelMask);
2221int aps_close_input(void *service __unused, audio_io_handle_t input);
2222int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002223int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002224 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002225 audio_io_handle_t dst_output);
2226char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2227 const char *keys);
2228void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2229 const char *kv_pairs, int delay_ms);
2230int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002231 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002232 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002233int aps_set_voice_volume(void *service, float volume, int delay_ms);
2234};
Dima Zavinfce7a472011-04-19 22:30:36 -07002235
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002236} // namespace android