blob: 4ce6dc1aca75edf1310118d8b522b37a298b023a [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>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070026
27#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <cutils/properties.h>
31#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080032#include <binder/PermissionController.h>
33#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <utils/String16.h>
35#include <utils/threads.h>
36#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080038#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070039#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080040#include <media/AudioParameter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070041#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080042#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080043#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
Dima Zavin64760242011-05-11 14:15:23 -070045#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070046#include <system/audio_policy.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070047
Mathias Agopian65ab4712010-07-14 17:59:35 -070048namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080049using binder::Status;
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Glenn Kasten8dad0e32012-01-09 08:41:22 -080051static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
52static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Mikhail Naganov959e2d02019-03-28 11:08:19 -070054static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Eric Laurent0ede8922014-05-09 18:04:42 -070056static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010057
Svet Ganovf4ddfef2018-01-16 07:37:58 -080058static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070059
Mathias Agopian65ab4712010-07-14 17:59:35 -070060// ----------------------------------------------------------------------------
61
62AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070063 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070064 mAudioPolicyManager(NULL),
65 mAudioPolicyClient(NULL),
66 mPhoneState(AUDIO_MODE_INVALID),
67 mCaptureStateNotifier(false) {
Eric Laurentf5ada6e2014-10-09 17:49:00 -070068}
69
70void AudioPolicyService::onFirstRef()
71{
Eric Laurent8b1e80b2014-10-07 09:08:47 -070072 {
73 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -080074
Eric Laurent8b1e80b2014-10-07 09:08:47 -070075 // start audio commands thread
76 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
77 // start output activity command thread
78 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -070079
Eric Laurent8b1e80b2014-10-07 09:08:47 -070080 mAudioPolicyClient = new AudioPolicyClient(this);
81 mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -070082 }
bryant_liuba2b4392014-06-11 16:49:30 +080083 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +000084 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
85 sp<UidPolicy> uidPolicy = new UidPolicy(this);
86 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -070087 {
88 Mutex::Autolock _l(mLock);
89 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +000090 mUidPolicy = uidPolicy;
91 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -070092 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +000093 uidPolicy->registerSelf();
94 sensorPrivacyPolicy->registerSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -070095}
96
97AudioPolicyService::~AudioPolicyService()
98{
Mathias Agopian65ab4712010-07-14 17:59:35 -070099 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700100 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700101
Eric Laurentf269b8e2014-06-09 20:01:29 -0700102 destroyAudioPolicyManager(mAudioPolicyManager);
Eric Laurentdce54a12014-03-10 12:19:46 -0700103 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700104
105 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800106 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800107
108 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800109 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000110
111 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800112 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700113}
114
115// A notification client is always registered by AudioSystem when the client process
116// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800117Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700118{
Eric Laurent12590252015-08-21 18:40:20 -0700119 if (client == 0) {
120 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800121 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700122 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800123 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700124
125 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800126 pid_t pid = IPCThreadState::self()->getCallingPid();
127 int64_t token = ((int64_t)uid<<32) | pid;
128
129 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700130 sp<NotificationClient> notificationClient = new NotificationClient(this,
131 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800132 uid,
133 pid);
134 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700135
luochaojiang908c7d72018-06-21 14:58:04 +0800136 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700137
Marco Nelissenf8880202014-11-14 07:58:25 -0800138 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700139 binder->linkToDeath(notificationClient);
140 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800141 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700142}
143
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800144Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700145{
146 Mutex::Autolock _l(mNotificationClientsLock);
147
148 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800149 pid_t pid = IPCThreadState::self()->getCallingPid();
150 int64_t token = ((int64_t)uid<<32) | pid;
151
152 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800153 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700154 }
luochaojiang908c7d72018-06-21 14:58:04 +0800155 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800156 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700157}
158
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800159Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100160{
161 Mutex::Autolock _l(mNotificationClientsLock);
162
163 uid_t uid = IPCThreadState::self()->getCallingUid();
164 pid_t pid = IPCThreadState::self()->getCallingPid();
165 int64_t token = ((int64_t)uid<<32) | pid;
166
167 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800168 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100169 }
170 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800171 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100172}
173
Eric Laurentb52c1522014-05-20 11:27:36 -0700174// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800175void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700176{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000177 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800178 {
179 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800180 int64_t token = ((int64_t)uid<<32) | pid;
181 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800182 for (size_t i = 0; i < mNotificationClients.size(); i++) {
183 if (mNotificationClients.valueAt(i)->uid() == uid) {
184 hasSameUid = true;
185 break;
186 }
187 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000188 }
189 {
190 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800191 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700192 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700193 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700194 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800195 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700196}
197
198void AudioPolicyService::onAudioPortListUpdate()
199{
200 mOutputCommandThread->updateAudioPortListCommand();
201}
202
203void AudioPolicyService::doOnAudioPortListUpdate()
204{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800205 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700206 for (size_t i = 0; i < mNotificationClients.size(); i++) {
207 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
208 }
209}
210
211void AudioPolicyService::onAudioPatchListUpdate()
212{
213 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700214}
215
Eric Laurentb52c1522014-05-20 11:27:36 -0700216void AudioPolicyService::doOnAudioPatchListUpdate()
217{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800218 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700219 for (size_t i = 0; i < mNotificationClients.size(); i++) {
220 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
221 }
222}
223
François Gaffiecfe17322018-11-07 13:41:29 +0100224void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
225{
226 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
227}
228
229void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
230{
231 Mutex::Autolock _l(mNotificationClientsLock);
232 for (size_t i = 0; i < mNotificationClients.size(); i++) {
233 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
234 }
235}
236
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700237void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700238{
239 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
240 regId.string(), state);
241 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
242}
243
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700244void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700245{
246 Mutex::Autolock _l(mNotificationClientsLock);
247 for (size_t i = 0; i < mNotificationClients.size(); i++) {
248 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
249 }
250}
251
Eric Laurenta9f86652018-11-28 17:23:11 -0800252void AudioPolicyService::onRecordingConfigurationUpdate(
253 int event,
254 const record_client_info_t *clientInfo,
255 const audio_config_base_t *clientConfig,
256 std::vector<effect_descriptor_t> clientEffects,
257 const audio_config_base_t *deviceConfig,
258 std::vector<effect_descriptor_t> effects,
259 audio_patch_handle_t patchHandle,
260 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800261{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800262 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800263 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800264}
265
Eric Laurenta9f86652018-11-28 17:23:11 -0800266void AudioPolicyService::doOnRecordingConfigurationUpdate(
267 int event,
268 const record_client_info_t *clientInfo,
269 const audio_config_base_t *clientConfig,
270 std::vector<effect_descriptor_t> clientEffects,
271 const audio_config_base_t *deviceConfig,
272 std::vector<effect_descriptor_t> effects,
273 audio_patch_handle_t patchHandle,
274 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800275{
276 Mutex::Autolock _l(mNotificationClientsLock);
277 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800278 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800279 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800280 }
281}
282
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700283void AudioPolicyService::onRoutingUpdated()
284{
285 mOutputCommandThread->routingChangedCommand();
286}
287
288void AudioPolicyService::doOnRoutingUpdated()
289{
290 Mutex::Autolock _l(mNotificationClientsLock);
291 for (size_t i = 0; i < mNotificationClients.size(); i++) {
292 mNotificationClients.valueAt(i)->onRoutingUpdated();
293 }
294}
295
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800296status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
297 audio_patch_handle_t *handle,
298 int delayMs)
299{
300 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
301}
302
303status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
304 int delayMs)
305{
306 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
307}
308
Eric Laurente1715a42014-05-20 11:30:42 -0700309status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
310 int delayMs)
311{
312 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
313}
314
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800315AudioPolicyService::NotificationClient::NotificationClient(
316 const sp<AudioPolicyService>& service,
317 const sp<media::IAudioPolicyServiceClient>& client,
318 uid_t uid,
319 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800320 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100321 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700322{
323}
324
325AudioPolicyService::NotificationClient::~NotificationClient()
326{
327}
328
329void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
330{
331 sp<NotificationClient> keep(this);
332 sp<AudioPolicyService> service = mService.promote();
333 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800334 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700335 }
336}
337
338void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
339{
Eric Laurente8726fe2015-06-26 09:39:24 -0700340 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700341 mAudioPolicyServiceClient->onAudioPortListUpdate();
342 }
343}
344
345void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
346{
Eric Laurente8726fe2015-06-26 09:39:24 -0700347 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700348 mAudioPolicyServiceClient->onAudioPatchListUpdate();
349 }
350}
Eric Laurent57dae992011-07-24 13:36:09 -0700351
François Gaffiecfe17322018-11-07 13:41:29 +0100352void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
353 int flags)
354{
355 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
356 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
357 }
358}
359
360
Jean-Michel Trivide801052015-04-14 19:10:14 -0700361void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700362 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700363{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700364 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800365 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
366 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800367 }
368}
369
370void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800371 int event,
372 const record_client_info_t *clientInfo,
373 const audio_config_base_t *clientConfig,
374 std::vector<effect_descriptor_t> clientEffects,
375 const audio_config_base_t *deviceConfig,
376 std::vector<effect_descriptor_t> effects,
377 audio_patch_handle_t patchHandle,
378 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800379{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700380 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800381 status_t status = [&]() -> status_t {
382 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
383 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
384 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
385 media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
386 legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig));
387 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
388 convertContainer<std::vector<media::EffectDescriptor>>(
389 clientEffects,
390 legacy2aidl_effect_descriptor_t_EffectDescriptor));
391 media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
392 legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig));
393 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
394 convertContainer<std::vector<media::EffectDescriptor>>(
395 effects,
396 legacy2aidl_effect_descriptor_t_EffectDescriptor));
397 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
398 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
399 media::AudioSourceType sourceAidl = VALUE_OR_RETURN_STATUS(
400 legacy2aidl_audio_source_t_AudioSourceType(source));
401 return aidl_utils::statusTFromBinderStatus(
402 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
403 clientInfoAidl,
404 clientConfigAidl,
405 clientEffectsAidl,
406 deviceConfigAidl,
407 effectsAidl,
408 patchHandleAidl,
409 sourceAidl));
410 }();
411 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700412 }
413}
414
Eric Laurente8726fe2015-06-26 09:39:24 -0700415void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
416{
417 mAudioPortCallbacksEnabled = enabled;
418}
419
François Gaffiecfe17322018-11-07 13:41:29 +0100420void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
421{
422 mAudioVolumeGroupCallbacksEnabled = enabled;
423}
Eric Laurente8726fe2015-06-26 09:39:24 -0700424
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700425void AudioPolicyService::NotificationClient::onRoutingUpdated()
426{
427 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
428 mAudioPolicyServiceClient->onRoutingUpdated();
429 }
430}
431
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700433 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700434 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435}
436
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000437static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000439 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
440}
441
442static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
443{
444 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445}
446
447status_t AudioPolicyService::dumpInternals(int fd)
448{
449 const size_t SIZE = 256;
450 char buffer[SIZE];
451 String8 result;
452
Eric Laurentdce54a12014-03-10 12:19:46 -0700453 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 result.append(buffer);
455 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
456 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457
Hayden Gomes524159d2019-12-23 14:41:47 -0800458 snprintf(buffer, SIZE, "Supported System Usages:\n");
459 result.append(buffer);
460 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
461 it != mSupportedSystemUsages.end(); ++it) {
462 snprintf(buffer, SIZE, "\t%d\n", *it);
463 result.append(buffer);
464 }
465
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 write(fd, result.string(), result.size());
467 return NO_ERROR;
468}
469
Eric Laurente8c8b432018-10-17 10:08:02 -0700470void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800471{
Eric Laurente8c8b432018-10-17 10:08:02 -0700472 Mutex::Autolock _l(mLock);
473 updateUidStates_l();
474}
475
476void AudioPolicyService::updateUidStates_l()
477{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800478// Go over all active clients and allow capture (does not force silence) in the
479// following cases:
Eric Laurent8ed73c12019-08-30 17:25:19 -0700480// The client is the assistant
Eric Laurent6ede98f2019-06-11 14:50:30 -0700481// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700482// AND the source is VOICE_RECOGNITION or HOTWORD
483// OR uses VOICE_RECOGNITION AND is on TOP
484// OR uses HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700485// AND there is no active privacy sensitive capture or call
486// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta46bedb2018-12-07 18:01:26 -0800487// OR The client is an accessibility service
Eric Laurent589171c2019-07-25 18:04:29 -0700488// AND Is on TOP
489// AND the source is VOICE_RECOGNITION or HOTWORD
490// OR The assistant is not on TOP
491// AND there is no active privacy sensitive capture or call
492// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta171e352019-05-07 13:04:45 -0700493// AND is on TOP
Eric Laurenta46bedb2018-12-07 18:01:26 -0800494// AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700495// OR the client source is virtual (remote submix, call audio TX or RX...)
Eric Laurent4e947da2019-10-17 15:24:06 -0700496// OR the client source is HOTWORD
497// AND is on TOP
498// OR all active clients are using HOTWORD source
499// AND no call is active
500// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700501// OR the client is the current InputMethodService
502// AND a RTT call is active AND the source is VOICE_RECOGNITION
Eric Laurenta171e352019-05-07 13:04:45 -0700503// OR Any client
Eric Laurenta46bedb2018-12-07 18:01:26 -0800504// AND The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700505// AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700506// AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700507// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800508
Eric Laurent4e947da2019-10-17 15:24:06 -0700509
Eric Laurent4eb58f12018-12-07 16:41:02 -0800510 sp<AudioRecordClient> topActive;
511 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800512 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700513 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700514
Eric Laurenta46bedb2018-12-07 18:01:26 -0800515 nsecs_t topStartNs = 0;
516 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800517 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800518 nsecs_t latestSensitiveStartNs = 0;
519 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
520 bool isAssistantOnTop = false;
521 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700522 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800523 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
524 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700525 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700526 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700527 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800528
Michael Groovercfd28302018-12-11 19:16:46 -0800529 // if Sensor Privacy is enabled then all recordings should be silenced.
530 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
531 silenceAllRecordings_l();
532 return;
533 }
534
Eric Laurente8c8b432018-10-17 10:08:02 -0700535 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
536 sp<AudioRecordClient> current = mAudioRecordClients[i];
Evan Severson241d9592021-01-08 12:16:02 -0800537 if (!isVirtualSource(current->attributes.source)
538 && isUserSensorPrivacyEnabledForUid(current->uid)) {
539 setAppState_l(current->portId, APP_STATE_IDLE);
540 continue;
541 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700542 if (!current->active) {
543 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800544 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700545
546 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
547 // clients which app is in IDLE state are not eligible for top active or
548 // latest active
549 if (appState == APP_STATE_IDLE) {
550 continue;
551 }
552
Eric Laurent589171c2019-07-25 18:04:29 -0700553 bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
Eric Laurent14a88632020-07-16 12:28:30 -0700554 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800555 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700556 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800557 bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
558 bool isPrivacySensitive =
559 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700560
Eric Laurentc21d5692020-02-25 10:24:36 -0800561 if (appState == APP_STATE_TOP) {
562 if (isPrivacySensitive) {
563 if (current->startTimeNs > topSensitiveStartNs) {
564 topSensitiveActive = current;
565 topSensitiveStartNs = current->startTimeNs;
566 }
567 } else {
568 if (current->startTimeNs > topStartNs) {
569 topActive = current;
570 topStartNs = current->startTimeNs;
571 }
572 }
573 if (isAssistant) {
574 isAssistantOnTop = true;
575 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800576 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800577 // Clients capturing for HOTWORD are not considered
578 // for latest active to avoid masking regular clients started before
579 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
580 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
581 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700582 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
583 // is marked latest sensitive active even if another app qualifies.
584 if (current->startTimeNs > latestSensitiveStartNs
585 || (isInCommunication && current->uid == mPhoneStateOwnerUid)) {
586 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
587 || latestSensitiveActiveOrComm->uid != mPhoneStateOwnerUid) {
588 latestSensitiveActiveOrComm = current;
589 latestSensitiveStartNs = current->startTimeNs;
590 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800591 }
592 isSensitiveActive = true;
593 } else {
594 if (current->startTimeNs > latestStartNs) {
595 latestActive = current;
596 latestStartNs = current->startTimeNs;
597 }
598 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800599 }
600 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700601 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
602 onlyHotwordActive = false;
603 }
Eric Laurentb809a752020-06-29 09:53:13 -0700604 if (current->uid == mPhoneStateOwnerUid) {
605 isPhoneStateOwnerActive = true;
606 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800607 }
608
Eric Laurent1ff16a72019-03-14 18:35:04 -0700609 // if no active client with UI on Top, consider latest active as top
610 if (topActive == nullptr) {
611 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800612 topStartNs = latestStartNs;
613 }
614 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700615 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800616 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700617 } else if (latestSensitiveActiveOrComm != nullptr) {
618 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
619 // foreground UI in case both are capturing with privacy sensitive flag.
620 if (isInCommunication && latestSensitiveActiveOrComm->uid == mPhoneStateOwnerUid) {
621 topSensitiveActive = latestSensitiveActiveOrComm;
622 topSensitiveStartNs = latestSensitiveStartNs;
623 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800624 }
625
626 // If both privacy sensitive and regular capture are active:
627 // if the regular capture is privileged
628 // allow concurrency
629 // else
630 // favor the privacy sensitive case
631 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700632 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800633 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800634 }
635
636 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
637 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700638 if (!current->active) {
639 continue;
640 }
641
Eric Laurent4eb58f12018-12-07 16:41:02 -0800642 audio_source_t source = current->attributes.source;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700643 bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800644 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ?
645 false : current->uid == topSensitiveActive->uid;
646
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000647 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700648 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700649 bool canCaptureCommunication = recordClient->canCaptureOutput
650 || !isPhoneStateOwnerActive
651 || recordClient->uid == mPhoneStateOwnerUid;
652 return !(isInCall && !canCaptureCall)
653 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800654 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700655
656 // By default allow capture if:
657 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700658 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700659 // AND there is no active privacy sensitive capture or call
660 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
661 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800662 && (isTopOrLatestActive || isTopOrLatestSensitive)
663 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700664 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800665 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800666
667 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700668 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
669 allowCapture = true;
Eric Laurent2dc962b2019-03-01 08:25:25 -0800670 } else if (mUidPolicy->isAssistantUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700671 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700672 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700673 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700674 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700675 // OR uses HOTWORD
676 // AND there is no active privacy sensitive capture or call
677 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700678 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800679 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700680 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800681 }
682 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700683 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800684 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700685 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800686 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700687 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800688 }
689 }
690 } else if (mUidPolicy->isA11yUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700691 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700692 // The assistant is not on TOP
693 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700694 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700695 // OR
696 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
697 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700698 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800699 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700700 allowCapture = true;
701 }
Eric Laurent589171c2019-07-25 18:04:29 -0700702 if (isA11yOnTop) {
703 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
704 allowCapture = true;
705 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800706 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700707 } else if (source == AUDIO_SOURCE_HOTWORD) {
708 // For HOTWORD source allow capture when not on TOP if:
709 // All active clients are using HOTWORD source
710 // AND no call is active
711 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800712 if (onlyHotwordActive
713 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700714 allowCapture = true;
715 }
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700716 } else if (mUidPolicy->isCurrentImeUid(current->uid)) {
717 // For current InputMethodService allow capture if:
718 // A RTT call is active AND the source is VOICE_RECOGNITION
719 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
720 allowCapture = true;
721 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800722 }
Eric Laurent5ada82e2019-08-29 17:53:54 -0700723 setAppState_l(current->portId,
Eric Laurent1ff16a72019-03-14 18:35:04 -0700724 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
725 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700726 }
727}
728
Michael Groovercfd28302018-12-11 19:16:46 -0800729void AudioPolicyService::silenceAllRecordings_l() {
730 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
731 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700732 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700733 setAppState_l(current->portId, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700734 }
Michael Groovercfd28302018-12-11 19:16:46 -0800735 }
736}
737
Eric Laurente8c8b432018-10-17 10:08:02 -0700738/* static */
739app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700740
741 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700742 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700743 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
744 // include persistent services
745 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700746 }
747 return APP_STATE_FOREGROUND;
748}
749
Eric Laurent4eb58f12018-12-07 16:41:02 -0800750/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800751bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800752{
753 switch (source) {
754 case AUDIO_SOURCE_VOICE_UPLINK:
755 case AUDIO_SOURCE_VOICE_DOWNLINK:
756 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800757 case AUDIO_SOURCE_REMOTE_SUBMIX:
758 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700759 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800760 return true;
761 default:
762 break;
763 }
764 return false;
765}
766
Eric Laurent5ada82e2019-08-29 17:53:54 -0700767void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700768{
769 AutoCallerClear acc;
770
771 if (mAudioPolicyManager) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700772 mAudioPolicyManager->setAppState(portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700773 }
774 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
775 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700776 bool silenced = state == APP_STATE_IDLE;
Eric Laurent5ada82e2019-08-29 17:53:54 -0700777 af->setRecordSilenced(portId, silenced);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700778 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800779}
780
Glenn Kasten0f11b512014-01-31 16:18:54 -0800781status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782{
Glenn Kasten44deb052012-02-05 18:09:08 -0800783 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784 dumpPermissionDenial(fd);
785 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000786 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 if (!locked) {
788 String8 result(kDeadlockedString);
789 write(fd, result.string(), result.size());
790 }
791
792 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800793 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 mAudioCommandThread->dump(fd);
795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796
Eric Laurentdce54a12014-03-10 12:19:46 -0700797 if (mAudioPolicyManager) {
798 mAudioPolicyManager->dump(fd);
799 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800
Kevin Rocard8be94972019-02-22 13:26:25 -0800801 mPackageManager.dump(fd);
802
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000803 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805 return NO_ERROR;
806}
807
808status_t AudioPolicyService::dumpPermissionDenial(int fd)
809{
810 const size_t SIZE = 256;
811 char buffer[SIZE];
812 String8 result;
813 snprintf(buffer, SIZE, "Permission Denial: "
814 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
815 IPCThreadState::self()->getCallingPid(),
816 IPCThreadState::self()->getCallingUid());
817 result.append(buffer);
818 write(fd, result.string(), result.size());
819 return NO_ERROR;
820}
821
822status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800823 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800824 // make sure transactions reserved to AudioFlinger do not come from other processes
825 switch (code) {
826 case TRANSACTION_startOutput:
827 case TRANSACTION_stopOutput:
828 case TRANSACTION_releaseOutput:
829 case TRANSACTION_getInputForAttr:
830 case TRANSACTION_startInput:
831 case TRANSACTION_stopInput:
832 case TRANSACTION_releaseInput:
833 case TRANSACTION_getOutputForEffect:
834 case TRANSACTION_registerEffect:
835 case TRANSACTION_unregisterEffect:
836 case TRANSACTION_setEffectEnabled:
837 case TRANSACTION_getStrategyForStream:
838 case TRANSACTION_getOutputForAttr:
839 case TRANSACTION_moveEffectsToIo:
840 ALOGW("%s: transaction %d received from PID %d",
841 __func__, code, IPCThreadState::self()->getCallingPid());
842 return INVALID_OPERATION;
843 default:
844 break;
845 }
846
847 // make sure the following transactions come from system components
848 switch (code) {
849 case TRANSACTION_setDeviceConnectionState:
850 case TRANSACTION_handleDeviceConfigChange:
851 case TRANSACTION_setPhoneState:
852//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
853// case TRANSACTION_setForceUse:
854 case TRANSACTION_initStreamVolume:
855 case TRANSACTION_setStreamVolumeIndex:
856 case TRANSACTION_setVolumeIndexForAttributes:
857 case TRANSACTION_getStreamVolumeIndex:
858 case TRANSACTION_getVolumeIndexForAttributes:
859 case TRANSACTION_getMinVolumeIndexForAttributes:
860 case TRANSACTION_getMaxVolumeIndexForAttributes:
861 case TRANSACTION_isStreamActive:
862 case TRANSACTION_isStreamActiveRemotely:
863 case TRANSACTION_isSourceActive:
864 case TRANSACTION_getDevicesForStream:
865 case TRANSACTION_registerPolicyMixes:
866 case TRANSACTION_setMasterMono:
867 case TRANSACTION_getSurroundFormats:
868 case TRANSACTION_setSurroundFormatEnabled:
869 case TRANSACTION_setAssistantUid:
870 case TRANSACTION_setA11yServicesUids:
871 case TRANSACTION_setUidDeviceAffinities:
872 case TRANSACTION_removeUidDeviceAffinities:
873 case TRANSACTION_setUserIdDeviceAffinities:
874 case TRANSACTION_removeUserIdDeviceAffinities:
875 case TRANSACTION_getHwOffloadEncodingFormatsSupportedForA2DP:
876 case TRANSACTION_listAudioVolumeGroups:
877 case TRANSACTION_getVolumeGroupFromAudioAttributes:
878 case TRANSACTION_acquireSoundTriggerSession:
879 case TRANSACTION_releaseSoundTriggerSession:
880 case TRANSACTION_setRttEnabled:
881 case TRANSACTION_isCallScreenModeSupported:
882 case TRANSACTION_setDevicesRoleForStrategy:
883 case TRANSACTION_setSupportedSystemUsages:
884 case TRANSACTION_removeDevicesRoleForStrategy:
885 case TRANSACTION_getDevicesForRoleAndStrategy:
886 case TRANSACTION_getDevicesForAttributes:
887 case TRANSACTION_setAllowedCapturePolicy:
888 case TRANSACTION_onNewAudioModulesAvailable:
889 case TRANSACTION_setCurrentImeUid:
890 case TRANSACTION_registerSoundTriggerCaptureStateListener:
891 case TRANSACTION_setDevicesRoleForCapturePreset:
892 case TRANSACTION_addDevicesRoleForCapturePreset:
893 case TRANSACTION_removeDevicesRoleForCapturePreset:
894 case TRANSACTION_clearDevicesRoleForCapturePreset:
895 case TRANSACTION_getDevicesForRoleAndCapturePreset: {
896 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
897 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
898 __func__, code, IPCThreadState::self()->getCallingPid(),
899 IPCThreadState::self()->getCallingUid());
900 return INVALID_OPERATION;
901 }
902 } break;
903 default:
904 break;
905 }
906
907 std::string tag("IAudioPolicyService command " + std::to_string(code));
908 TimeCheck check(tag.c_str());
909
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800910 switch (code) {
911 case SHELL_COMMAND_TRANSACTION: {
912 int in = data.readFileDescriptor();
913 int out = data.readFileDescriptor();
914 int err = data.readFileDescriptor();
915 int argc = data.readInt32();
916 Vector<String16> args;
917 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
918 args.add(data.readString16());
919 }
920 sp<IBinder> unusedCallback;
921 sp<IResultReceiver> resultReceiver;
922 status_t status;
923 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
924 return status;
925 }
926 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
927 return status;
928 }
929 status = shellCommand(in, out, err, args);
930 if (resultReceiver != nullptr) {
931 resultReceiver->send(status);
932 }
933 return NO_ERROR;
934 }
935 }
936
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 return BnAudioPolicyService::onTransact(code, data, reply, flags);
938}
939
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800940// ------------------- Shell command implementation -------------------
941
942// NOTE: This is a remote API - make sure all args are validated
943status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
944 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
945 return PERMISSION_DENIED;
946 }
947 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
948 return BAD_VALUE;
949 }
jovanakbe066e12019-09-02 11:54:39 -0700950 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800951 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700952 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800953 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700954 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800955 return handleGetUidState(args, out, err);
956 } else if (args.size() == 1 && args[0] == String16("help")) {
957 printHelp(out);
958 return NO_ERROR;
959 }
960 printHelp(err);
961 return BAD_VALUE;
962}
963
jovanakbe066e12019-09-02 11:54:39 -0700964static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
965 if (userId < 0) {
966 ALOGE("Invalid user: %d", userId);
967 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800968 return BAD_VALUE;
969 }
jovanakbe066e12019-09-02 11:54:39 -0700970
971 PermissionController pc;
972 uid = pc.getPackageUid(packageName, 0);
973 if (uid <= 0) {
974 ALOGE("Unknown package: '%s'", String8(packageName).string());
975 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
976 return BAD_VALUE;
977 }
978
979 uid = multiuser_get_uid(userId, uid);
980 return NO_ERROR;
981}
982
983status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
984 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
985 if (!(args.size() == 3 || args.size() == 5)) {
986 printHelp(err);
987 return BAD_VALUE;
988 }
989
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800990 bool active = false;
991 if (args[2] == String16("active")) {
992 active = true;
993 } else if ((args[2] != String16("idle"))) {
994 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
995 return BAD_VALUE;
996 }
jovanakbe066e12019-09-02 11:54:39 -0700997
998 int userId = 0;
999 if (args.size() >= 5 && args[3] == String16("--user")) {
1000 userId = atoi(String8(args[4]));
1001 }
1002
1003 uid_t uid;
1004 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1005 return BAD_VALUE;
1006 }
1007
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001008 sp<UidPolicy> uidPolicy;
1009 {
1010 Mutex::Autolock _l(mLock);
1011 uidPolicy = mUidPolicy;
1012 }
1013 if (uidPolicy) {
1014 uidPolicy->addOverrideUid(uid, active);
1015 return NO_ERROR;
1016 }
1017 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001018}
1019
1020status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001021 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1022 if (!(args.size() == 2 || args.size() == 4)) {
1023 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001024 return BAD_VALUE;
1025 }
jovanakbe066e12019-09-02 11:54:39 -07001026
1027 int userId = 0;
1028 if (args.size() >= 4 && args[2] == String16("--user")) {
1029 userId = atoi(String8(args[3]));
1030 }
1031
1032 uid_t uid;
1033 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1034 return BAD_VALUE;
1035 }
1036
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001037 sp<UidPolicy> uidPolicy;
1038 {
1039 Mutex::Autolock _l(mLock);
1040 uidPolicy = mUidPolicy;
1041 }
1042 if (uidPolicy) {
1043 uidPolicy->removeOverrideUid(uid);
1044 return NO_ERROR;
1045 }
1046 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001047}
1048
1049status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001050 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1051 if (!(args.size() == 2 || args.size() == 4)) {
1052 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001053 return BAD_VALUE;
1054 }
jovanakbe066e12019-09-02 11:54:39 -07001055
1056 int userId = 0;
1057 if (args.size() >= 4 && args[2] == String16("--user")) {
1058 userId = atoi(String8(args[3]));
1059 }
1060
1061 uid_t uid;
1062 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1063 return BAD_VALUE;
1064 }
1065
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001066 sp<UidPolicy> uidPolicy;
1067 {
1068 Mutex::Autolock _l(mLock);
1069 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001070 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001071 if (uidPolicy) {
1072 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1073 }
1074 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001075}
1076
Evan Severson241d9592021-01-08 12:16:02 -08001077bool AudioPolicyService::isUserSensorPrivacyEnabledForUid(uid_t uid) {
1078 userid_t userId = multiuser_get_user_id(uid);
1079 if (mMicrophoneSensorPrivacyPolicies.find(userId) == mMicrophoneSensorPrivacyPolicies.end()) {
1080 sp<SensorPrivacyPolicy> userPolicy = new SensorPrivacyPolicy(this);
1081 userPolicy->registerSelfForMicrophoneOnly(userId);
1082 mMicrophoneSensorPrivacyPolicies[userId] = userPolicy;
1083 }
1084 return mMicrophoneSensorPrivacyPolicies[userId]->isSensorPrivacyEnabled();
1085}
1086
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001087status_t AudioPolicyService::printHelp(int out) {
1088 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001089 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1090 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1091 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001092 " help print this message\n");
1093}
1094
1095// ----------- AudioPolicyService::UidPolicy implementation ----------
1096
1097void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001098 status_t res = mAm.linkToDeath(this);
1099 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001100 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001101 | ActivityManager::UID_OBSERVER_ACTIVE
1102 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001103 ActivityManager::PROCESS_STATE_UNKNOWN,
1104 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001105 if (!res) {
1106 Mutex::Autolock _l(mLock);
1107 mObserverRegistered = true;
1108 } else {
1109 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001110
Steven Moreland2f348142019-07-02 15:59:07 -07001111 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001112 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001113}
1114
1115void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001116 mAm.unlinkToDeath(this);
1117 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001118 Mutex::Autolock _l(mLock);
1119 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001120}
1121
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001122void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1123 Mutex::Autolock _l(mLock);
1124 mCachedUids.clear();
1125 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001126}
1127
Eric Laurente8c8b432018-10-17 10:08:02 -07001128void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001129 bool needToReregister = false;
1130 {
1131 Mutex::Autolock _l(mLock);
1132 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001133 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001134 if (needToReregister) {
1135 // Looks like ActivityManager has died previously, attempt to re-register.
1136 registerSelf();
1137 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001138}
1139
1140bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1141 if (isServiceUid(uid)) return true;
1142 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001143 {
1144 Mutex::Autolock _l(mLock);
1145 auto overrideIter = mOverrideUids.find(uid);
1146 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001147 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001148 }
1149 // In an absense of the ActivityManager, assume everything to be active.
1150 if (!mObserverRegistered) return true;
1151 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001152 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001153 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001154 }
1155 }
1156 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001157 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001158 {
1159 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001160 mCachedUids.insert(std::pair<uid_t,
1161 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1162 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001163 }
1164 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001165}
1166
Eric Laurente8c8b432018-10-17 10:08:02 -07001167int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1168 if (isServiceUid(uid)) {
1169 return ActivityManager::PROCESS_STATE_TOP;
1170 }
1171 checkRegistered();
1172 {
1173 Mutex::Autolock _l(mLock);
1174 auto overrideIter = mOverrideUids.find(uid);
1175 if (overrideIter != mOverrideUids.end()) {
1176 if (overrideIter->second.first) {
1177 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1178 return overrideIter->second.second;
1179 } else {
1180 auto cacheIter = mCachedUids.find(uid);
1181 if (cacheIter != mCachedUids.end()) {
1182 return cacheIter->second.second;
1183 }
1184 }
1185 }
1186 return ActivityManager::PROCESS_STATE_UNKNOWN;
1187 }
1188 // In an absense of the ActivityManager, assume everything to be active.
1189 if (!mObserverRegistered) {
1190 return ActivityManager::PROCESS_STATE_TOP;
1191 }
1192 auto cacheIter = mCachedUids.find(uid);
1193 if (cacheIter != mCachedUids.end()) {
1194 if (cacheIter->second.first) {
1195 return cacheIter->second.second;
1196 } else {
1197 return ActivityManager::PROCESS_STATE_UNKNOWN;
1198 }
1199 }
1200 }
1201 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001202 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001203 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1204 if (active) {
1205 state = am.getUidProcessState(uid, String16("audioserver"));
1206 }
1207 {
1208 Mutex::Autolock _l(mLock);
1209 mCachedUids.insert(std::pair<uid_t,
1210 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1211 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001212
Eric Laurente8c8b432018-10-17 10:08:02 -07001213 return state;
1214}
1215
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001216void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001217 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001218}
1219
1220void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001221 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001222}
1223
1224void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001225 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001226}
1227
Eric Laurente8c8b432018-10-17 10:08:02 -07001228void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1229 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001230 int64_t procStateSeq __unused,
1231 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001232 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1233 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001234 }
1235}
1236
1237void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001238 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1239}
1240
1241void AudioPolicyService::UidPolicy::notifyService() {
1242 sp<AudioPolicyService> service = mService.promote();
1243 if (service != nullptr) {
1244 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001245 }
1246}
1247
Eric Laurente8c8b432018-10-17 10:08:02 -07001248void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1249 std::pair<bool, int>> *uids,
1250 uid_t uid,
1251 bool active,
1252 int state,
1253 bool insert) {
1254 if (isServiceUid(uid)) {
1255 return;
1256 }
1257 bool wasActive = isUidActive(uid);
1258 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001259 {
1260 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001261 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001262 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001263 if (wasActive != isUidActive(uid) || state != previousState) {
1264 notifyService();
1265 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001266}
1267
Eric Laurente8c8b432018-10-17 10:08:02 -07001268void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1269 std::pair<bool, int>> *uids,
1270 uid_t uid,
1271 bool active,
1272 int state,
1273 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001274 auto it = uids->find(uid);
1275 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001276 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001277 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1278 it->second.first = active;
1279 }
1280 if (it->second.first) {
1281 it->second.second = state;
1282 } else {
1283 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1284 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001285 } else {
1286 uids->erase(it);
1287 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001288 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1289 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1290 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001291 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001292}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293
Eric Laurent4eb58f12018-12-07 16:41:02 -08001294bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1295 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001296 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001297 continue;
1298 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001299 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1300 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001301 return true;
1302 }
1303 }
1304 return false;
1305}
1306
Eric Laurentb78763e2018-10-17 10:08:02 -07001307bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1308{
1309 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1310 return it != mA11yUids.end();
1311}
1312
Michael Groovercfd28302018-12-11 19:16:46 -08001313// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1314void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1315 SensorPrivacyManager spm;
1316 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1317 spm.addSensorPrivacyListener(this);
1318}
1319
Evan Severson241d9592021-01-08 12:16:02 -08001320void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
1321 SensorPrivacyManager spm;
1322 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
1323 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
1324 spm.addIndividualSensorPrivacyListener(userId,
1325 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
1326}
1327
Michael Groovercfd28302018-12-11 19:16:46 -08001328void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1329 SensorPrivacyManager spm;
1330 spm.removeSensorPrivacyListener(this);
1331}
1332
1333bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1334 return mSensorPrivacyEnabled;
1335}
1336
1337binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1338 mSensorPrivacyEnabled = enabled;
1339 sp<AudioPolicyService> service = mService.promote();
1340 if (service != nullptr) {
1341 service->updateUidStates();
1342 }
1343 return binder::Status::ok();
1344}
1345
Mathias Agopian65ab4712010-07-14 17:59:35 -07001346// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1347
Eric Laurentbfb1b832013-01-07 09:53:42 -08001348AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1349 const wp<AudioPolicyService>& service)
1350 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352}
1353
1354
1355AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1356{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001357 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 release_wake_lock(mName.string());
1359 }
1360 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361}
1362
1363void AudioPolicyService::AudioCommandThread::onFirstRef()
1364{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001365 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366}
1367
1368bool AudioPolicyService::AudioCommandThread::threadLoop()
1369{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001370 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371
1372 mLock.lock();
1373 while (!exitPending())
1374 {
Eric Laurent59a89232014-06-08 14:14:17 -07001375 sp<AudioPolicyService> svc;
1376 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 nsecs_t curTime = systemTime();
1378 // commands are sorted by increasing time stamp: execute them from index 0 and up
1379 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001380 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001382 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383
1384 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001386 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001387 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001388 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001389 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001390 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1391 data->mVolume,
1392 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001393 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394 }break;
1395 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001396 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001397 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1398 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001399 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001400 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001401 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001402 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001404 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001405 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001406 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001407 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001409 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001411 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001412 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001413 ALOGV("AudioCommandThread() processing stop output portId %d",
1414 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001415 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001416 if (svc == 0) {
1417 break;
1418 }
1419 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001420 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001421 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001422 }break;
1423 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001424 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001425 ALOGV("AudioCommandThread() processing release output portId %d",
1426 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001427 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001428 if (svc == 0) {
1429 break;
1430 }
1431 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001432 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001433 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001434 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001435 case CREATE_AUDIO_PATCH: {
1436 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1437 ALOGV("AudioCommandThread() processing create audio patch");
1438 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1439 if (af == 0) {
1440 command->mStatus = PERMISSION_DENIED;
1441 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001442 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001443 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001444 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001445 }
1446 } break;
1447 case RELEASE_AUDIO_PATCH: {
1448 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1449 ALOGV("AudioCommandThread() processing release audio patch");
1450 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1451 if (af == 0) {
1452 command->mStatus = PERMISSION_DENIED;
1453 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001454 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001455 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001456 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001457 }
1458 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001459 case UPDATE_AUDIOPORT_LIST: {
1460 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001461 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001462 if (svc == 0) {
1463 break;
1464 }
1465 mLock.unlock();
1466 svc->doOnAudioPortListUpdate();
1467 mLock.lock();
1468 }break;
1469 case UPDATE_AUDIOPATCH_LIST: {
1470 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001471 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001472 if (svc == 0) {
1473 break;
1474 }
1475 mLock.unlock();
1476 svc->doOnAudioPatchListUpdate();
1477 mLock.lock();
1478 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001479 case CHANGED_AUDIOVOLUMEGROUP: {
1480 AudioVolumeGroupData *data =
1481 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1482 ALOGV("AudioCommandThread() processing update audio volume group");
1483 svc = mService.promote();
1484 if (svc == 0) {
1485 break;
1486 }
1487 mLock.unlock();
1488 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1489 mLock.lock();
1490 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001491 case SET_AUDIOPORT_CONFIG: {
1492 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1493 ALOGV("AudioCommandThread() processing set port config");
1494 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1495 if (af == 0) {
1496 command->mStatus = PERMISSION_DENIED;
1497 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001498 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001499 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001500 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001501 }
1502 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001503 case DYN_POLICY_MIX_STATE_UPDATE: {
1504 DynPolicyMixStateUpdateData *data =
1505 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001506 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1507 data->mRegId.string(), data->mState);
1508 svc = mService.promote();
1509 if (svc == 0) {
1510 break;
1511 }
1512 mLock.unlock();
1513 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1514 mLock.lock();
1515 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001516 case RECORDING_CONFIGURATION_UPDATE: {
1517 RecordingConfigurationUpdateData *data =
1518 (RecordingConfigurationUpdateData *)command->mParam.get();
1519 ALOGV("AudioCommandThread() processing recording configuration update");
1520 svc = mService.promote();
1521 if (svc == 0) {
1522 break;
1523 }
1524 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001525 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001526 &data->mClientConfig, data->mClientEffects,
1527 &data->mDeviceConfig, data->mEffects,
1528 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001529 mLock.lock();
1530 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001531 case SET_EFFECT_SUSPENDED: {
1532 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1533 ALOGV("AudioCommandThread() processing set effect suspended");
1534 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1535 if (af != 0) {
1536 mLock.unlock();
1537 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1538 mLock.lock();
1539 }
1540 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001541 case AUDIO_MODULES_UPDATE: {
1542 ALOGV("AudioCommandThread() processing audio modules update");
1543 svc = mService.promote();
1544 if (svc == 0) {
1545 break;
1546 }
1547 mLock.unlock();
1548 svc->doOnNewAudioModulesAvailable();
1549 mLock.lock();
1550 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001551 case ROUTING_UPDATED: {
1552 ALOGV("AudioCommandThread() processing routing update");
1553 svc = mService.promote();
1554 if (svc == 0) {
1555 break;
1556 }
1557 mLock.unlock();
1558 svc->doOnRoutingUpdated();
1559 mLock.lock();
1560 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001561
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001563 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001565 {
1566 Mutex::Autolock _l(command->mLock);
1567 if (command->mWaitStatus) {
1568 command->mWaitStatus = false;
1569 command->mCond.signal();
1570 }
1571 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001572 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001573 // release mLock before releasing strong reference on the service as
1574 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1575 // acquires mLock.
1576 mLock.unlock();
1577 svc.clear();
1578 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 } else {
1580 waitTime = mAudioCommands[0]->mTime - curTime;
1581 break;
1582 }
1583 }
Zach Janga754b4f2015-10-27 01:29:34 +00001584
1585 // release delayed commands wake lock if the queue is empty
1586 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001587 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001588 }
1589
1590 // At this stage we have either an empty command queue or the first command in the queue
1591 // has a finite delay. So unless we are exiting it is safe to wait.
1592 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001593 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001594 if (waitTime == -1) {
1595 mWaitWorkCV.wait(mLock);
1596 } else {
1597 mWaitWorkCV.waitRelative(mLock, waitTime);
1598 }
Eric Laurent59a89232014-06-08 14:14:17 -07001599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001601 // release delayed commands wake lock before quitting
1602 if (!mAudioCommands.isEmpty()) {
1603 release_wake_lock(mName.string());
1604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 mLock.unlock();
1606 return false;
1607}
1608
1609status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1610{
1611 const size_t SIZE = 256;
1612 char buffer[SIZE];
1613 String8 result;
1614
1615 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1616 result.append(buffer);
1617 write(fd, result.string(), result.size());
1618
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001619 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 if (!locked) {
1621 String8 result2(kCmdDeadlockedString);
1622 write(fd, result2.string(), result2.size());
1623 }
1624
1625 snprintf(buffer, SIZE, "- Commands:\n");
1626 result = String8(buffer);
1627 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001628 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 mAudioCommands[i]->dump(buffer, SIZE);
1630 result.append(buffer);
1631 }
1632 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001633 if (mLastCommand != 0) {
1634 mLastCommand->dump(buffer, SIZE);
1635 result.append(buffer);
1636 } else {
1637 result.append(" none\n");
1638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639
1640 write(fd, result.string(), result.size());
1641
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001642 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643
1644 return NO_ERROR;
1645}
1646
Glenn Kastenfff6d712012-01-12 16:38:12 -08001647status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001648 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001649 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001650 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651{
Eric Laurent0ede8922014-05-09 18:04:42 -07001652 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001654 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 data->mStream = stream;
1656 data->mVolume = volume;
1657 data->mIO = output;
1658 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001659 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001660 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001661 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001662 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663}
1664
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001665status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001666 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001667 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668{
Eric Laurent0ede8922014-05-09 18:04:42 -07001669 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001671 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001673 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001675 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001676 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001677 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001678 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679}
1680
1681status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1682{
Eric Laurent0ede8922014-05-09 18:04:42 -07001683 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001685 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 data->mVolume = volume;
1687 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001688 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001689 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001690 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691}
1692
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001693void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1694 audio_session_t sessionId,
1695 bool suspended)
1696{
1697 sp<AudioCommand> command = new AudioCommand();
1698 command->mCommand = SET_EFFECT_SUSPENDED;
1699 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1700 data->mEffectId = effectId;
1701 data->mSessionId = sessionId;
1702 data->mSuspended = suspended;
1703 command->mParam = data;
1704 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1705 effectId, sessionId, suspended);
1706 sendCommand(command);
1707}
1708
1709
Eric Laurentd7fe0862018-07-14 16:48:01 -07001710void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001711{
Eric Laurent0ede8922014-05-09 18:04:42 -07001712 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001713 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001714 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001715 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001716 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001717 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001718 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001719}
1720
Eric Laurentd7fe0862018-07-14 16:48:01 -07001721void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001722{
Eric Laurent0ede8922014-05-09 18:04:42 -07001723 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001724 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001725 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001726 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001727 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001728 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001729 sendCommand(command);
1730}
1731
Eric Laurent951f4552014-05-20 10:48:17 -07001732status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1733 const struct audio_patch *patch,
1734 audio_patch_handle_t *handle,
1735 int delayMs)
1736{
1737 status_t status = NO_ERROR;
1738
1739 sp<AudioCommand> command = new AudioCommand();
1740 command->mCommand = CREATE_AUDIO_PATCH;
1741 CreateAudioPatchData *data = new CreateAudioPatchData();
1742 data->mPatch = *patch;
1743 data->mHandle = *handle;
1744 command->mParam = data;
1745 command->mWaitStatus = true;
1746 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1747 status = sendCommand(command, delayMs);
1748 if (status == NO_ERROR) {
1749 *handle = data->mHandle;
1750 }
1751 return status;
1752}
1753
1754status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1755 int delayMs)
1756{
1757 sp<AudioCommand> command = new AudioCommand();
1758 command->mCommand = RELEASE_AUDIO_PATCH;
1759 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1760 data->mHandle = handle;
1761 command->mParam = data;
1762 command->mWaitStatus = true;
1763 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1764 return sendCommand(command, delayMs);
1765}
1766
Eric Laurentb52c1522014-05-20 11:27:36 -07001767void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1768{
1769 sp<AudioCommand> command = new AudioCommand();
1770 command->mCommand = UPDATE_AUDIOPORT_LIST;
1771 ALOGV("AudioCommandThread() adding update audio port list");
1772 sendCommand(command);
1773}
1774
1775void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1776{
1777 sp<AudioCommand>command = new AudioCommand();
1778 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1779 ALOGV("AudioCommandThread() adding update audio patch list");
1780 sendCommand(command);
1781}
1782
François Gaffiecfe17322018-11-07 13:41:29 +01001783void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1784 int flags)
1785{
1786 sp<AudioCommand>command = new AudioCommand();
1787 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1788 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1789 data->mGroup = group;
1790 data->mFlags = flags;
1791 command->mParam = data;
1792 ALOGV("AudioCommandThread() adding audio volume group changed");
1793 sendCommand(command);
1794}
1795
Eric Laurente1715a42014-05-20 11:30:42 -07001796status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1797 const struct audio_port_config *config, int delayMs)
1798{
1799 sp<AudioCommand> command = new AudioCommand();
1800 command->mCommand = SET_AUDIOPORT_CONFIG;
1801 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1802 data->mConfig = *config;
1803 command->mParam = data;
1804 command->mWaitStatus = true;
1805 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1806 return sendCommand(command, delayMs);
1807}
1808
Jean-Michel Trivide801052015-04-14 19:10:14 -07001809void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001810 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001811{
1812 sp<AudioCommand> command = new AudioCommand();
1813 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1814 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1815 data->mRegId = regId;
1816 data->mState = state;
1817 command->mParam = data;
1818 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1819 regId.string(), state);
1820 sendCommand(command);
1821}
1822
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001823void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001824 int event,
1825 const record_client_info_t *clientInfo,
1826 const audio_config_base_t *clientConfig,
1827 std::vector<effect_descriptor_t> clientEffects,
1828 const audio_config_base_t *deviceConfig,
1829 std::vector<effect_descriptor_t> effects,
1830 audio_patch_handle_t patchHandle,
1831 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001832{
1833 sp<AudioCommand>command = new AudioCommand();
1834 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1835 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1836 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001837 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001838 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001839 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001840 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001841 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001842 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001843 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001844 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001845 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1846 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001847 sendCommand(command);
1848}
1849
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001850void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1851{
1852 sp<AudioCommand> command = new AudioCommand();
1853 command->mCommand = AUDIO_MODULES_UPDATE;
1854 sendCommand(command);
1855}
1856
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001857void AudioPolicyService::AudioCommandThread::routingChangedCommand()
1858{
1859 sp<AudioCommand>command = new AudioCommand();
1860 command->mCommand = ROUTING_UPDATED;
1861 ALOGV("AudioCommandThread() adding routing update");
1862 sendCommand(command);
1863}
1864
Eric Laurent0ede8922014-05-09 18:04:42 -07001865status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1866{
1867 {
1868 Mutex::Autolock _l(mLock);
1869 insertCommand_l(command, delayMs);
1870 mWaitWorkCV.signal();
1871 }
1872 Mutex::Autolock _l(command->mLock);
1873 while (command->mWaitStatus) {
1874 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1875 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1876 command->mStatus = TIMED_OUT;
1877 command->mWaitStatus = false;
1878 }
1879 }
1880 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001881}
1882
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001884void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001886 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001887 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888 command->mTime = systemTime() + milliseconds(delayMs);
1889
1890 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001891 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1893 }
1894
1895 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001896 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001897 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1899 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001900
1901 // create audio patch or release audio patch commands are equivalent
1902 // with regard to filtering
1903 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1904 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1905 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1906 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1907 continue;
1908 }
1909 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910
1911 switch (command->mCommand) {
1912 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001913 ParametersData *data = (ParametersData *)command->mParam.get();
1914 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001916 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001917 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1919 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1920 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001921 String8 key;
1922 String8 value;
1923 param.getAt(j, key, value);
1924 for (size_t k = 0; k < param2.size(); k++) {
1925 String8 key2;
1926 String8 value2;
1927 param2.getAt(k, key2, value2);
1928 if (key2 == key) {
1929 param2.remove(key2);
1930 ALOGV("Filtering out parameter %s", key2.string());
1931 break;
1932 }
1933 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 }
1935 // if all keys have been filtered out, remove the command.
1936 // otherwise, update the key value pairs
1937 if (param2.size() == 0) {
1938 removedCommands.add(command2);
1939 } else {
1940 data2->mKeyValuePairs = param2.toString();
1941 }
Eric Laurent21e54562013-09-23 12:08:05 -07001942 command->mTime = command2->mTime;
1943 // force delayMs to non 0 so that code below does not request to wait for
1944 // command status as the command is now delayed
1945 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 } break;
1947
1948 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001949 VolumeData *data = (VolumeData *)command->mParam.get();
1950 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 if (data->mIO != data2->mIO) break;
1952 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01001953 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07001954 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07001956 command->mTime = command2->mTime;
1957 // force delayMs to non 0 so that code below does not request to wait for
1958 // command status as the command is now delayed
1959 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001961
Eric Laurentbaf35fe2016-07-27 15:36:53 -07001962 case SET_VOICE_VOLUME: {
1963 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1964 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
1965 ALOGV("Filtering out voice volume command value %f replaced by %f",
1966 data2->mVolume, data->mVolume);
1967 removedCommands.add(command2);
1968 command->mTime = command2->mTime;
1969 // force delayMs to non 0 so that code below does not request to wait for
1970 // command status as the command is now delayed
1971 delayMs = 1;
1972 } break;
1973
Eric Laurente45b48a2014-09-04 16:40:57 -07001974 case CREATE_AUDIO_PATCH:
1975 case RELEASE_AUDIO_PATCH: {
1976 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001977 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001978 if (command->mCommand == CREATE_AUDIO_PATCH) {
1979 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001980 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001981 } else {
1982 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07001983 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07001984 }
1985 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001986 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07001987 if (command2->mCommand == CREATE_AUDIO_PATCH) {
1988 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001989 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001990 } else {
1991 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07001992 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07001993 }
1994 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001995 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
1996 same output. */
1997 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
1998 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
1999 bool isOutputDiff = false;
2000 if (patch.num_sources == patch2.num_sources) {
2001 for (unsigned count = 0; count < patch.num_sources; count++) {
2002 if (patch.sources[count].id != patch2.sources[count].id) {
2003 isOutputDiff = true;
2004 break;
2005 }
2006 }
2007 if (isOutputDiff)
2008 break;
2009 }
2010 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002011 ALOGV("Filtering out %s audio patch command for handle %d",
2012 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2013 removedCommands.add(command2);
2014 command->mTime = command2->mTime;
2015 // force delayMs to non 0 so that code below does not request to wait for
2016 // command status as the command is now delayed
2017 delayMs = 1;
2018 } break;
2019
Jean-Michel Trivide801052015-04-14 19:10:14 -07002020 case DYN_POLICY_MIX_STATE_UPDATE: {
2021
2022 } break;
2023
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002024 case RECORDING_CONFIGURATION_UPDATE: {
2025
2026 } break;
2027
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002028 case ROUTING_UPDATED: {
2029
2030 } break;
2031
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 default:
2033 break;
2034 }
2035 }
2036
2037 // remove filtered commands
2038 for (size_t j = 0; j < removedCommands.size(); j++) {
2039 // removed commands always have time stamps greater than current command
2040 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002041 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002042 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 mAudioCommands.removeAt(k);
2044 break;
2045 }
2046 }
2047 }
2048 removedCommands.clear();
2049
Eric Laurentaa79bef2015-01-15 14:33:51 -08002050 // Disable wait for status if delay is not 0.
2051 // Except for create audio patch command because the returned patch handle
2052 // is needed by audio policy manager
2053 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002054 command->mWaitStatus = false;
2055 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002056
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002058 ALOGV("inserting command: %d at index %zd, num commands %zu",
2059 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 mAudioCommands.insertAt(command, i + 1);
2061}
2062
2063void AudioPolicyService::AudioCommandThread::exit()
2064{
Steve Block3856b092011-10-20 11:56:00 +01002065 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 {
2067 AutoMutex _l(mLock);
2068 requestExit();
2069 mWaitWorkCV.signal();
2070 }
Zach Janga754b4f2015-10-27 01:29:34 +00002071 // Note that we can call it from the thread loop if all other references have been released
2072 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 requestExitAndWait();
2074}
2075
2076void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2077{
2078 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2079 mCommand,
2080 (int)ns2s(mTime),
2081 (int)ns2ms(mTime)%1000,
2082 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002083 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084}
2085
Dima Zavinfce7a472011-04-19 22:30:36 -07002086/******* helpers for the service_ops callbacks defined below *********/
2087void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2088 const char *keyValuePairs,
2089 int delayMs)
2090{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002091 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002092 delayMs);
2093}
2094
2095int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2096 float volume,
2097 audio_io_handle_t output,
2098 int delayMs)
2099{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002100 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002101 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002102}
2103
Dima Zavinfce7a472011-04-19 22:30:36 -07002104int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2105{
2106 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2107}
2108
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002109void AudioPolicyService::setEffectSuspended(int effectId,
2110 audio_session_t sessionId,
2111 bool suspended)
2112{
2113 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2114}
2115
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002116Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002117{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002118 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002119 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002120}
2121
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002122
Dima Zavinfce7a472011-04-19 22:30:36 -07002123extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002124audio_module_handle_t aps_load_hw_module(void *service __unused,
2125 const char *name);
2126audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002127 audio_devices_t *pDevices,
2128 uint32_t *pSamplingRate,
2129 audio_format_t *pFormat,
2130 audio_channel_mask_t *pChannelMask,
2131 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002132 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002133
Eric Laurent2d388ec2014-03-07 13:25:54 -08002134audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002135 audio_module_handle_t module,
2136 audio_devices_t *pDevices,
2137 uint32_t *pSamplingRate,
2138 audio_format_t *pFormat,
2139 audio_channel_mask_t *pChannelMask,
2140 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002141 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002142 const audio_offload_info_t *offloadInfo);
2143audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002144 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002145 audio_io_handle_t output2);
2146int aps_close_output(void *service __unused, audio_io_handle_t output);
2147int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2148int aps_restore_output(void *service __unused, audio_io_handle_t output);
2149audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002150 audio_devices_t *pDevices,
2151 uint32_t *pSamplingRate,
2152 audio_format_t *pFormat,
2153 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002154 audio_in_acoustics_t acoustics __unused);
2155audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002156 audio_module_handle_t module,
2157 audio_devices_t *pDevices,
2158 uint32_t *pSamplingRate,
2159 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002160 audio_channel_mask_t *pChannelMask);
2161int aps_close_input(void *service __unused, audio_io_handle_t input);
2162int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002163int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002164 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002165 audio_io_handle_t dst_output);
2166char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2167 const char *keys);
2168void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2169 const char *kv_pairs, int delay_ms);
2170int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002171 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002172 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002173int aps_set_voice_volume(void *service, float volume, int delay_ms);
2174};
Dima Zavinfce7a472011-04-19 22:30:36 -07002175
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002176} // namespace android