blob: 59fb481d6492eca64d892c2352373760c5bca79f [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()
Eric Laurentdce54a12014-03-10 12:19:46 -070060 : BnAudioPolicyService(), mpAudioPolicyDev(NULL), mpAudioPolicy(NULL),
Eric Laurentbb6c9a02014-09-25 14:11:47 -070061 mAudioPolicyManager(NULL), mAudioPolicyClient(NULL), mPhoneState(AUDIO_MODE_INVALID)
Mathias Agopian65ab4712010-07-14 17:59:35 -070062{
Eric Laurentf5ada6e2014-10-09 17:49:00 -070063}
64
65void AudioPolicyService::onFirstRef()
66{
Eric Laurent8b1e80b2014-10-07 09:08:47 -070067 {
68 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -080069
Eric Laurent8b1e80b2014-10-07 09:08:47 -070070 // start audio commands thread
71 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
72 // start output activity command thread
73 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -070074
Eric Laurent8b1e80b2014-10-07 09:08:47 -070075 mAudioPolicyClient = new AudioPolicyClient(this);
76 mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
Hayden Gomes524159d2019-12-23 14:41:47 -080077
78 mSupportedSystemUsages = std::vector<audio_usage_t> {};
Eric Laurent8b1e80b2014-10-07 09:08:47 -070079 }
bryant_liuba2b4392014-06-11 16:49:30 +080080 // load audio processing modules
Eric Laurent8b1e80b2014-10-07 09:08:47 -070081 sp<AudioPolicyEffects>audioPolicyEffects = new AudioPolicyEffects();
82 {
83 Mutex::Autolock _l(mLock);
84 mAudioPolicyEffects = audioPolicyEffects;
85 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -080086
87 mUidPolicy = new UidPolicy(this);
88 mUidPolicy->registerSelf();
Michael Groovercfd28302018-12-11 19:16:46 -080089
90 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
91 mSensorPrivacyPolicy->registerSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -070092}
93
94AudioPolicyService::~AudioPolicyService()
95{
Mathias Agopian65ab4712010-07-14 17:59:35 -070096 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -070097 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -070098
Eric Laurentf269b8e2014-06-09 20:01:29 -070099 destroyAudioPolicyManager(mAudioPolicyManager);
Eric Laurentdce54a12014-03-10 12:19:46 -0700100 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700101
102 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800103 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800104
105 mUidPolicy->unregisterSelf();
106 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800107
108 mSensorPrivacyPolicy->unregisterSelf();
109 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700110}
111
112// A notification client is always registered by AudioSystem when the client process
113// connects to AudioPolicyService.
114void AudioPolicyService::registerClient(const sp<IAudioPolicyServiceClient>& client)
115{
Eric Laurent12590252015-08-21 18:40:20 -0700116 if (client == 0) {
117 ALOGW("%s got NULL client", __FUNCTION__);
118 return;
119 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800120 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700121
122 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800123 pid_t pid = IPCThreadState::self()->getCallingPid();
124 int64_t token = ((int64_t)uid<<32) | pid;
125
126 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700127 sp<NotificationClient> notificationClient = new NotificationClient(this,
128 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800129 uid,
130 pid);
131 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700132
luochaojiang908c7d72018-06-21 14:58:04 +0800133 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700134
Marco Nelissenf8880202014-11-14 07:58:25 -0800135 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700136 binder->linkToDeath(notificationClient);
137 }
138}
139
Eric Laurente8726fe2015-06-26 09:39:24 -0700140void AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
141{
142 Mutex::Autolock _l(mNotificationClientsLock);
143
144 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800145 pid_t pid = IPCThreadState::self()->getCallingPid();
146 int64_t token = ((int64_t)uid<<32) | pid;
147
148 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurente8726fe2015-06-26 09:39:24 -0700149 return;
150 }
luochaojiang908c7d72018-06-21 14:58:04 +0800151 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Eric Laurente8726fe2015-06-26 09:39:24 -0700152}
153
François Gaffiecfe17322018-11-07 13:41:29 +0100154void AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
155{
156 Mutex::Autolock _l(mNotificationClientsLock);
157
158 uid_t uid = IPCThreadState::self()->getCallingUid();
159 pid_t pid = IPCThreadState::self()->getCallingPid();
160 int64_t token = ((int64_t)uid<<32) | pid;
161
162 if (mNotificationClients.indexOfKey(token) < 0) {
163 return;
164 }
165 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
166}
167
Eric Laurentb52c1522014-05-20 11:27:36 -0700168// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800169void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700170{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800171 {
172 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800173 int64_t token = ((int64_t)uid<<32) | pid;
174 mNotificationClients.removeItem(token);
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800175 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800176 {
177 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800178 bool hasSameUid = false;
179 for (size_t i = 0; i < mNotificationClients.size(); i++) {
180 if (mNotificationClients.valueAt(i)->uid() == uid) {
181 hasSameUid = true;
182 break;
183 }
184 }
185 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700186 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700187 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700188 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800189 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700190}
191
192void AudioPolicyService::onAudioPortListUpdate()
193{
194 mOutputCommandThread->updateAudioPortListCommand();
195}
196
197void AudioPolicyService::doOnAudioPortListUpdate()
198{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800199 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700200 for (size_t i = 0; i < mNotificationClients.size(); i++) {
201 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
202 }
203}
204
205void AudioPolicyService::onAudioPatchListUpdate()
206{
207 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208}
209
Eric Laurentb52c1522014-05-20 11:27:36 -0700210void AudioPolicyService::doOnAudioPatchListUpdate()
211{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800212 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700213 for (size_t i = 0; i < mNotificationClients.size(); i++) {
214 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
215 }
216}
217
François Gaffiecfe17322018-11-07 13:41:29 +0100218void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
219{
220 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
221}
222
223void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
224{
225 Mutex::Autolock _l(mNotificationClientsLock);
226 for (size_t i = 0; i < mNotificationClients.size(); i++) {
227 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
228 }
229}
230
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700231void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700232{
233 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
234 regId.string(), state);
235 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
236}
237
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700238void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700239{
240 Mutex::Autolock _l(mNotificationClientsLock);
241 for (size_t i = 0; i < mNotificationClients.size(); i++) {
242 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
243 }
244}
245
Eric Laurenta9f86652018-11-28 17:23:11 -0800246void AudioPolicyService::onRecordingConfigurationUpdate(
247 int event,
248 const record_client_info_t *clientInfo,
249 const audio_config_base_t *clientConfig,
250 std::vector<effect_descriptor_t> clientEffects,
251 const audio_config_base_t *deviceConfig,
252 std::vector<effect_descriptor_t> effects,
253 audio_patch_handle_t patchHandle,
254 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800255{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800256 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800257 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800258}
259
Eric Laurenta9f86652018-11-28 17:23:11 -0800260void AudioPolicyService::doOnRecordingConfigurationUpdate(
261 int event,
262 const record_client_info_t *clientInfo,
263 const audio_config_base_t *clientConfig,
264 std::vector<effect_descriptor_t> clientEffects,
265 const audio_config_base_t *deviceConfig,
266 std::vector<effect_descriptor_t> effects,
267 audio_patch_handle_t patchHandle,
268 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800269{
270 Mutex::Autolock _l(mNotificationClientsLock);
271 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800272 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800273 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800274 }
275}
276
277status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
278 audio_patch_handle_t *handle,
279 int delayMs)
280{
281 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
282}
283
284status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
285 int delayMs)
286{
287 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
288}
289
Eric Laurente1715a42014-05-20 11:30:42 -0700290status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
291 int delayMs)
292{
293 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
294}
295
Eric Laurentb52c1522014-05-20 11:27:36 -0700296AudioPolicyService::NotificationClient::NotificationClient(const sp<AudioPolicyService>& service,
297 const sp<IAudioPolicyServiceClient>& client,
luochaojiang908c7d72018-06-21 14:58:04 +0800298 uid_t uid,
299 pid_t pid)
300 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100301 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700302{
303}
304
305AudioPolicyService::NotificationClient::~NotificationClient()
306{
307}
308
309void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
310{
311 sp<NotificationClient> keep(this);
312 sp<AudioPolicyService> service = mService.promote();
313 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800314 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700315 }
316}
317
318void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
319{
Eric Laurente8726fe2015-06-26 09:39:24 -0700320 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700321 mAudioPolicyServiceClient->onAudioPortListUpdate();
322 }
323}
324
325void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
326{
Eric Laurente8726fe2015-06-26 09:39:24 -0700327 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700328 mAudioPolicyServiceClient->onAudioPatchListUpdate();
329 }
330}
Eric Laurent57dae992011-07-24 13:36:09 -0700331
François Gaffiecfe17322018-11-07 13:41:29 +0100332void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
333 int flags)
334{
335 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
336 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
337 }
338}
339
340
Jean-Michel Trivide801052015-04-14 19:10:14 -0700341void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700342 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700343{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700344 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800345 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(regId, state);
346 }
347}
348
349void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800350 int event,
351 const record_client_info_t *clientInfo,
352 const audio_config_base_t *clientConfig,
353 std::vector<effect_descriptor_t> clientEffects,
354 const audio_config_base_t *deviceConfig,
355 std::vector<effect_descriptor_t> effects,
356 audio_patch_handle_t patchHandle,
357 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800358{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700359 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800360 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800361 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700362 }
363}
364
Eric Laurente8726fe2015-06-26 09:39:24 -0700365void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
366{
367 mAudioPortCallbacksEnabled = enabled;
368}
369
François Gaffiecfe17322018-11-07 13:41:29 +0100370void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
371{
372 mAudioVolumeGroupCallbacksEnabled = enabled;
373}
Eric Laurente8726fe2015-06-26 09:39:24 -0700374
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700376 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700377 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700378}
379
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700380static bool dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700381{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700382 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
383 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384}
385
386status_t AudioPolicyService::dumpInternals(int fd)
387{
388 const size_t SIZE = 256;
389 char buffer[SIZE];
390 String8 result;
391
Eric Laurentdce54a12014-03-10 12:19:46 -0700392 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393 result.append(buffer);
394 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
395 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700396
Hayden Gomes524159d2019-12-23 14:41:47 -0800397 snprintf(buffer, SIZE, "Supported System Usages:\n");
398 result.append(buffer);
399 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
400 it != mSupportedSystemUsages.end(); ++it) {
401 snprintf(buffer, SIZE, "\t%d\n", *it);
402 result.append(buffer);
403 }
404
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 write(fd, result.string(), result.size());
406 return NO_ERROR;
407}
408
Eric Laurente8c8b432018-10-17 10:08:02 -0700409void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800410{
Eric Laurente8c8b432018-10-17 10:08:02 -0700411 Mutex::Autolock _l(mLock);
412 updateUidStates_l();
413}
414
415void AudioPolicyService::updateUidStates_l()
416{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800417// Go over all active clients and allow capture (does not force silence) in the
418// following cases:
Eric Laurent8ed73c12019-08-30 17:25:19 -0700419// The client is the assistant
Eric Laurent6ede98f2019-06-11 14:50:30 -0700420// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700421// AND the source is VOICE_RECOGNITION or HOTWORD
422// OR uses VOICE_RECOGNITION AND is on TOP
423// OR uses HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700424// AND there is no active privacy sensitive capture or call
425// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta46bedb2018-12-07 18:01:26 -0800426// OR The client is an accessibility service
Eric Laurent589171c2019-07-25 18:04:29 -0700427// AND Is on TOP
428// AND the source is VOICE_RECOGNITION or HOTWORD
429// OR The assistant is not on TOP
430// AND there is no active privacy sensitive capture or call
431// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta171e352019-05-07 13:04:45 -0700432// AND is on TOP
Eric Laurenta46bedb2018-12-07 18:01:26 -0800433// AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700434// OR the client source is virtual (remote submix, call audio TX or RX...)
Eric Laurent4e947da2019-10-17 15:24:06 -0700435// OR the client source is HOTWORD
436// AND is on TOP
437// OR all active clients are using HOTWORD source
438// AND no call is active
439// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta171e352019-05-07 13:04:45 -0700440// OR Any client
Eric Laurenta46bedb2018-12-07 18:01:26 -0800441// AND The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700442// AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700443// AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700444// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800445
Eric Laurent4e947da2019-10-17 15:24:06 -0700446
Eric Laurent4eb58f12018-12-07 16:41:02 -0800447 sp<AudioRecordClient> topActive;
448 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800449 sp<AudioRecordClient> topSensitiveActive;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800450 sp<AudioRecordClient> latestSensitiveActive;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700451
Eric Laurenta46bedb2018-12-07 18:01:26 -0800452 nsecs_t topStartNs = 0;
453 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800454 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800455 nsecs_t latestSensitiveStartNs = 0;
456 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
457 bool isAssistantOnTop = false;
458 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700459 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800460 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
461 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700462 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700463 bool onlyHotwordActive = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800464
Michael Groovercfd28302018-12-11 19:16:46 -0800465 // if Sensor Privacy is enabled then all recordings should be silenced.
466 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
467 silenceAllRecordings_l();
468 return;
469 }
470
Eric Laurente8c8b432018-10-17 10:08:02 -0700471 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
472 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700473 if (!current->active) {
474 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800475 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700476
477 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
478 // clients which app is in IDLE state are not eligible for top active or
479 // latest active
480 if (appState == APP_STATE_IDLE) {
481 continue;
482 }
483
Eric Laurent589171c2019-07-25 18:04:29 -0700484 bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800485 // Clients capturing for Accessibility services are not considered
486 // for top or latest active to avoid masking regular clients started before
487 if (!isAccessibility) {
488 bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
489 bool isPrivacySensitive =
490 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
491 if (appState == APP_STATE_TOP) {
492 if (isPrivacySensitive) {
493 if (current->startTimeNs > topSensitiveStartNs) {
494 topSensitiveActive = current;
495 topSensitiveStartNs = current->startTimeNs;
496 }
497 } else {
498 if (current->startTimeNs > topStartNs) {
499 topActive = current;
500 topStartNs = current->startTimeNs;
501 }
502 }
503 if (isAssistant) {
504 isAssistantOnTop = true;
505 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800506 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800507 // Clients capturing for HOTWORD are not considered
508 // for latest active to avoid masking regular clients started before
509 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
510 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
511 if (isPrivacySensitive) {
512 if (current->startTimeNs > latestSensitiveStartNs) {
513 latestSensitiveActive = current;
514 latestSensitiveStartNs = current->startTimeNs;
515 }
516 isSensitiveActive = true;
517 } else {
518 if (current->startTimeNs > latestStartNs) {
519 latestActive = current;
520 latestStartNs = current->startTimeNs;
521 }
522 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800523 }
524 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700525 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
526 onlyHotwordActive = false;
527 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800528 }
529
Eric Laurent1ff16a72019-03-14 18:35:04 -0700530 // if no active client with UI on Top, consider latest active as top
531 if (topActive == nullptr) {
532 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800533 topStartNs = latestStartNs;
534 }
535 if (topSensitiveActive == nullptr) {
536 topSensitiveActive = latestSensitiveActive;
537 topSensitiveStartNs = latestSensitiveStartNs;
538 }
539
540 // If both privacy sensitive and regular capture are active:
541 // if the regular capture is privileged
542 // allow concurrency
543 // else
544 // favor the privacy sensitive case
545 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700546 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800547 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800548 }
549
550 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
551 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700552 if (!current->active) {
553 continue;
554 }
555
Eric Laurent4eb58f12018-12-07 16:41:02 -0800556 audio_source_t source = current->attributes.source;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700557 bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800558 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ?
559 false : current->uid == topSensitiveActive->uid;
560
561 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700562 bool canCaptureCall = recordClient->canCaptureOutput;
563 bool canCaptureCommunication = recordClient->canCaptureOutput
Eric Laurentc21d5692020-02-25 10:24:36 -0800564 || recordClient->uid == mPhoneStateOwnerUid
565 || isServiceUid(mPhoneStateOwnerUid);
566 return !(isInCall && !canCaptureCall)
567 && !(isInCommunication && !canCaptureCommunication);
568 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700569
570 // By default allow capture if:
571 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700572 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700573 // AND there is no active privacy sensitive capture or call
574 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
575 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800576 && (isTopOrLatestActive || isTopOrLatestSensitive)
577 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700578 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800579 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800580
581 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700582 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
583 allowCapture = true;
Eric Laurent2dc962b2019-03-01 08:25:25 -0800584 } else if (mUidPolicy->isAssistantUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700585 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700586 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700587 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700588 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700589 // OR uses HOTWORD
590 // AND there is no active privacy sensitive capture or call
591 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700592 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800593 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700594 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800595 }
596 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700597 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800598 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700599 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800600 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700601 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800602 }
603 }
604 } else if (mUidPolicy->isA11yUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700605 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700606 // The assistant is not on TOP
607 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700608 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700609 // OR
610 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
611 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700612 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800613 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700614 allowCapture = true;
615 }
Eric Laurent589171c2019-07-25 18:04:29 -0700616 if (isA11yOnTop) {
617 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
618 allowCapture = true;
619 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800620 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700621 } else if (source == AUDIO_SOURCE_HOTWORD) {
622 // For HOTWORD source allow capture when not on TOP if:
623 // All active clients are using HOTWORD source
624 // AND no call is active
625 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800626 if (onlyHotwordActive
627 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700628 allowCapture = true;
629 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800630 }
Eric Laurent5ada82e2019-08-29 17:53:54 -0700631 setAppState_l(current->portId,
Eric Laurent1ff16a72019-03-14 18:35:04 -0700632 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
633 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700634 }
635}
636
Michael Groovercfd28302018-12-11 19:16:46 -0800637void AudioPolicyService::silenceAllRecordings_l() {
638 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
639 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700640 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700641 setAppState_l(current->portId, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700642 }
Michael Groovercfd28302018-12-11 19:16:46 -0800643 }
644}
645
Eric Laurente8c8b432018-10-17 10:08:02 -0700646/* static */
647app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700648
649 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700650 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700651 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
652 // include persistent services
653 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700654 }
655 return APP_STATE_FOREGROUND;
656}
657
Eric Laurent4eb58f12018-12-07 16:41:02 -0800658/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800659bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800660{
661 switch (source) {
662 case AUDIO_SOURCE_VOICE_UPLINK:
663 case AUDIO_SOURCE_VOICE_DOWNLINK:
664 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800665 case AUDIO_SOURCE_REMOTE_SUBMIX:
666 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800667 return true;
668 default:
669 break;
670 }
671 return false;
672}
673
Eric Laurent5ada82e2019-08-29 17:53:54 -0700674void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700675{
676 AutoCallerClear acc;
677
678 if (mAudioPolicyManager) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700679 mAudioPolicyManager->setAppState(portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700680 }
681 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
682 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700683 bool silenced = state == APP_STATE_IDLE;
Eric Laurent5ada82e2019-08-29 17:53:54 -0700684 af->setRecordSilenced(portId, silenced);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700685 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800686}
687
Glenn Kasten0f11b512014-01-31 16:18:54 -0800688status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689{
Glenn Kasten44deb052012-02-05 18:09:08 -0800690 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691 dumpPermissionDenial(fd);
692 } else {
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700693 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 if (!locked) {
695 String8 result(kDeadlockedString);
696 write(fd, result.string(), result.size());
697 }
698
699 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800700 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 mAudioCommandThread->dump(fd);
702 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703
Eric Laurentdce54a12014-03-10 12:19:46 -0700704 if (mAudioPolicyManager) {
705 mAudioPolicyManager->dump(fd);
706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707
Kevin Rocard8be94972019-02-22 13:26:25 -0800708 mPackageManager.dump(fd);
709
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 if (locked) mLock.unlock();
711 }
712 return NO_ERROR;
713}
714
715status_t AudioPolicyService::dumpPermissionDenial(int fd)
716{
717 const size_t SIZE = 256;
718 char buffer[SIZE];
719 String8 result;
720 snprintf(buffer, SIZE, "Permission Denial: "
721 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
722 IPCThreadState::self()->getCallingPid(),
723 IPCThreadState::self()->getCallingUid());
724 result.append(buffer);
725 write(fd, result.string(), result.size());
726 return NO_ERROR;
727}
728
729status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800730 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
731 switch (code) {
732 case SHELL_COMMAND_TRANSACTION: {
733 int in = data.readFileDescriptor();
734 int out = data.readFileDescriptor();
735 int err = data.readFileDescriptor();
736 int argc = data.readInt32();
737 Vector<String16> args;
738 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
739 args.add(data.readString16());
740 }
741 sp<IBinder> unusedCallback;
742 sp<IResultReceiver> resultReceiver;
743 status_t status;
744 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
745 return status;
746 }
747 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
748 return status;
749 }
750 status = shellCommand(in, out, err, args);
751 if (resultReceiver != nullptr) {
752 resultReceiver->send(status);
753 }
754 return NO_ERROR;
755 }
756 }
757
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 return BnAudioPolicyService::onTransact(code, data, reply, flags);
759}
760
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800761// ------------------- Shell command implementation -------------------
762
763// NOTE: This is a remote API - make sure all args are validated
764status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
765 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
766 return PERMISSION_DENIED;
767 }
768 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
769 return BAD_VALUE;
770 }
jovanakbe066e12019-09-02 11:54:39 -0700771 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800772 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700773 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800774 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700775 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800776 return handleGetUidState(args, out, err);
777 } else if (args.size() == 1 && args[0] == String16("help")) {
778 printHelp(out);
779 return NO_ERROR;
780 }
781 printHelp(err);
782 return BAD_VALUE;
783}
784
jovanakbe066e12019-09-02 11:54:39 -0700785static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
786 if (userId < 0) {
787 ALOGE("Invalid user: %d", userId);
788 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800789 return BAD_VALUE;
790 }
jovanakbe066e12019-09-02 11:54:39 -0700791
792 PermissionController pc;
793 uid = pc.getPackageUid(packageName, 0);
794 if (uid <= 0) {
795 ALOGE("Unknown package: '%s'", String8(packageName).string());
796 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
797 return BAD_VALUE;
798 }
799
800 uid = multiuser_get_uid(userId, uid);
801 return NO_ERROR;
802}
803
804status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
805 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
806 if (!(args.size() == 3 || args.size() == 5)) {
807 printHelp(err);
808 return BAD_VALUE;
809 }
810
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800811 bool active = false;
812 if (args[2] == String16("active")) {
813 active = true;
814 } else if ((args[2] != String16("idle"))) {
815 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
816 return BAD_VALUE;
817 }
jovanakbe066e12019-09-02 11:54:39 -0700818
819 int userId = 0;
820 if (args.size() >= 5 && args[3] == String16("--user")) {
821 userId = atoi(String8(args[4]));
822 }
823
824 uid_t uid;
825 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
826 return BAD_VALUE;
827 }
828
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800829 mUidPolicy->addOverrideUid(uid, active);
830 return NO_ERROR;
831}
832
833status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -0700834 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
835 if (!(args.size() == 2 || args.size() == 4)) {
836 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800837 return BAD_VALUE;
838 }
jovanakbe066e12019-09-02 11:54:39 -0700839
840 int userId = 0;
841 if (args.size() >= 4 && args[2] == String16("--user")) {
842 userId = atoi(String8(args[3]));
843 }
844
845 uid_t uid;
846 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
847 return BAD_VALUE;
848 }
849
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800850 mUidPolicy->removeOverrideUid(uid);
851 return NO_ERROR;
852}
853
854status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -0700855 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
856 if (!(args.size() == 2 || args.size() == 4)) {
857 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800858 return BAD_VALUE;
859 }
jovanakbe066e12019-09-02 11:54:39 -0700860
861 int userId = 0;
862 if (args.size() >= 4 && args[2] == String16("--user")) {
863 userId = atoi(String8(args[3]));
864 }
865
866 uid_t uid;
867 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
868 return BAD_VALUE;
869 }
870
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800871 if (mUidPolicy->isUidActive(uid)) {
872 return dprintf(out, "active\n");
873 } else {
874 return dprintf(out, "idle\n");
875 }
876}
877
878status_t AudioPolicyService::printHelp(int out) {
879 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -0700880 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
881 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
882 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800883 " help print this message\n");
884}
885
886// ----------- AudioPolicyService::UidPolicy implementation ----------
887
888void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -0700889 status_t res = mAm.linkToDeath(this);
890 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800891 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -0700892 | ActivityManager::UID_OBSERVER_ACTIVE
893 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800894 ActivityManager::PROCESS_STATE_UNKNOWN,
895 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700896 if (!res) {
897 Mutex::Autolock _l(mLock);
898 mObserverRegistered = true;
899 } else {
900 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -0800901
Steven Moreland2f348142019-07-02 15:59:07 -0700902 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700903 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800904}
905
906void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -0700907 mAm.unlinkToDeath(this);
908 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700909 Mutex::Autolock _l(mLock);
910 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800911}
912
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700913void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
914 Mutex::Autolock _l(mLock);
915 mCachedUids.clear();
916 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800917}
918
Eric Laurente8c8b432018-10-17 10:08:02 -0700919void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700920 bool needToReregister = false;
921 {
922 Mutex::Autolock _l(mLock);
923 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800924 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700925 if (needToReregister) {
926 // Looks like ActivityManager has died previously, attempt to re-register.
927 registerSelf();
928 }
Eric Laurente8c8b432018-10-17 10:08:02 -0700929}
930
931bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
932 if (isServiceUid(uid)) return true;
933 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700934 {
935 Mutex::Autolock _l(mLock);
936 auto overrideIter = mOverrideUids.find(uid);
937 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700938 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700939 }
940 // In an absense of the ActivityManager, assume everything to be active.
941 if (!mObserverRegistered) return true;
942 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -0700943 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700944 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700945 }
946 }
947 ActivityManager am;
948 bool active = am.isUidActive(uid, String16("audioserver"));
949 {
950 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -0700951 mCachedUids.insert(std::pair<uid_t,
952 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
953 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700954 }
955 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800956}
957
Eric Laurente8c8b432018-10-17 10:08:02 -0700958int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
959 if (isServiceUid(uid)) {
960 return ActivityManager::PROCESS_STATE_TOP;
961 }
962 checkRegistered();
963 {
964 Mutex::Autolock _l(mLock);
965 auto overrideIter = mOverrideUids.find(uid);
966 if (overrideIter != mOverrideUids.end()) {
967 if (overrideIter->second.first) {
968 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
969 return overrideIter->second.second;
970 } else {
971 auto cacheIter = mCachedUids.find(uid);
972 if (cacheIter != mCachedUids.end()) {
973 return cacheIter->second.second;
974 }
975 }
976 }
977 return ActivityManager::PROCESS_STATE_UNKNOWN;
978 }
979 // In an absense of the ActivityManager, assume everything to be active.
980 if (!mObserverRegistered) {
981 return ActivityManager::PROCESS_STATE_TOP;
982 }
983 auto cacheIter = mCachedUids.find(uid);
984 if (cacheIter != mCachedUids.end()) {
985 if (cacheIter->second.first) {
986 return cacheIter->second.second;
987 } else {
988 return ActivityManager::PROCESS_STATE_UNKNOWN;
989 }
990 }
991 }
992 ActivityManager am;
993 bool active = am.isUidActive(uid, String16("audioserver"));
994 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
995 if (active) {
996 state = am.getUidProcessState(uid, String16("audioserver"));
997 }
998 {
999 Mutex::Autolock _l(mLock);
1000 mCachedUids.insert(std::pair<uid_t,
1001 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1002 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001003
Eric Laurente8c8b432018-10-17 10:08:02 -07001004 return state;
1005}
1006
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001007void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001008 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001009}
1010
1011void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001012 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001013}
1014
1015void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001016 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001017}
1018
Eric Laurente8c8b432018-10-17 10:08:02 -07001019void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1020 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001021 int64_t procStateSeq __unused,
1022 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001023 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1024 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001025 }
1026}
1027
1028void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001029 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1030}
1031
1032void AudioPolicyService::UidPolicy::notifyService() {
1033 sp<AudioPolicyService> service = mService.promote();
1034 if (service != nullptr) {
1035 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001036 }
1037}
1038
Eric Laurente8c8b432018-10-17 10:08:02 -07001039void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1040 std::pair<bool, int>> *uids,
1041 uid_t uid,
1042 bool active,
1043 int state,
1044 bool insert) {
1045 if (isServiceUid(uid)) {
1046 return;
1047 }
1048 bool wasActive = isUidActive(uid);
1049 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001050 {
1051 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001052 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001053 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001054 if (wasActive != isUidActive(uid) || state != previousState) {
1055 notifyService();
1056 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001057}
1058
Eric Laurente8c8b432018-10-17 10:08:02 -07001059void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1060 std::pair<bool, int>> *uids,
1061 uid_t uid,
1062 bool active,
1063 int state,
1064 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001065 auto it = uids->find(uid);
1066 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001067 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001068 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1069 it->second.first = active;
1070 }
1071 if (it->second.first) {
1072 it->second.second = state;
1073 } else {
1074 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1075 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001076 } else {
1077 uids->erase(it);
1078 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001079 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1080 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1081 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001082 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001083}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084
Eric Laurent4eb58f12018-12-07 16:41:02 -08001085bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1086 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001087 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001088 continue;
1089 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001090 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1091 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001092 return true;
1093 }
1094 }
1095 return false;
1096}
1097
Eric Laurentb78763e2018-10-17 10:08:02 -07001098bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1099{
1100 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1101 return it != mA11yUids.end();
1102}
1103
Michael Groovercfd28302018-12-11 19:16:46 -08001104// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1105void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1106 SensorPrivacyManager spm;
1107 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1108 spm.addSensorPrivacyListener(this);
1109}
1110
1111void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1112 SensorPrivacyManager spm;
1113 spm.removeSensorPrivacyListener(this);
1114}
1115
1116bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1117 return mSensorPrivacyEnabled;
1118}
1119
1120binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1121 mSensorPrivacyEnabled = enabled;
1122 sp<AudioPolicyService> service = mService.promote();
1123 if (service != nullptr) {
1124 service->updateUidStates();
1125 }
1126 return binder::Status::ok();
1127}
1128
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1130
Eric Laurentbfb1b832013-01-07 09:53:42 -08001131AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1132 const wp<AudioPolicyService>& service)
1133 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135}
1136
1137
1138AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1139{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001140 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 release_wake_lock(mName.string());
1142 }
1143 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144}
1145
1146void AudioPolicyService::AudioCommandThread::onFirstRef()
1147{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001148 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149}
1150
1151bool AudioPolicyService::AudioCommandThread::threadLoop()
1152{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001153 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154
1155 mLock.lock();
1156 while (!exitPending())
1157 {
Eric Laurent59a89232014-06-08 14:14:17 -07001158 sp<AudioPolicyService> svc;
1159 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 nsecs_t curTime = systemTime();
1161 // commands are sorted by increasing time stamp: execute them from index 0 and up
1162 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001163 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001165 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166
1167 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001169 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001170 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001171 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001172 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001173 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1174 data->mVolume,
1175 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001176 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 }break;
1178 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001179 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001180 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1181 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001182 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001183 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001184 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001185 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001187 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001188 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001189 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001190 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001192 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001194 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001195 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001196 ALOGV("AudioCommandThread() processing stop output portId %d",
1197 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001198 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001199 if (svc == 0) {
1200 break;
1201 }
1202 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001203 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001204 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001205 }break;
1206 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001207 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001208 ALOGV("AudioCommandThread() processing release 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->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001216 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001217 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001218 case CREATE_AUDIO_PATCH: {
1219 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1220 ALOGV("AudioCommandThread() processing create audio patch");
1221 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1222 if (af == 0) {
1223 command->mStatus = PERMISSION_DENIED;
1224 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001225 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001226 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001227 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001228 }
1229 } break;
1230 case RELEASE_AUDIO_PATCH: {
1231 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1232 ALOGV("AudioCommandThread() processing release 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->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001239 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001240 }
1241 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001242 case UPDATE_AUDIOPORT_LIST: {
1243 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001244 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001245 if (svc == 0) {
1246 break;
1247 }
1248 mLock.unlock();
1249 svc->doOnAudioPortListUpdate();
1250 mLock.lock();
1251 }break;
1252 case UPDATE_AUDIOPATCH_LIST: {
1253 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001254 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001255 if (svc == 0) {
1256 break;
1257 }
1258 mLock.unlock();
1259 svc->doOnAudioPatchListUpdate();
1260 mLock.lock();
1261 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001262 case CHANGED_AUDIOVOLUMEGROUP: {
1263 AudioVolumeGroupData *data =
1264 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1265 ALOGV("AudioCommandThread() processing update audio volume group");
1266 svc = mService.promote();
1267 if (svc == 0) {
1268 break;
1269 }
1270 mLock.unlock();
1271 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1272 mLock.lock();
1273 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001274 case SET_AUDIOPORT_CONFIG: {
1275 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1276 ALOGV("AudioCommandThread() processing set port config");
1277 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1278 if (af == 0) {
1279 command->mStatus = PERMISSION_DENIED;
1280 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001281 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001282 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001283 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001284 }
1285 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001286 case DYN_POLICY_MIX_STATE_UPDATE: {
1287 DynPolicyMixStateUpdateData *data =
1288 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001289 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1290 data->mRegId.string(), data->mState);
1291 svc = mService.promote();
1292 if (svc == 0) {
1293 break;
1294 }
1295 mLock.unlock();
1296 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1297 mLock.lock();
1298 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001299 case RECORDING_CONFIGURATION_UPDATE: {
1300 RecordingConfigurationUpdateData *data =
1301 (RecordingConfigurationUpdateData *)command->mParam.get();
1302 ALOGV("AudioCommandThread() processing recording configuration update");
1303 svc = mService.promote();
1304 if (svc == 0) {
1305 break;
1306 }
1307 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001308 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001309 &data->mClientConfig, data->mClientEffects,
1310 &data->mDeviceConfig, data->mEffects,
1311 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001312 mLock.lock();
1313 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001314 case SET_EFFECT_SUSPENDED: {
1315 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1316 ALOGV("AudioCommandThread() processing set effect suspended");
1317 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1318 if (af != 0) {
1319 mLock.unlock();
1320 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1321 mLock.lock();
1322 }
1323 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001324 case AUDIO_MODULES_UPDATE: {
1325 ALOGV("AudioCommandThread() processing audio modules update");
1326 svc = mService.promote();
1327 if (svc == 0) {
1328 break;
1329 }
1330 mLock.unlock();
1331 svc->doOnNewAudioModulesAvailable();
1332 mLock.lock();
1333 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001334
Mathias Agopian65ab4712010-07-14 17:59:35 -07001335 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001336 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001338 {
1339 Mutex::Autolock _l(command->mLock);
1340 if (command->mWaitStatus) {
1341 command->mWaitStatus = false;
1342 command->mCond.signal();
1343 }
1344 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001345 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001346 // release mLock before releasing strong reference on the service as
1347 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1348 // acquires mLock.
1349 mLock.unlock();
1350 svc.clear();
1351 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352 } else {
1353 waitTime = mAudioCommands[0]->mTime - curTime;
1354 break;
1355 }
1356 }
Zach Janga754b4f2015-10-27 01:29:34 +00001357
1358 // release delayed commands wake lock if the queue is empty
1359 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001360 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001361 }
1362
1363 // At this stage we have either an empty command queue or the first command in the queue
1364 // has a finite delay. So unless we are exiting it is safe to wait.
1365 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001366 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001367 if (waitTime == -1) {
1368 mWaitWorkCV.wait(mLock);
1369 } else {
1370 mWaitWorkCV.waitRelative(mLock, waitTime);
1371 }
Eric Laurent59a89232014-06-08 14:14:17 -07001372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001374 // release delayed commands wake lock before quitting
1375 if (!mAudioCommands.isEmpty()) {
1376 release_wake_lock(mName.string());
1377 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378 mLock.unlock();
1379 return false;
1380}
1381
1382status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1383{
1384 const size_t SIZE = 256;
1385 char buffer[SIZE];
1386 String8 result;
1387
1388 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1389 result.append(buffer);
1390 write(fd, result.string(), result.size());
1391
Mikhail Naganov959e2d02019-03-28 11:08:19 -07001392 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393 if (!locked) {
1394 String8 result2(kCmdDeadlockedString);
1395 write(fd, result2.string(), result2.size());
1396 }
1397
1398 snprintf(buffer, SIZE, "- Commands:\n");
1399 result = String8(buffer);
1400 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001401 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402 mAudioCommands[i]->dump(buffer, SIZE);
1403 result.append(buffer);
1404 }
1405 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001406 if (mLastCommand != 0) {
1407 mLastCommand->dump(buffer, SIZE);
1408 result.append(buffer);
1409 } else {
1410 result.append(" none\n");
1411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412
1413 write(fd, result.string(), result.size());
1414
1415 if (locked) mLock.unlock();
1416
1417 return NO_ERROR;
1418}
1419
Glenn Kastenfff6d712012-01-12 16:38:12 -08001420status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001421 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001422 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001423 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424{
Eric Laurent0ede8922014-05-09 18:04:42 -07001425 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001427 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428 data->mStream = stream;
1429 data->mVolume = volume;
1430 data->mIO = output;
1431 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001432 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001433 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001434 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001435 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436}
1437
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001438status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001439 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001440 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441{
Eric Laurent0ede8922014-05-09 18:04:42 -07001442 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001444 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001446 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001448 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001449 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001450 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001451 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452}
1453
1454status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1455{
Eric Laurent0ede8922014-05-09 18:04:42 -07001456 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001458 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 data->mVolume = volume;
1460 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001461 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001463 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464}
1465
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001466void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1467 audio_session_t sessionId,
1468 bool suspended)
1469{
1470 sp<AudioCommand> command = new AudioCommand();
1471 command->mCommand = SET_EFFECT_SUSPENDED;
1472 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1473 data->mEffectId = effectId;
1474 data->mSessionId = sessionId;
1475 data->mSuspended = suspended;
1476 command->mParam = data;
1477 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1478 effectId, sessionId, suspended);
1479 sendCommand(command);
1480}
1481
1482
Eric Laurentd7fe0862018-07-14 16:48:01 -07001483void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001484{
Eric Laurent0ede8922014-05-09 18:04:42 -07001485 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001486 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001487 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001488 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001489 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001490 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001491 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001492}
1493
Eric Laurentd7fe0862018-07-14 16:48:01 -07001494void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001495{
Eric Laurent0ede8922014-05-09 18:04:42 -07001496 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001497 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001498 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001499 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001500 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001501 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001502 sendCommand(command);
1503}
1504
Eric Laurent951f4552014-05-20 10:48:17 -07001505status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1506 const struct audio_patch *patch,
1507 audio_patch_handle_t *handle,
1508 int delayMs)
1509{
1510 status_t status = NO_ERROR;
1511
1512 sp<AudioCommand> command = new AudioCommand();
1513 command->mCommand = CREATE_AUDIO_PATCH;
1514 CreateAudioPatchData *data = new CreateAudioPatchData();
1515 data->mPatch = *patch;
1516 data->mHandle = *handle;
1517 command->mParam = data;
1518 command->mWaitStatus = true;
1519 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1520 status = sendCommand(command, delayMs);
1521 if (status == NO_ERROR) {
1522 *handle = data->mHandle;
1523 }
1524 return status;
1525}
1526
1527status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1528 int delayMs)
1529{
1530 sp<AudioCommand> command = new AudioCommand();
1531 command->mCommand = RELEASE_AUDIO_PATCH;
1532 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1533 data->mHandle = handle;
1534 command->mParam = data;
1535 command->mWaitStatus = true;
1536 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1537 return sendCommand(command, delayMs);
1538}
1539
Eric Laurentb52c1522014-05-20 11:27:36 -07001540void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1541{
1542 sp<AudioCommand> command = new AudioCommand();
1543 command->mCommand = UPDATE_AUDIOPORT_LIST;
1544 ALOGV("AudioCommandThread() adding update audio port list");
1545 sendCommand(command);
1546}
1547
1548void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1549{
1550 sp<AudioCommand>command = new AudioCommand();
1551 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1552 ALOGV("AudioCommandThread() adding update audio patch list");
1553 sendCommand(command);
1554}
1555
François Gaffiecfe17322018-11-07 13:41:29 +01001556void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1557 int flags)
1558{
1559 sp<AudioCommand>command = new AudioCommand();
1560 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1561 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1562 data->mGroup = group;
1563 data->mFlags = flags;
1564 command->mParam = data;
1565 ALOGV("AudioCommandThread() adding audio volume group changed");
1566 sendCommand(command);
1567}
1568
Eric Laurente1715a42014-05-20 11:30:42 -07001569status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1570 const struct audio_port_config *config, int delayMs)
1571{
1572 sp<AudioCommand> command = new AudioCommand();
1573 command->mCommand = SET_AUDIOPORT_CONFIG;
1574 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1575 data->mConfig = *config;
1576 command->mParam = data;
1577 command->mWaitStatus = true;
1578 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1579 return sendCommand(command, delayMs);
1580}
1581
Jean-Michel Trivide801052015-04-14 19:10:14 -07001582void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001583 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001584{
1585 sp<AudioCommand> command = new AudioCommand();
1586 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1587 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1588 data->mRegId = regId;
1589 data->mState = state;
1590 command->mParam = data;
1591 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1592 regId.string(), state);
1593 sendCommand(command);
1594}
1595
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001596void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001597 int event,
1598 const record_client_info_t *clientInfo,
1599 const audio_config_base_t *clientConfig,
1600 std::vector<effect_descriptor_t> clientEffects,
1601 const audio_config_base_t *deviceConfig,
1602 std::vector<effect_descriptor_t> effects,
1603 audio_patch_handle_t patchHandle,
1604 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001605{
1606 sp<AudioCommand>command = new AudioCommand();
1607 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1608 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1609 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001610 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001611 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001612 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001613 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001614 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001615 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001616 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001617 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001618 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1619 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001620 sendCommand(command);
1621}
1622
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001623void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1624{
1625 sp<AudioCommand> command = new AudioCommand();
1626 command->mCommand = AUDIO_MODULES_UPDATE;
1627 sendCommand(command);
1628}
1629
Eric Laurent0ede8922014-05-09 18:04:42 -07001630status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1631{
1632 {
1633 Mutex::Autolock _l(mLock);
1634 insertCommand_l(command, delayMs);
1635 mWaitWorkCV.signal();
1636 }
1637 Mutex::Autolock _l(command->mLock);
1638 while (command->mWaitStatus) {
1639 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1640 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1641 command->mStatus = TIMED_OUT;
1642 command->mWaitStatus = false;
1643 }
1644 }
1645 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001646}
1647
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001649void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001651 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001652 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 command->mTime = systemTime() + milliseconds(delayMs);
1654
1655 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001656 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1658 }
1659
1660 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001661 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001662 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1664 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001665
1666 // create audio patch or release audio patch commands are equivalent
1667 // with regard to filtering
1668 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1669 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1670 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1671 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1672 continue;
1673 }
1674 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675
1676 switch (command->mCommand) {
1677 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001678 ParametersData *data = (ParametersData *)command->mParam.get();
1679 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001681 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001682 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1684 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1685 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001686 String8 key;
1687 String8 value;
1688 param.getAt(j, key, value);
1689 for (size_t k = 0; k < param2.size(); k++) {
1690 String8 key2;
1691 String8 value2;
1692 param2.getAt(k, key2, value2);
1693 if (key2 == key) {
1694 param2.remove(key2);
1695 ALOGV("Filtering out parameter %s", key2.string());
1696 break;
1697 }
1698 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 }
1700 // if all keys have been filtered out, remove the command.
1701 // otherwise, update the key value pairs
1702 if (param2.size() == 0) {
1703 removedCommands.add(command2);
1704 } else {
1705 data2->mKeyValuePairs = param2.toString();
1706 }
Eric Laurent21e54562013-09-23 12:08:05 -07001707 command->mTime = command2->mTime;
1708 // force delayMs to non 0 so that code below does not request to wait for
1709 // command status as the command is now delayed
1710 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 } break;
1712
1713 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001714 VolumeData *data = (VolumeData *)command->mParam.get();
1715 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 if (data->mIO != data2->mIO) break;
1717 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01001718 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07001719 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07001721 command->mTime = command2->mTime;
1722 // force delayMs to non 0 so that code below does not request to wait for
1723 // command status as the command is now delayed
1724 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001726
Eric Laurentbaf35fe2016-07-27 15:36:53 -07001727 case SET_VOICE_VOLUME: {
1728 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1729 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
1730 ALOGV("Filtering out voice volume command value %f replaced by %f",
1731 data2->mVolume, data->mVolume);
1732 removedCommands.add(command2);
1733 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;
1737 } break;
1738
Eric Laurente45b48a2014-09-04 16:40:57 -07001739 case CREATE_AUDIO_PATCH:
1740 case RELEASE_AUDIO_PATCH: {
1741 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001742 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001743 if (command->mCommand == CREATE_AUDIO_PATCH) {
1744 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001745 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001746 } else {
1747 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07001748 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07001749 }
1750 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001751 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07001752 if (command2->mCommand == CREATE_AUDIO_PATCH) {
1753 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001754 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001755 } else {
1756 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07001757 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07001758 }
1759 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001760 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
1761 same output. */
1762 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
1763 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
1764 bool isOutputDiff = false;
1765 if (patch.num_sources == patch2.num_sources) {
1766 for (unsigned count = 0; count < patch.num_sources; count++) {
1767 if (patch.sources[count].id != patch2.sources[count].id) {
1768 isOutputDiff = true;
1769 break;
1770 }
1771 }
1772 if (isOutputDiff)
1773 break;
1774 }
1775 }
Eric Laurente45b48a2014-09-04 16:40:57 -07001776 ALOGV("Filtering out %s audio patch command for handle %d",
1777 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
1778 removedCommands.add(command2);
1779 command->mTime = command2->mTime;
1780 // force delayMs to non 0 so that code below does not request to wait for
1781 // command status as the command is now delayed
1782 delayMs = 1;
1783 } break;
1784
Jean-Michel Trivide801052015-04-14 19:10:14 -07001785 case DYN_POLICY_MIX_STATE_UPDATE: {
1786
1787 } break;
1788
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001789 case RECORDING_CONFIGURATION_UPDATE: {
1790
1791 } break;
1792
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 default:
1794 break;
1795 }
1796 }
1797
1798 // remove filtered commands
1799 for (size_t j = 0; j < removedCommands.size(); j++) {
1800 // removed commands always have time stamps greater than current command
1801 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001802 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01001803 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804 mAudioCommands.removeAt(k);
1805 break;
1806 }
1807 }
1808 }
1809 removedCommands.clear();
1810
Eric Laurentaa79bef2015-01-15 14:33:51 -08001811 // Disable wait for status if delay is not 0.
1812 // Except for create audio patch command because the returned patch handle
1813 // is needed by audio policy manager
1814 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07001815 command->mWaitStatus = false;
1816 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07001817
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07001819 ALOGV("inserting command: %d at index %zd, num commands %zu",
1820 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 mAudioCommands.insertAt(command, i + 1);
1822}
1823
1824void AudioPolicyService::AudioCommandThread::exit()
1825{
Steve Block3856b092011-10-20 11:56:00 +01001826 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827 {
1828 AutoMutex _l(mLock);
1829 requestExit();
1830 mWaitWorkCV.signal();
1831 }
Zach Janga754b4f2015-10-27 01:29:34 +00001832 // Note that we can call it from the thread loop if all other references have been released
1833 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 requestExitAndWait();
1835}
1836
1837void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1838{
1839 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
1840 mCommand,
1841 (int)ns2s(mTime),
1842 (int)ns2ms(mTime)%1000,
1843 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07001844 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845}
1846
Dima Zavinfce7a472011-04-19 22:30:36 -07001847/******* helpers for the service_ops callbacks defined below *********/
1848void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1849 const char *keyValuePairs,
1850 int delayMs)
1851{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001852 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07001853 delayMs);
1854}
1855
1856int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1857 float volume,
1858 audio_io_handle_t output,
1859 int delayMs)
1860{
Glenn Kastenfff6d712012-01-12 16:38:12 -08001861 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001862 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07001863}
1864
Dima Zavinfce7a472011-04-19 22:30:36 -07001865int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1866{
1867 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1868}
1869
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001870void AudioPolicyService::setEffectSuspended(int effectId,
1871 audio_session_t sessionId,
1872 bool suspended)
1873{
1874 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
1875}
1876
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001877void AudioPolicyService::onNewAudioModulesAvailable()
1878{
1879 mAudioCommandThread->audioModulesUpdateCommand();
1880}
1881
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001882
Dima Zavinfce7a472011-04-19 22:30:36 -07001883extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08001884audio_module_handle_t aps_load_hw_module(void *service __unused,
1885 const char *name);
1886audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001887 audio_devices_t *pDevices,
1888 uint32_t *pSamplingRate,
1889 audio_format_t *pFormat,
1890 audio_channel_mask_t *pChannelMask,
1891 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001892 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001893
Eric Laurent2d388ec2014-03-07 13:25:54 -08001894audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001895 audio_module_handle_t module,
1896 audio_devices_t *pDevices,
1897 uint32_t *pSamplingRate,
1898 audio_format_t *pFormat,
1899 audio_channel_mask_t *pChannelMask,
1900 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001901 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001902 const audio_offload_info_t *offloadInfo);
1903audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07001904 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001905 audio_io_handle_t output2);
1906int aps_close_output(void *service __unused, audio_io_handle_t output);
1907int aps_suspend_output(void *service __unused, audio_io_handle_t output);
1908int aps_restore_output(void *service __unused, audio_io_handle_t output);
1909audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001910 audio_devices_t *pDevices,
1911 uint32_t *pSamplingRate,
1912 audio_format_t *pFormat,
1913 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001914 audio_in_acoustics_t acoustics __unused);
1915audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001916 audio_module_handle_t module,
1917 audio_devices_t *pDevices,
1918 uint32_t *pSamplingRate,
1919 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001920 audio_channel_mask_t *pChannelMask);
1921int aps_close_input(void *service __unused, audio_io_handle_t input);
1922int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08001923int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07001924 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001925 audio_io_handle_t dst_output);
1926char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
1927 const char *keys);
1928void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1929 const char *kv_pairs, int delay_ms);
1930int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07001931 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001932 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08001933int aps_set_voice_volume(void *service, float volume, int delay_ms);
1934};
Dima Zavinfce7a472011-04-19 22:30:36 -07001935
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08001936} // namespace android