blob: d743be9ab60cec38eda3814d9af8226d69eef3c2 [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>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070038#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080039#include <media/AudioParameter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070040#include <mediautils/ServiceUtilities.h>
Michael Groovercfd28302018-12-11 19:16:46 -080041#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
Dima Zavin64760242011-05-11 14:15:23 -070043#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070044#include <system/audio_policy.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070045
Mathias Agopian65ab4712010-07-14 17:59:35 -070046namespace android {
47
Glenn Kasten8dad0e32012-01-09 08:41:22 -080048static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
49static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Mikhail Naganov959e2d02019-03-28 11:08:19 -070051static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Eric Laurent0ede8922014-05-09 18:04:42 -070053static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010054
Svet Ganovf4ddfef2018-01-16 07:37:58 -080055static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057// ----------------------------------------------------------------------------
58
59AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070060 : BnAudioPolicyService(),
61 mpAudioPolicyDev(NULL),
62 mpAudioPolicy(NULL),
63 mAudioPolicyManager(NULL),
64 mAudioPolicyClient(NULL),
65 mPhoneState(AUDIO_MODE_INVALID),
66 mCaptureStateNotifier(false) {
Eric Laurentf5ada6e2014-10-09 17:49:00 -070067}
68
69void AudioPolicyService::onFirstRef()
70{
Eric Laurent8b1e80b2014-10-07 09:08:47 -070071 {
72 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -080073
Eric Laurent8b1e80b2014-10-07 09:08:47 -070074 // start audio commands thread
75 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
76 // start output activity command thread
77 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -070078
Eric Laurent8b1e80b2014-10-07 09:08:47 -070079 mAudioPolicyClient = new AudioPolicyClient(this);
80 mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
Hayden Gomes524159d2019-12-23 14:41:47 -080081
82 mSupportedSystemUsages = std::vector<audio_usage_t> {};
Eric Laurent8b1e80b2014-10-07 09:08:47 -070083 }
bryant_liuba2b4392014-06-11 16:49:30 +080084 // load audio processing modules
Eric Laurent8b1e80b2014-10-07 09:08:47 -070085 sp<AudioPolicyEffects>audioPolicyEffects = new AudioPolicyEffects();
86 {
87 Mutex::Autolock _l(mLock);
88 mAudioPolicyEffects = audioPolicyEffects;
89 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -080090
91 mUidPolicy = new UidPolicy(this);
92 mUidPolicy->registerSelf();
Michael Groovercfd28302018-12-11 19:16:46 -080093
94 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
95 mSensorPrivacyPolicy->registerSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -070096}
97
98AudioPolicyService::~AudioPolicyService()
99{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700101 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700102
Eric Laurentf269b8e2014-06-09 20:01:29 -0700103 destroyAudioPolicyManager(mAudioPolicyManager);
Eric Laurentdce54a12014-03-10 12:19:46 -0700104 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700105
106 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800107 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800108
109 mUidPolicy->unregisterSelf();
110 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800111
112 mSensorPrivacyPolicy->unregisterSelf();
113 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700114}
115
116// A notification client is always registered by AudioSystem when the client process
117// connects to AudioPolicyService.
118void AudioPolicyService::registerClient(const sp<IAudioPolicyServiceClient>& client)
119{
Eric Laurent12590252015-08-21 18:40:20 -0700120 if (client == 0) {
121 ALOGW("%s got NULL client", __FUNCTION__);
122 return;
123 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800124 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700125
126 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800127 pid_t pid = IPCThreadState::self()->getCallingPid();
128 int64_t token = ((int64_t)uid<<32) | pid;
129
130 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700131 sp<NotificationClient> notificationClient = new NotificationClient(this,
132 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800133 uid,
134 pid);
135 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700136
luochaojiang908c7d72018-06-21 14:58:04 +0800137 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700138
Marco Nelissenf8880202014-11-14 07:58:25 -0800139 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700140 binder->linkToDeath(notificationClient);
141 }
142}
143
Eric Laurente8726fe2015-06-26 09:39:24 -0700144void AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
145{
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) {
Eric Laurente8726fe2015-06-26 09:39:24 -0700153 return;
154 }
luochaojiang908c7d72018-06-21 14:58:04 +0800155 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Eric Laurente8726fe2015-06-26 09:39:24 -0700156}
157
François Gaffiecfe17322018-11-07 13:41:29 +0100158void AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
159{
160 Mutex::Autolock _l(mNotificationClientsLock);
161
162 uid_t uid = IPCThreadState::self()->getCallingUid();
163 pid_t pid = IPCThreadState::self()->getCallingPid();
164 int64_t token = ((int64_t)uid<<32) | pid;
165
166 if (mNotificationClients.indexOfKey(token) < 0) {
167 return;
168 }
169 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
170}
171
Eric Laurentb52c1522014-05-20 11:27:36 -0700172// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800173void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700174{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800175 {
176 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800177 int64_t token = ((int64_t)uid<<32) | pid;
178 mNotificationClients.removeItem(token);
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800179 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800180 {
181 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800182 bool hasSameUid = false;
183 for (size_t i = 0; i < mNotificationClients.size(); i++) {
184 if (mNotificationClients.valueAt(i)->uid() == uid) {
185 hasSameUid = true;
186 break;
187 }
188 }
189 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700190 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700191 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700192 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800193 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700194}
195
196void AudioPolicyService::onAudioPortListUpdate()
197{
198 mOutputCommandThread->updateAudioPortListCommand();
199}
200
201void AudioPolicyService::doOnAudioPortListUpdate()
202{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800203 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700204 for (size_t i = 0; i < mNotificationClients.size(); i++) {
205 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
206 }
207}
208
209void AudioPolicyService::onAudioPatchListUpdate()
210{
211 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212}
213
Eric Laurentb52c1522014-05-20 11:27:36 -0700214void AudioPolicyService::doOnAudioPatchListUpdate()
215{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800216 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700217 for (size_t i = 0; i < mNotificationClients.size(); i++) {
218 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
219 }
220}
221
François Gaffiecfe17322018-11-07 13:41:29 +0100222void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
223{
224 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
225}
226
227void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
228{
229 Mutex::Autolock _l(mNotificationClientsLock);
230 for (size_t i = 0; i < mNotificationClients.size(); i++) {
231 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
232 }
233}
234
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700235void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700236{
237 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
238 regId.string(), state);
239 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
240}
241
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700242void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700243{
244 Mutex::Autolock _l(mNotificationClientsLock);
245 for (size_t i = 0; i < mNotificationClients.size(); i++) {
246 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
247 }
248}
249
Eric Laurenta9f86652018-11-28 17:23:11 -0800250void AudioPolicyService::onRecordingConfigurationUpdate(
251 int event,
252 const record_client_info_t *clientInfo,
253 const audio_config_base_t *clientConfig,
254 std::vector<effect_descriptor_t> clientEffects,
255 const audio_config_base_t *deviceConfig,
256 std::vector<effect_descriptor_t> effects,
257 audio_patch_handle_t patchHandle,
258 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800259{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800260 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800261 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800262}
263
Eric Laurenta9f86652018-11-28 17:23:11 -0800264void AudioPolicyService::doOnRecordingConfigurationUpdate(
265 int event,
266 const record_client_info_t *clientInfo,
267 const audio_config_base_t *clientConfig,
268 std::vector<effect_descriptor_t> clientEffects,
269 const audio_config_base_t *deviceConfig,
270 std::vector<effect_descriptor_t> effects,
271 audio_patch_handle_t patchHandle,
272 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800273{
274 Mutex::Autolock _l(mNotificationClientsLock);
275 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800276 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800277 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800278 }
279}
280
281status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
282 audio_patch_handle_t *handle,
283 int delayMs)
284{
285 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
286}
287
288status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
289 int delayMs)
290{
291 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
292}
293
Eric Laurente1715a42014-05-20 11:30:42 -0700294status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
295 int delayMs)
296{
297 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
298}
299
Eric Laurentb52c1522014-05-20 11:27:36 -0700300AudioPolicyService::NotificationClient::NotificationClient(const sp<AudioPolicyService>& service,
301 const sp<IAudioPolicyServiceClient>& client,
luochaojiang908c7d72018-06-21 14:58:04 +0800302 uid_t uid,
303 pid_t pid)
304 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100305 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700306{
307}
308
309AudioPolicyService::NotificationClient::~NotificationClient()
310{
311}
312
313void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
314{
315 sp<NotificationClient> keep(this);
316 sp<AudioPolicyService> service = mService.promote();
317 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800318 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700319 }
320}
321
322void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
323{
Eric Laurente8726fe2015-06-26 09:39:24 -0700324 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700325 mAudioPolicyServiceClient->onAudioPortListUpdate();
326 }
327}
328
329void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
330{
Eric Laurente8726fe2015-06-26 09:39:24 -0700331 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700332 mAudioPolicyServiceClient->onAudioPatchListUpdate();
333 }
334}
Eric Laurent57dae992011-07-24 13:36:09 -0700335
François Gaffiecfe17322018-11-07 13:41:29 +0100336void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
337 int flags)
338{
339 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
340 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
341 }
342}
343
344
Jean-Michel Trivide801052015-04-14 19:10:14 -0700345void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700346 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700347{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700348 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800349 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(regId, state);
350 }
351}
352
353void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800354 int event,
355 const record_client_info_t *clientInfo,
356 const audio_config_base_t *clientConfig,
357 std::vector<effect_descriptor_t> clientEffects,
358 const audio_config_base_t *deviceConfig,
359 std::vector<effect_descriptor_t> effects,
360 audio_patch_handle_t patchHandle,
361 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800362{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700363 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800364 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800365 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700366 }
367}
368
Eric Laurente8726fe2015-06-26 09:39:24 -0700369void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
370{
371 mAudioPortCallbacksEnabled = enabled;
372}
373
François Gaffiecfe17322018-11-07 13:41:29 +0100374void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
375{
376 mAudioVolumeGroupCallbacksEnabled = enabled;
377}
Eric Laurente8726fe2015-06-26 09:39:24 -0700378
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700380 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700381 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382}
383
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700384static bool dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700386 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
387 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388}
389
390status_t AudioPolicyService::dumpInternals(int fd)
391{
392 const size_t SIZE = 256;
393 char buffer[SIZE];
394 String8 result;
395
Eric Laurentdce54a12014-03-10 12:19:46 -0700396 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397 result.append(buffer);
398 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
399 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400
Hayden Gomes524159d2019-12-23 14:41:47 -0800401 snprintf(buffer, SIZE, "Supported System Usages:\n");
402 result.append(buffer);
403 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
404 it != mSupportedSystemUsages.end(); ++it) {
405 snprintf(buffer, SIZE, "\t%d\n", *it);
406 result.append(buffer);
407 }
408
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 write(fd, result.string(), result.size());
410 return NO_ERROR;
411}
412
Eric Laurente8c8b432018-10-17 10:08:02 -0700413void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800414{
Eric Laurente8c8b432018-10-17 10:08:02 -0700415 Mutex::Autolock _l(mLock);
416 updateUidStates_l();
417}
418
419void AudioPolicyService::updateUidStates_l()
420{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800421// Go over all active clients and allow capture (does not force silence) in the
422// following cases:
Eric Laurent8ed73c12019-08-30 17:25:19 -0700423// The client is the assistant
Eric Laurent6ede98f2019-06-11 14:50:30 -0700424// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700425// AND the source is VOICE_RECOGNITION or HOTWORD
426// OR uses VOICE_RECOGNITION AND is on TOP
427// OR uses HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700428// AND there is no active privacy sensitive capture or call
429// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta46bedb2018-12-07 18:01:26 -0800430// OR The client is an accessibility service
Eric Laurent589171c2019-07-25 18:04:29 -0700431// AND Is on TOP
432// AND the source is VOICE_RECOGNITION or HOTWORD
433// OR The assistant is not on TOP
434// AND there is no active privacy sensitive capture or call
435// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta171e352019-05-07 13:04:45 -0700436// AND is on TOP
Eric Laurenta46bedb2018-12-07 18:01:26 -0800437// AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700438// OR the client source is virtual (remote submix, call audio TX or RX...)
Eric Laurent4e947da2019-10-17 15:24:06 -0700439// OR the client source is HOTWORD
440// AND is on TOP
441// OR all active clients are using HOTWORD source
442// AND no call is active
443// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700444// OR the client is the current InputMethodService
445// AND a RTT call is active AND the source is VOICE_RECOGNITION
Eric Laurenta171e352019-05-07 13:04:45 -0700446// OR Any client
Eric Laurenta46bedb2018-12-07 18:01:26 -0800447// AND The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700448// AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700449// AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700450// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800451
Eric Laurent4e947da2019-10-17 15:24:06 -0700452
Eric Laurent4eb58f12018-12-07 16:41:02 -0800453 sp<AudioRecordClient> topActive;
454 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800455 sp<AudioRecordClient> topSensitiveActive;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800456 sp<AudioRecordClient> latestSensitiveActive;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700457
Eric Laurenta46bedb2018-12-07 18:01:26 -0800458 nsecs_t topStartNs = 0;
459 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800460 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800461 nsecs_t latestSensitiveStartNs = 0;
462 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
463 bool isAssistantOnTop = false;
464 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700465 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800466 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
467 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700468 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700469 bool onlyHotwordActive = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800470
Michael Groovercfd28302018-12-11 19:16:46 -0800471 // if Sensor Privacy is enabled then all recordings should be silenced.
472 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
473 silenceAllRecordings_l();
474 return;
475 }
476
Eric Laurente8c8b432018-10-17 10:08:02 -0700477 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
478 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700479 if (!current->active) {
480 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800481 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700482
483 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
484 // clients which app is in IDLE state are not eligible for top active or
485 // latest active
486 if (appState == APP_STATE_IDLE) {
487 continue;
488 }
489
Eric Laurent589171c2019-07-25 18:04:29 -0700490 bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800491 // Clients capturing for Accessibility services are not considered
492 // for top or latest active to avoid masking regular clients started before
493 if (!isAccessibility) {
494 bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
495 bool isPrivacySensitive =
496 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
497 if (appState == APP_STATE_TOP) {
498 if (isPrivacySensitive) {
499 if (current->startTimeNs > topSensitiveStartNs) {
500 topSensitiveActive = current;
501 topSensitiveStartNs = current->startTimeNs;
502 }
503 } else {
504 if (current->startTimeNs > topStartNs) {
505 topActive = current;
506 topStartNs = current->startTimeNs;
507 }
508 }
509 if (isAssistant) {
510 isAssistantOnTop = true;
511 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800512 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800513 // Clients capturing for HOTWORD are not considered
514 // for latest active to avoid masking regular clients started before
515 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
516 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
517 if (isPrivacySensitive) {
518 if (current->startTimeNs > latestSensitiveStartNs) {
519 latestSensitiveActive = current;
520 latestSensitiveStartNs = current->startTimeNs;
521 }
522 isSensitiveActive = true;
523 } else {
524 if (current->startTimeNs > latestStartNs) {
525 latestActive = current;
526 latestStartNs = current->startTimeNs;
527 }
528 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800529 }
530 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700531 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
532 onlyHotwordActive = false;
533 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800534 }
535
Eric Laurent1ff16a72019-03-14 18:35:04 -0700536 // if no active client with UI on Top, consider latest active as top
537 if (topActive == nullptr) {
538 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800539 topStartNs = latestStartNs;
540 }
541 if (topSensitiveActive == nullptr) {
542 topSensitiveActive = latestSensitiveActive;
543 topSensitiveStartNs = latestSensitiveStartNs;
544 }
545
546 // If both privacy sensitive and regular capture are active:
547 // if the regular capture is privileged
548 // allow concurrency
549 // else
550 // favor the privacy sensitive case
551 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700552 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800553 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800554 }
555
556 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
557 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700558 if (!current->active) {
559 continue;
560 }
561
Eric Laurent4eb58f12018-12-07 16:41:02 -0800562 audio_source_t source = current->attributes.source;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700563 bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800564 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ?
565 false : current->uid == topSensitiveActive->uid;
566
567 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700568 bool canCaptureCall = recordClient->canCaptureOutput;
569 bool canCaptureCommunication = recordClient->canCaptureOutput
Eric Laurentc21d5692020-02-25 10:24:36 -0800570 || recordClient->uid == mPhoneStateOwnerUid
571 || isServiceUid(mPhoneStateOwnerUid);
572 return !(isInCall && !canCaptureCall)
573 && !(isInCommunication && !canCaptureCommunication);
574 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700575
576 // By default allow capture if:
577 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700578 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700579 // AND there is no active privacy sensitive capture or call
580 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
581 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800582 && (isTopOrLatestActive || isTopOrLatestSensitive)
583 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700584 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800585 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800586
587 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700588 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
589 allowCapture = true;
Eric Laurent2dc962b2019-03-01 08:25:25 -0800590 } else if (mUidPolicy->isAssistantUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700591 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700592 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700593 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700594 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700595 // OR uses HOTWORD
596 // AND there is no active privacy sensitive capture or call
597 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700598 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800599 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700600 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800601 }
602 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700603 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800604 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700605 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800606 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700607 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800608 }
609 }
610 } else if (mUidPolicy->isA11yUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700611 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700612 // The assistant is not on TOP
613 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700614 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700615 // OR
616 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
617 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700618 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800619 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700620 allowCapture = true;
621 }
Eric Laurent589171c2019-07-25 18:04:29 -0700622 if (isA11yOnTop) {
623 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
624 allowCapture = true;
625 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800626 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700627 } else if (source == AUDIO_SOURCE_HOTWORD) {
628 // For HOTWORD source allow capture when not on TOP if:
629 // All active clients are using HOTWORD source
630 // AND no call is active
631 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800632 if (onlyHotwordActive
633 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700634 allowCapture = true;
635 }
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700636 } else if (mUidPolicy->isCurrentImeUid(current->uid)) {
637 // For current InputMethodService allow capture if:
638 // A RTT call is active AND the source is VOICE_RECOGNITION
639 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
640 allowCapture = true;
641 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800642 }
Eric Laurent5ada82e2019-08-29 17:53:54 -0700643 setAppState_l(current->portId,
Eric Laurent1ff16a72019-03-14 18:35:04 -0700644 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
645 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700646 }
647}
648
Michael Groovercfd28302018-12-11 19:16:46 -0800649void AudioPolicyService::silenceAllRecordings_l() {
650 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
651 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700652 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700653 setAppState_l(current->portId, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700654 }
Michael Groovercfd28302018-12-11 19:16:46 -0800655 }
656}
657
Eric Laurente8c8b432018-10-17 10:08:02 -0700658/* static */
659app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700660
661 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700662 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700663 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
664 // include persistent services
665 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700666 }
667 return APP_STATE_FOREGROUND;
668}
669
Eric Laurent4eb58f12018-12-07 16:41:02 -0800670/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800671bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800672{
673 switch (source) {
674 case AUDIO_SOURCE_VOICE_UPLINK:
675 case AUDIO_SOURCE_VOICE_DOWNLINK:
676 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800677 case AUDIO_SOURCE_REMOTE_SUBMIX:
678 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800679 return true;
680 default:
681 break;
682 }
683 return false;
684}
685
Eric Laurent5ada82e2019-08-29 17:53:54 -0700686void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700687{
688 AutoCallerClear acc;
689
690 if (mAudioPolicyManager) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700691 mAudioPolicyManager->setAppState(portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700692 }
693 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
694 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700695 bool silenced = state == APP_STATE_IDLE;
Eric Laurent5ada82e2019-08-29 17:53:54 -0700696 af->setRecordSilenced(portId, silenced);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700697 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800698}
699
Glenn Kasten0f11b512014-01-31 16:18:54 -0800700status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701{
Glenn Kasten44deb052012-02-05 18:09:08 -0800702 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 dumpPermissionDenial(fd);
704 } else {
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700705 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 if (!locked) {
707 String8 result(kDeadlockedString);
708 write(fd, result.string(), result.size());
709 }
710
711 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800712 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713 mAudioCommandThread->dump(fd);
714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715
Eric Laurentdce54a12014-03-10 12:19:46 -0700716 if (mAudioPolicyManager) {
717 mAudioPolicyManager->dump(fd);
718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719
Kevin Rocard8be94972019-02-22 13:26:25 -0800720 mPackageManager.dump(fd);
721
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 if (locked) mLock.unlock();
723 }
724 return NO_ERROR;
725}
726
727status_t AudioPolicyService::dumpPermissionDenial(int fd)
728{
729 const size_t SIZE = 256;
730 char buffer[SIZE];
731 String8 result;
732 snprintf(buffer, SIZE, "Permission Denial: "
733 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
734 IPCThreadState::self()->getCallingPid(),
735 IPCThreadState::self()->getCallingUid());
736 result.append(buffer);
737 write(fd, result.string(), result.size());
738 return NO_ERROR;
739}
740
741status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800742 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
743 switch (code) {
744 case SHELL_COMMAND_TRANSACTION: {
745 int in = data.readFileDescriptor();
746 int out = data.readFileDescriptor();
747 int err = data.readFileDescriptor();
748 int argc = data.readInt32();
749 Vector<String16> args;
750 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
751 args.add(data.readString16());
752 }
753 sp<IBinder> unusedCallback;
754 sp<IResultReceiver> resultReceiver;
755 status_t status;
756 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
757 return status;
758 }
759 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
760 return status;
761 }
762 status = shellCommand(in, out, err, args);
763 if (resultReceiver != nullptr) {
764 resultReceiver->send(status);
765 }
766 return NO_ERROR;
767 }
768 }
769
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 return BnAudioPolicyService::onTransact(code, data, reply, flags);
771}
772
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800773// ------------------- Shell command implementation -------------------
774
775// NOTE: This is a remote API - make sure all args are validated
776status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
777 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
778 return PERMISSION_DENIED;
779 }
780 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
781 return BAD_VALUE;
782 }
jovanakbe066e12019-09-02 11:54:39 -0700783 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800784 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700785 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800786 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700787 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800788 return handleGetUidState(args, out, err);
789 } else if (args.size() == 1 && args[0] == String16("help")) {
790 printHelp(out);
791 return NO_ERROR;
792 }
793 printHelp(err);
794 return BAD_VALUE;
795}
796
jovanakbe066e12019-09-02 11:54:39 -0700797static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
798 if (userId < 0) {
799 ALOGE("Invalid user: %d", userId);
800 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800801 return BAD_VALUE;
802 }
jovanakbe066e12019-09-02 11:54:39 -0700803
804 PermissionController pc;
805 uid = pc.getPackageUid(packageName, 0);
806 if (uid <= 0) {
807 ALOGE("Unknown package: '%s'", String8(packageName).string());
808 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
809 return BAD_VALUE;
810 }
811
812 uid = multiuser_get_uid(userId, uid);
813 return NO_ERROR;
814}
815
816status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
817 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
818 if (!(args.size() == 3 || args.size() == 5)) {
819 printHelp(err);
820 return BAD_VALUE;
821 }
822
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800823 bool active = false;
824 if (args[2] == String16("active")) {
825 active = true;
826 } else if ((args[2] != String16("idle"))) {
827 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
828 return BAD_VALUE;
829 }
jovanakbe066e12019-09-02 11:54:39 -0700830
831 int userId = 0;
832 if (args.size() >= 5 && args[3] == String16("--user")) {
833 userId = atoi(String8(args[4]));
834 }
835
836 uid_t uid;
837 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
838 return BAD_VALUE;
839 }
840
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800841 mUidPolicy->addOverrideUid(uid, active);
842 return NO_ERROR;
843}
844
845status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -0700846 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
847 if (!(args.size() == 2 || args.size() == 4)) {
848 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800849 return BAD_VALUE;
850 }
jovanakbe066e12019-09-02 11:54:39 -0700851
852 int userId = 0;
853 if (args.size() >= 4 && args[2] == String16("--user")) {
854 userId = atoi(String8(args[3]));
855 }
856
857 uid_t uid;
858 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
859 return BAD_VALUE;
860 }
861
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800862 mUidPolicy->removeOverrideUid(uid);
863 return NO_ERROR;
864}
865
866status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -0700867 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
868 if (!(args.size() == 2 || args.size() == 4)) {
869 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800870 return BAD_VALUE;
871 }
jovanakbe066e12019-09-02 11:54:39 -0700872
873 int userId = 0;
874 if (args.size() >= 4 && args[2] == String16("--user")) {
875 userId = atoi(String8(args[3]));
876 }
877
878 uid_t uid;
879 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
880 return BAD_VALUE;
881 }
882
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800883 if (mUidPolicy->isUidActive(uid)) {
884 return dprintf(out, "active\n");
885 } else {
886 return dprintf(out, "idle\n");
887 }
888}
889
890status_t AudioPolicyService::printHelp(int out) {
891 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -0700892 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
893 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
894 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800895 " help print this message\n");
896}
897
898// ----------- AudioPolicyService::UidPolicy implementation ----------
899
900void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -0700901 status_t res = mAm.linkToDeath(this);
902 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800903 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -0700904 | ActivityManager::UID_OBSERVER_ACTIVE
905 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800906 ActivityManager::PROCESS_STATE_UNKNOWN,
907 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700908 if (!res) {
909 Mutex::Autolock _l(mLock);
910 mObserverRegistered = true;
911 } else {
912 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -0800913
Steven Moreland2f348142019-07-02 15:59:07 -0700914 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700915 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800916}
917
918void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -0700919 mAm.unlinkToDeath(this);
920 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700921 Mutex::Autolock _l(mLock);
922 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800923}
924
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700925void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
926 Mutex::Autolock _l(mLock);
927 mCachedUids.clear();
928 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800929}
930
Eric Laurente8c8b432018-10-17 10:08:02 -0700931void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700932 bool needToReregister = false;
933 {
934 Mutex::Autolock _l(mLock);
935 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800936 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700937 if (needToReregister) {
938 // Looks like ActivityManager has died previously, attempt to re-register.
939 registerSelf();
940 }
Eric Laurente8c8b432018-10-17 10:08:02 -0700941}
942
943bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
944 if (isServiceUid(uid)) return true;
945 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700946 {
947 Mutex::Autolock _l(mLock);
948 auto overrideIter = mOverrideUids.find(uid);
949 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700950 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700951 }
952 // In an absense of the ActivityManager, assume everything to be active.
953 if (!mObserverRegistered) return true;
954 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -0700955 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700956 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700957 }
958 }
959 ActivityManager am;
Hui Yuffffffc2020-03-24 16:13:59 -0700960 bool active = am.isUidActiveOrForeground(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700961 {
962 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -0700963 mCachedUids.insert(std::pair<uid_t,
964 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
965 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700966 }
967 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800968}
969
Eric Laurente8c8b432018-10-17 10:08:02 -0700970int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
971 if (isServiceUid(uid)) {
972 return ActivityManager::PROCESS_STATE_TOP;
973 }
974 checkRegistered();
975 {
976 Mutex::Autolock _l(mLock);
977 auto overrideIter = mOverrideUids.find(uid);
978 if (overrideIter != mOverrideUids.end()) {
979 if (overrideIter->second.first) {
980 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
981 return overrideIter->second.second;
982 } else {
983 auto cacheIter = mCachedUids.find(uid);
984 if (cacheIter != mCachedUids.end()) {
985 return cacheIter->second.second;
986 }
987 }
988 }
989 return ActivityManager::PROCESS_STATE_UNKNOWN;
990 }
991 // In an absense of the ActivityManager, assume everything to be active.
992 if (!mObserverRegistered) {
993 return ActivityManager::PROCESS_STATE_TOP;
994 }
995 auto cacheIter = mCachedUids.find(uid);
996 if (cacheIter != mCachedUids.end()) {
997 if (cacheIter->second.first) {
998 return cacheIter->second.second;
999 } else {
1000 return ActivityManager::PROCESS_STATE_UNKNOWN;
1001 }
1002 }
1003 }
1004 ActivityManager am;
Hui Yuffffffc2020-03-24 16:13:59 -07001005 bool active = am.isUidActiveOrForeground(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001006 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1007 if (active) {
1008 state = am.getUidProcessState(uid, String16("audioserver"));
1009 }
1010 {
1011 Mutex::Autolock _l(mLock);
1012 mCachedUids.insert(std::pair<uid_t,
1013 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1014 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001015
Eric Laurente8c8b432018-10-17 10:08:02 -07001016 return state;
1017}
1018
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001019void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001020 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001021}
1022
1023void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001024 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001025}
1026
1027void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001028 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001029}
1030
Eric Laurente8c8b432018-10-17 10:08:02 -07001031void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1032 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001033 int64_t procStateSeq __unused,
1034 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001035 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1036 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001037 }
1038}
1039
1040void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001041 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1042}
1043
1044void AudioPolicyService::UidPolicy::notifyService() {
1045 sp<AudioPolicyService> service = mService.promote();
1046 if (service != nullptr) {
1047 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001048 }
1049}
1050
Eric Laurente8c8b432018-10-17 10:08:02 -07001051void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1052 std::pair<bool, int>> *uids,
1053 uid_t uid,
1054 bool active,
1055 int state,
1056 bool insert) {
1057 if (isServiceUid(uid)) {
1058 return;
1059 }
1060 bool wasActive = isUidActive(uid);
1061 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001062 {
1063 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001064 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001065 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001066 if (wasActive != isUidActive(uid) || state != previousState) {
1067 notifyService();
1068 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001069}
1070
Eric Laurente8c8b432018-10-17 10:08:02 -07001071void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1072 std::pair<bool, int>> *uids,
1073 uid_t uid,
1074 bool active,
1075 int state,
1076 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001077 auto it = uids->find(uid);
1078 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001079 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001080 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1081 it->second.first = active;
1082 }
1083 if (it->second.first) {
1084 it->second.second = state;
1085 } else {
1086 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1087 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001088 } else {
1089 uids->erase(it);
1090 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001091 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1092 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1093 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001094 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001095}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096
Eric Laurent4eb58f12018-12-07 16:41:02 -08001097bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1098 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001099 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001100 continue;
1101 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001102 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1103 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001104 return true;
1105 }
1106 }
1107 return false;
1108}
1109
Eric Laurentb78763e2018-10-17 10:08:02 -07001110bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1111{
1112 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1113 return it != mA11yUids.end();
1114}
1115
Michael Groovercfd28302018-12-11 19:16:46 -08001116// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1117void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1118 SensorPrivacyManager spm;
1119 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1120 spm.addSensorPrivacyListener(this);
1121}
1122
1123void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1124 SensorPrivacyManager spm;
1125 spm.removeSensorPrivacyListener(this);
1126}
1127
1128bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1129 return mSensorPrivacyEnabled;
1130}
1131
1132binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1133 mSensorPrivacyEnabled = enabled;
1134 sp<AudioPolicyService> service = mService.promote();
1135 if (service != nullptr) {
1136 service->updateUidStates();
1137 }
1138 return binder::Status::ok();
1139}
1140
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1142
Eric Laurentbfb1b832013-01-07 09:53:42 -08001143AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1144 const wp<AudioPolicyService>& service)
1145 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147}
1148
1149
1150AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1151{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001152 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 release_wake_lock(mName.string());
1154 }
1155 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156}
1157
1158void AudioPolicyService::AudioCommandThread::onFirstRef()
1159{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001160 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161}
1162
1163bool AudioPolicyService::AudioCommandThread::threadLoop()
1164{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001165 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166
1167 mLock.lock();
1168 while (!exitPending())
1169 {
Eric Laurent59a89232014-06-08 14:14:17 -07001170 sp<AudioPolicyService> svc;
1171 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 nsecs_t curTime = systemTime();
1173 // commands are sorted by increasing time stamp: execute them from index 0 and up
1174 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001175 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001177 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178
1179 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001181 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001183 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001184 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001185 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1186 data->mVolume,
1187 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001188 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }break;
1190 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001191 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001192 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1193 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001194 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001195 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001196 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001197 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001199 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001200 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001201 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001202 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001204 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001206 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001207 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001208 ALOGV("AudioCommandThread() processing stop output portId %d",
1209 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001210 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001211 if (svc == 0) {
1212 break;
1213 }
1214 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001215 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001216 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001217 }break;
1218 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001219 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001220 ALOGV("AudioCommandThread() processing release output portId %d",
1221 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001222 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001223 if (svc == 0) {
1224 break;
1225 }
1226 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001227 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001228 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001229 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001230 case CREATE_AUDIO_PATCH: {
1231 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1232 ALOGV("AudioCommandThread() processing create audio patch");
1233 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1234 if (af == 0) {
1235 command->mStatus = PERMISSION_DENIED;
1236 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001237 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001238 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001239 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001240 }
1241 } break;
1242 case RELEASE_AUDIO_PATCH: {
1243 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1244 ALOGV("AudioCommandThread() processing release audio patch");
1245 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1246 if (af == 0) {
1247 command->mStatus = PERMISSION_DENIED;
1248 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001249 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001250 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001251 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001252 }
1253 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001254 case UPDATE_AUDIOPORT_LIST: {
1255 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001256 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001257 if (svc == 0) {
1258 break;
1259 }
1260 mLock.unlock();
1261 svc->doOnAudioPortListUpdate();
1262 mLock.lock();
1263 }break;
1264 case UPDATE_AUDIOPATCH_LIST: {
1265 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001266 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001267 if (svc == 0) {
1268 break;
1269 }
1270 mLock.unlock();
1271 svc->doOnAudioPatchListUpdate();
1272 mLock.lock();
1273 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001274 case CHANGED_AUDIOVOLUMEGROUP: {
1275 AudioVolumeGroupData *data =
1276 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1277 ALOGV("AudioCommandThread() processing update audio volume group");
1278 svc = mService.promote();
1279 if (svc == 0) {
1280 break;
1281 }
1282 mLock.unlock();
1283 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1284 mLock.lock();
1285 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001286 case SET_AUDIOPORT_CONFIG: {
1287 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1288 ALOGV("AudioCommandThread() processing set port config");
1289 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1290 if (af == 0) {
1291 command->mStatus = PERMISSION_DENIED;
1292 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001293 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001294 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001295 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001296 }
1297 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001298 case DYN_POLICY_MIX_STATE_UPDATE: {
1299 DynPolicyMixStateUpdateData *data =
1300 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001301 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1302 data->mRegId.string(), data->mState);
1303 svc = mService.promote();
1304 if (svc == 0) {
1305 break;
1306 }
1307 mLock.unlock();
1308 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1309 mLock.lock();
1310 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001311 case RECORDING_CONFIGURATION_UPDATE: {
1312 RecordingConfigurationUpdateData *data =
1313 (RecordingConfigurationUpdateData *)command->mParam.get();
1314 ALOGV("AudioCommandThread() processing recording configuration update");
1315 svc = mService.promote();
1316 if (svc == 0) {
1317 break;
1318 }
1319 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001320 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001321 &data->mClientConfig, data->mClientEffects,
1322 &data->mDeviceConfig, data->mEffects,
1323 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001324 mLock.lock();
1325 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001326 case SET_EFFECT_SUSPENDED: {
1327 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1328 ALOGV("AudioCommandThread() processing set effect suspended");
1329 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1330 if (af != 0) {
1331 mLock.unlock();
1332 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1333 mLock.lock();
1334 }
1335 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001336 case AUDIO_MODULES_UPDATE: {
1337 ALOGV("AudioCommandThread() processing audio modules update");
1338 svc = mService.promote();
1339 if (svc == 0) {
1340 break;
1341 }
1342 mLock.unlock();
1343 svc->doOnNewAudioModulesAvailable();
1344 mLock.lock();
1345 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001346
Mathias Agopian65ab4712010-07-14 17:59:35 -07001347 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001348 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001350 {
1351 Mutex::Autolock _l(command->mLock);
1352 if (command->mWaitStatus) {
1353 command->mWaitStatus = false;
1354 command->mCond.signal();
1355 }
1356 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001357 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001358 // release mLock before releasing strong reference on the service as
1359 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1360 // acquires mLock.
1361 mLock.unlock();
1362 svc.clear();
1363 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364 } else {
1365 waitTime = mAudioCommands[0]->mTime - curTime;
1366 break;
1367 }
1368 }
Zach Janga754b4f2015-10-27 01:29:34 +00001369
1370 // release delayed commands wake lock if the queue is empty
1371 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001372 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001373 }
1374
1375 // At this stage we have either an empty command queue or the first command in the queue
1376 // has a finite delay. So unless we are exiting it is safe to wait.
1377 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001378 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001379 if (waitTime == -1) {
1380 mWaitWorkCV.wait(mLock);
1381 } else {
1382 mWaitWorkCV.waitRelative(mLock, waitTime);
1383 }
Eric Laurent59a89232014-06-08 14:14:17 -07001384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001386 // release delayed commands wake lock before quitting
1387 if (!mAudioCommands.isEmpty()) {
1388 release_wake_lock(mName.string());
1389 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390 mLock.unlock();
1391 return false;
1392}
1393
1394status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1395{
1396 const size_t SIZE = 256;
1397 char buffer[SIZE];
1398 String8 result;
1399
1400 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1401 result.append(buffer);
1402 write(fd, result.string(), result.size());
1403
Mikhail Naganov959e2d02019-03-28 11:08:19 -07001404 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405 if (!locked) {
1406 String8 result2(kCmdDeadlockedString);
1407 write(fd, result2.string(), result2.size());
1408 }
1409
1410 snprintf(buffer, SIZE, "- Commands:\n");
1411 result = String8(buffer);
1412 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001413 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414 mAudioCommands[i]->dump(buffer, SIZE);
1415 result.append(buffer);
1416 }
1417 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001418 if (mLastCommand != 0) {
1419 mLastCommand->dump(buffer, SIZE);
1420 result.append(buffer);
1421 } else {
1422 result.append(" none\n");
1423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424
1425 write(fd, result.string(), result.size());
1426
1427 if (locked) mLock.unlock();
1428
1429 return NO_ERROR;
1430}
1431
Glenn Kastenfff6d712012-01-12 16:38:12 -08001432status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001433 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001434 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001435 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436{
Eric Laurent0ede8922014-05-09 18:04:42 -07001437 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001439 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 data->mStream = stream;
1441 data->mVolume = volume;
1442 data->mIO = output;
1443 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001444 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001445 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001446 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001447 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448}
1449
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001450status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001451 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001452 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453{
Eric Laurent0ede8922014-05-09 18:04:42 -07001454 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001456 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001458 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001460 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001461 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001462 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001463 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464}
1465
1466status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1467{
Eric Laurent0ede8922014-05-09 18:04:42 -07001468 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001470 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 data->mVolume = volume;
1472 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001473 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001474 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001475 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001478void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1479 audio_session_t sessionId,
1480 bool suspended)
1481{
1482 sp<AudioCommand> command = new AudioCommand();
1483 command->mCommand = SET_EFFECT_SUSPENDED;
1484 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1485 data->mEffectId = effectId;
1486 data->mSessionId = sessionId;
1487 data->mSuspended = suspended;
1488 command->mParam = data;
1489 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1490 effectId, sessionId, suspended);
1491 sendCommand(command);
1492}
1493
1494
Eric Laurentd7fe0862018-07-14 16:48:01 -07001495void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001496{
Eric Laurent0ede8922014-05-09 18:04:42 -07001497 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001498 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001499 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001500 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001501 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001502 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001503 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001504}
1505
Eric Laurentd7fe0862018-07-14 16:48:01 -07001506void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001507{
Eric Laurent0ede8922014-05-09 18:04:42 -07001508 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001509 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001510 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001511 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001512 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001513 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001514 sendCommand(command);
1515}
1516
Eric Laurent951f4552014-05-20 10:48:17 -07001517status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1518 const struct audio_patch *patch,
1519 audio_patch_handle_t *handle,
1520 int delayMs)
1521{
1522 status_t status = NO_ERROR;
1523
1524 sp<AudioCommand> command = new AudioCommand();
1525 command->mCommand = CREATE_AUDIO_PATCH;
1526 CreateAudioPatchData *data = new CreateAudioPatchData();
1527 data->mPatch = *patch;
1528 data->mHandle = *handle;
1529 command->mParam = data;
1530 command->mWaitStatus = true;
1531 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1532 status = sendCommand(command, delayMs);
1533 if (status == NO_ERROR) {
1534 *handle = data->mHandle;
1535 }
1536 return status;
1537}
1538
1539status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1540 int delayMs)
1541{
1542 sp<AudioCommand> command = new AudioCommand();
1543 command->mCommand = RELEASE_AUDIO_PATCH;
1544 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1545 data->mHandle = handle;
1546 command->mParam = data;
1547 command->mWaitStatus = true;
1548 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1549 return sendCommand(command, delayMs);
1550}
1551
Eric Laurentb52c1522014-05-20 11:27:36 -07001552void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1553{
1554 sp<AudioCommand> command = new AudioCommand();
1555 command->mCommand = UPDATE_AUDIOPORT_LIST;
1556 ALOGV("AudioCommandThread() adding update audio port list");
1557 sendCommand(command);
1558}
1559
1560void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1561{
1562 sp<AudioCommand>command = new AudioCommand();
1563 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1564 ALOGV("AudioCommandThread() adding update audio patch list");
1565 sendCommand(command);
1566}
1567
François Gaffiecfe17322018-11-07 13:41:29 +01001568void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1569 int flags)
1570{
1571 sp<AudioCommand>command = new AudioCommand();
1572 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1573 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1574 data->mGroup = group;
1575 data->mFlags = flags;
1576 command->mParam = data;
1577 ALOGV("AudioCommandThread() adding audio volume group changed");
1578 sendCommand(command);
1579}
1580
Eric Laurente1715a42014-05-20 11:30:42 -07001581status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1582 const struct audio_port_config *config, int delayMs)
1583{
1584 sp<AudioCommand> command = new AudioCommand();
1585 command->mCommand = SET_AUDIOPORT_CONFIG;
1586 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1587 data->mConfig = *config;
1588 command->mParam = data;
1589 command->mWaitStatus = true;
1590 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1591 return sendCommand(command, delayMs);
1592}
1593
Jean-Michel Trivide801052015-04-14 19:10:14 -07001594void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001595 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001596{
1597 sp<AudioCommand> command = new AudioCommand();
1598 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1599 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1600 data->mRegId = regId;
1601 data->mState = state;
1602 command->mParam = data;
1603 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1604 regId.string(), state);
1605 sendCommand(command);
1606}
1607
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001608void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001609 int event,
1610 const record_client_info_t *clientInfo,
1611 const audio_config_base_t *clientConfig,
1612 std::vector<effect_descriptor_t> clientEffects,
1613 const audio_config_base_t *deviceConfig,
1614 std::vector<effect_descriptor_t> effects,
1615 audio_patch_handle_t patchHandle,
1616 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001617{
1618 sp<AudioCommand>command = new AudioCommand();
1619 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1620 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1621 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001622 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001623 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001624 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001625 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001626 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001627 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001628 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001629 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001630 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1631 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001632 sendCommand(command);
1633}
1634
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001635void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1636{
1637 sp<AudioCommand> command = new AudioCommand();
1638 command->mCommand = AUDIO_MODULES_UPDATE;
1639 sendCommand(command);
1640}
1641
Eric Laurent0ede8922014-05-09 18:04:42 -07001642status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1643{
1644 {
1645 Mutex::Autolock _l(mLock);
1646 insertCommand_l(command, delayMs);
1647 mWaitWorkCV.signal();
1648 }
1649 Mutex::Autolock _l(command->mLock);
1650 while (command->mWaitStatus) {
1651 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1652 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1653 command->mStatus = TIMED_OUT;
1654 command->mWaitStatus = false;
1655 }
1656 }
1657 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001658}
1659
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001661void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001663 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001664 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 command->mTime = systemTime() + milliseconds(delayMs);
1666
1667 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001668 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1670 }
1671
1672 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001673 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001674 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1676 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001677
1678 // create audio patch or release audio patch commands are equivalent
1679 // with regard to filtering
1680 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1681 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1682 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1683 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1684 continue;
1685 }
1686 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687
1688 switch (command->mCommand) {
1689 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001690 ParametersData *data = (ParametersData *)command->mParam.get();
1691 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001693 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001694 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1696 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1697 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001698 String8 key;
1699 String8 value;
1700 param.getAt(j, key, value);
1701 for (size_t k = 0; k < param2.size(); k++) {
1702 String8 key2;
1703 String8 value2;
1704 param2.getAt(k, key2, value2);
1705 if (key2 == key) {
1706 param2.remove(key2);
1707 ALOGV("Filtering out parameter %s", key2.string());
1708 break;
1709 }
1710 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 }
1712 // if all keys have been filtered out, remove the command.
1713 // otherwise, update the key value pairs
1714 if (param2.size() == 0) {
1715 removedCommands.add(command2);
1716 } else {
1717 data2->mKeyValuePairs = param2.toString();
1718 }
Eric Laurent21e54562013-09-23 12:08:05 -07001719 command->mTime = command2->mTime;
1720 // force delayMs to non 0 so that code below does not request to wait for
1721 // command status as the command is now delayed
1722 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 } break;
1724
1725 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001726 VolumeData *data = (VolumeData *)command->mParam.get();
1727 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 if (data->mIO != data2->mIO) break;
1729 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01001730 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07001731 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07001733 command->mTime = command2->mTime;
1734 // force delayMs to non 0 so that code below does not request to wait for
1735 // command status as the command is now delayed
1736 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001738
Eric Laurentbaf35fe2016-07-27 15:36:53 -07001739 case SET_VOICE_VOLUME: {
1740 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1741 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
1742 ALOGV("Filtering out voice volume command value %f replaced by %f",
1743 data2->mVolume, data->mVolume);
1744 removedCommands.add(command2);
1745 command->mTime = command2->mTime;
1746 // force delayMs to non 0 so that code below does not request to wait for
1747 // command status as the command is now delayed
1748 delayMs = 1;
1749 } break;
1750
Eric Laurente45b48a2014-09-04 16:40:57 -07001751 case CREATE_AUDIO_PATCH:
1752 case RELEASE_AUDIO_PATCH: {
1753 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001754 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001755 if (command->mCommand == CREATE_AUDIO_PATCH) {
1756 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001757 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001758 } else {
1759 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07001760 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07001761 }
1762 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001763 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07001764 if (command2->mCommand == CREATE_AUDIO_PATCH) {
1765 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001766 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001767 } else {
1768 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07001769 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07001770 }
1771 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001772 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
1773 same output. */
1774 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
1775 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
1776 bool isOutputDiff = false;
1777 if (patch.num_sources == patch2.num_sources) {
1778 for (unsigned count = 0; count < patch.num_sources; count++) {
1779 if (patch.sources[count].id != patch2.sources[count].id) {
1780 isOutputDiff = true;
1781 break;
1782 }
1783 }
1784 if (isOutputDiff)
1785 break;
1786 }
1787 }
Eric Laurente45b48a2014-09-04 16:40:57 -07001788 ALOGV("Filtering out %s audio patch command for handle %d",
1789 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
1790 removedCommands.add(command2);
1791 command->mTime = command2->mTime;
1792 // force delayMs to non 0 so that code below does not request to wait for
1793 // command status as the command is now delayed
1794 delayMs = 1;
1795 } break;
1796
Jean-Michel Trivide801052015-04-14 19:10:14 -07001797 case DYN_POLICY_MIX_STATE_UPDATE: {
1798
1799 } break;
1800
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001801 case RECORDING_CONFIGURATION_UPDATE: {
1802
1803 } break;
1804
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 default:
1806 break;
1807 }
1808 }
1809
1810 // remove filtered commands
1811 for (size_t j = 0; j < removedCommands.size(); j++) {
1812 // removed commands always have time stamps greater than current command
1813 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001814 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01001815 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816 mAudioCommands.removeAt(k);
1817 break;
1818 }
1819 }
1820 }
1821 removedCommands.clear();
1822
Eric Laurentaa79bef2015-01-15 14:33:51 -08001823 // Disable wait for status if delay is not 0.
1824 // Except for create audio patch command because the returned patch handle
1825 // is needed by audio policy manager
1826 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07001827 command->mWaitStatus = false;
1828 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07001829
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07001831 ALOGV("inserting command: %d at index %zd, num commands %zu",
1832 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 mAudioCommands.insertAt(command, i + 1);
1834}
1835
1836void AudioPolicyService::AudioCommandThread::exit()
1837{
Steve Block3856b092011-10-20 11:56:00 +01001838 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 {
1840 AutoMutex _l(mLock);
1841 requestExit();
1842 mWaitWorkCV.signal();
1843 }
Zach Janga754b4f2015-10-27 01:29:34 +00001844 // Note that we can call it from the thread loop if all other references have been released
1845 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 requestExitAndWait();
1847}
1848
1849void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1850{
1851 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
1852 mCommand,
1853 (int)ns2s(mTime),
1854 (int)ns2ms(mTime)%1000,
1855 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07001856 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857}
1858
Dima Zavinfce7a472011-04-19 22:30:36 -07001859/******* helpers for the service_ops callbacks defined below *********/
1860void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1861 const char *keyValuePairs,
1862 int delayMs)
1863{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001864 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07001865 delayMs);
1866}
1867
1868int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1869 float volume,
1870 audio_io_handle_t output,
1871 int delayMs)
1872{
Glenn Kastenfff6d712012-01-12 16:38:12 -08001873 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001874 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07001875}
1876
Dima Zavinfce7a472011-04-19 22:30:36 -07001877int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1878{
1879 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1880}
1881
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001882void AudioPolicyService::setEffectSuspended(int effectId,
1883 audio_session_t sessionId,
1884 bool suspended)
1885{
1886 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
1887}
1888
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001889void AudioPolicyService::onNewAudioModulesAvailable()
1890{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07001891 mOutputCommandThread->audioModulesUpdateCommand();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001892}
1893
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001894
Dima Zavinfce7a472011-04-19 22:30:36 -07001895extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08001896audio_module_handle_t aps_load_hw_module(void *service __unused,
1897 const char *name);
1898audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001899 audio_devices_t *pDevices,
1900 uint32_t *pSamplingRate,
1901 audio_format_t *pFormat,
1902 audio_channel_mask_t *pChannelMask,
1903 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001904 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001905
Eric Laurent2d388ec2014-03-07 13:25:54 -08001906audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001907 audio_module_handle_t module,
1908 audio_devices_t *pDevices,
1909 uint32_t *pSamplingRate,
1910 audio_format_t *pFormat,
1911 audio_channel_mask_t *pChannelMask,
1912 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001913 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001914 const audio_offload_info_t *offloadInfo);
1915audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07001916 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001917 audio_io_handle_t output2);
1918int aps_close_output(void *service __unused, audio_io_handle_t output);
1919int aps_suspend_output(void *service __unused, audio_io_handle_t output);
1920int aps_restore_output(void *service __unused, audio_io_handle_t output);
1921audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001922 audio_devices_t *pDevices,
1923 uint32_t *pSamplingRate,
1924 audio_format_t *pFormat,
1925 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001926 audio_in_acoustics_t acoustics __unused);
1927audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001928 audio_module_handle_t module,
1929 audio_devices_t *pDevices,
1930 uint32_t *pSamplingRate,
1931 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001932 audio_channel_mask_t *pChannelMask);
1933int aps_close_input(void *service __unused, audio_io_handle_t input);
1934int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08001935int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07001936 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001937 audio_io_handle_t dst_output);
1938char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
1939 const char *keys);
1940void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1941 const char *kv_pairs, int delay_ms);
1942int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07001943 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001944 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08001945int aps_set_voice_volume(void *service, float volume, int delay_ms);
1946};
Dima Zavinfce7a472011-04-19 22:30:36 -07001947
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08001948} // namespace android