1 /*
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 
20 #include "Configuration.h"
21 #undef __STRICT_ANSI__
22 #define __STDINT_LIMITS
23 #define __STDC_LIMIT_MACROS
24 #include <stdint.h>
25 #include <sys/time.h>
26 
27 #include <audio_utils/clock.h>
28 #include <binder/IServiceManager.h>
29 #include <utils/Log.h>
30 #include <cutils/properties.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/PermissionController.h>
33 #include <binder/IResultReceiver.h>
34 #include <utils/String16.h>
35 #include <utils/threads.h>
36 #include "AudioPolicyService.h"
37 #include <hardware_legacy/power.h>
38 #include <media/AudioEffect.h>
39 #include <media/AudioParameter.h>
40 #include <mediautils/ServiceUtilities.h>
41 #include <sensorprivacy/SensorPrivacyManager.h>
42 
43 #include <system/audio.h>
44 #include <system/audio_policy.h>
45 
46 namespace android {
47 
48 static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
49 static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
50 
51 static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
52 
53 static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
54 
55 static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
56 
57 // ----------------------------------------------------------------------------
58 
AudioPolicyService()59 AudioPolicyService::AudioPolicyService()
60     : BnAudioPolicyService(),
61       mAudioPolicyManager(NULL),
62       mAudioPolicyClient(NULL),
63       mPhoneState(AUDIO_MODE_INVALID),
64       mCaptureStateNotifier(false) {
65 }
66 
onFirstRef()67 void AudioPolicyService::onFirstRef()
68 {
69     {
70         Mutex::Autolock _l(mLock);
71 
72         // start audio commands thread
73         mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
74         // start output activity command thread
75         mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
76 
77         mAudioPolicyClient = new AudioPolicyClient(this);
78         mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
79     }
80     // load audio processing modules
81     sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
82     sp<UidPolicy> uidPolicy = new UidPolicy(this);
83     sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
84     {
85         Mutex::Autolock _l(mLock);
86         mAudioPolicyEffects = audioPolicyEffects;
87         mUidPolicy = uidPolicy;
88         mSensorPrivacyPolicy = sensorPrivacyPolicy;
89     }
90     uidPolicy->registerSelf();
91     sensorPrivacyPolicy->registerSelf();
92 }
93 
~AudioPolicyService()94 AudioPolicyService::~AudioPolicyService()
95 {
96     mAudioCommandThread->exit();
97     mOutputCommandThread->exit();
98 
99     destroyAudioPolicyManager(mAudioPolicyManager);
100     delete mAudioPolicyClient;
101 
102     mNotificationClients.clear();
103     mAudioPolicyEffects.clear();
104 
105     mUidPolicy->unregisterSelf();
106     mSensorPrivacyPolicy->unregisterSelf();
107 
108     mUidPolicy.clear();
109     mSensorPrivacyPolicy.clear();
110 }
111 
112 // A notification client is always registered by AudioSystem when the client process
113 // connects to AudioPolicyService.
registerClient(const sp<IAudioPolicyServiceClient> & client)114 void AudioPolicyService::registerClient(const sp<IAudioPolicyServiceClient>& client)
115 {
116     if (client == 0) {
117         ALOGW("%s got NULL client", __FUNCTION__);
118         return;
119     }
120     Mutex::Autolock _l(mNotificationClientsLock);
121 
122     uid_t uid = IPCThreadState::self()->getCallingUid();
123     pid_t pid = IPCThreadState::self()->getCallingPid();
124     int64_t token = ((int64_t)uid<<32) | pid;
125 
126     if (mNotificationClients.indexOfKey(token) < 0) {
127         sp<NotificationClient> notificationClient = new NotificationClient(this,
128                                                                            client,
129                                                                            uid,
130                                                                            pid);
131         ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
132 
133         mNotificationClients.add(token, notificationClient);
134 
135         sp<IBinder> binder = IInterface::asBinder(client);
136         binder->linkToDeath(notificationClient);
137     }
138 }
139 
setAudioPortCallbacksEnabled(bool enabled)140 void AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
141 {
142     Mutex::Autolock _l(mNotificationClientsLock);
143 
144     uid_t uid = IPCThreadState::self()->getCallingUid();
145     pid_t pid = IPCThreadState::self()->getCallingPid();
146     int64_t token = ((int64_t)uid<<32) | pid;
147 
148     if (mNotificationClients.indexOfKey(token) < 0) {
149         return;
150     }
151     mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
152 }
153 
setAudioVolumeGroupCallbacksEnabled(bool enabled)154 void 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 
168 // removeNotificationClient() is called when the client process dies.
removeNotificationClient(uid_t uid,pid_t pid)169 void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
170 {
171     bool hasSameUid = false;
172     {
173         Mutex::Autolock _l(mNotificationClientsLock);
174         int64_t token = ((int64_t)uid<<32) | pid;
175         mNotificationClients.removeItem(token);
176         for (size_t i = 0; i < mNotificationClients.size(); i++) {
177             if (mNotificationClients.valueAt(i)->uid() == uid) {
178                 hasSameUid = true;
179                 break;
180             }
181         }
182     }
183     {
184         Mutex::Autolock _l(mLock);
185         if (mAudioPolicyManager && !hasSameUid) {
186             // called from binder death notification: no need to clear caller identity
187             mAudioPolicyManager->releaseResourcesForUid(uid);
188         }
189     }
190 }
191 
onAudioPortListUpdate()192 void AudioPolicyService::onAudioPortListUpdate()
193 {
194     mOutputCommandThread->updateAudioPortListCommand();
195 }
196 
doOnAudioPortListUpdate()197 void AudioPolicyService::doOnAudioPortListUpdate()
198 {
199     Mutex::Autolock _l(mNotificationClientsLock);
200     for (size_t i = 0; i < mNotificationClients.size(); i++) {
201         mNotificationClients.valueAt(i)->onAudioPortListUpdate();
202     }
203 }
204 
onAudioPatchListUpdate()205 void AudioPolicyService::onAudioPatchListUpdate()
206 {
207     mOutputCommandThread->updateAudioPatchListCommand();
208 }
209 
doOnAudioPatchListUpdate()210 void AudioPolicyService::doOnAudioPatchListUpdate()
211 {
212     Mutex::Autolock _l(mNotificationClientsLock);
213     for (size_t i = 0; i < mNotificationClients.size(); i++) {
214         mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
215     }
216 }
217 
onAudioVolumeGroupChanged(volume_group_t group,int flags)218 void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
219 {
220     mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
221 }
222 
doOnAudioVolumeGroupChanged(volume_group_t group,int flags)223 void 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 
onDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)231 void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
232 {
233     ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
234             regId.string(), state);
235     mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
236 }
237 
doOnDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)238 void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
239 {
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 
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)246 void 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)
255 {
256     mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
257             clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
258 }
259 
doOnRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)260 void 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)
269 {
270     Mutex::Autolock _l(mNotificationClientsLock);
271     for (size_t i = 0; i < mNotificationClients.size(); i++) {
272         mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
273                 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
274     }
275 }
276 
clientCreateAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)277 status_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 
clientReleaseAudioPatch(audio_patch_handle_t handle,int delayMs)284 status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
285                                                  int delayMs)
286 {
287     return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
288 }
289 
clientSetAudioPortConfig(const struct audio_port_config * config,int delayMs)290 status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
291                                                       int delayMs)
292 {
293     return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
294 }
295 
NotificationClient(const sp<AudioPolicyService> & service,const sp<IAudioPolicyServiceClient> & client,uid_t uid,pid_t pid)296 AudioPolicyService::NotificationClient::NotificationClient(const sp<AudioPolicyService>& service,
297                                                      const sp<IAudioPolicyServiceClient>& client,
298                                                      uid_t uid,
299                                                      pid_t pid)
300     : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
301       mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
302 {
303 }
304 
~NotificationClient()305 AudioPolicyService::NotificationClient::~NotificationClient()
306 {
307 }
308 
binderDied(const wp<IBinder> & who __unused)309 void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
310 {
311     sp<NotificationClient> keep(this);
312     sp<AudioPolicyService> service = mService.promote();
313     if (service != 0) {
314         service->removeNotificationClient(mUid, mPid);
315     }
316 }
317 
onAudioPortListUpdate()318 void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
319 {
320     if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
321         mAudioPolicyServiceClient->onAudioPortListUpdate();
322     }
323 }
324 
onAudioPatchListUpdate()325 void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
326 {
327     if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
328         mAudioPolicyServiceClient->onAudioPatchListUpdate();
329     }
330 }
331 
onAudioVolumeGroupChanged(volume_group_t group,int flags)332 void 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 
onDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)341 void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
342         const String8& regId, int32_t state)
343 {
344     if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
345         mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(regId, state);
346     }
347 }
348 
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)349 void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
350                                             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)
358 {
359     if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
360         mAudioPolicyServiceClient->onRecordingConfigurationUpdate(event, clientInfo,
361                 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
362     }
363 }
364 
setAudioPortCallbacksEnabled(bool enabled)365 void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
366 {
367     mAudioPortCallbacksEnabled = enabled;
368 }
369 
setAudioVolumeGroupCallbacksEnabled(bool enabled)370 void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
371 {
372     mAudioVolumeGroupCallbacksEnabled = enabled;
373 }
374 
binderDied(const wp<IBinder> & who)375 void AudioPolicyService::binderDied(const wp<IBinder>& who) {
376     ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
377             IPCThreadState::self()->getCallingPid());
378 }
379 
dumpTryLock(Mutex & mutex)380 static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
381 {
382     return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
383 }
384 
dumpReleaseLock(Mutex & mutex,bool locked)385 static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
386 {
387     if (locked) mutex.unlock();
388 }
389 
dumpInternals(int fd)390 status_t AudioPolicyService::dumpInternals(int fd)
391 {
392     const size_t SIZE = 256;
393     char buffer[SIZE];
394     String8 result;
395 
396     snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
397     result.append(buffer);
398     snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
399     result.append(buffer);
400 
401     snprintf(buffer, SIZE, "Supported System Usages:\n");
402     result.append(buffer);
403     for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
404         it != mSupportedSystemUsages.end(); ++it) {
405         snprintf(buffer, SIZE, "\t%d\n", *it);
406         result.append(buffer);
407     }
408 
409     write(fd, result.string(), result.size());
410     return NO_ERROR;
411 }
412 
updateUidStates()413 void AudioPolicyService::updateUidStates()
414 {
415     Mutex::Autolock _l(mLock);
416     updateUidStates_l();
417 }
418 
updateUidStates_l()419 void AudioPolicyService::updateUidStates_l()
420 {
421 //    Go over all active clients and allow capture (does not force silence) in the
422 //    following cases:
423 //    The client is the assistant
424 //        AND an accessibility service is on TOP or a RTT call is active
425 //                AND the source is VOICE_RECOGNITION or HOTWORD
426 //            OR uses VOICE_RECOGNITION AND is on TOP
427 //                OR uses HOTWORD
428 //            AND there is no active privacy sensitive capture or call
429 //                OR client has CAPTURE_AUDIO_OUTPUT privileged permission
430 //    OR The client is an accessibility service
431 //        AND Is on TOP
432 //                AND the source is VOICE_RECOGNITION or HOTWORD
433 //            OR The assistant is not on TOP
434 //                AND there is no active privacy sensitive capture or call
435 //                    OR client has CAPTURE_AUDIO_OUTPUT privileged permission
436 //        AND is on TOP
437 //        AND the source is VOICE_RECOGNITION or HOTWORD
438 //    OR the client source is virtual (remote submix, call audio TX or RX...)
439 //    OR the client source is HOTWORD
440 //        AND is on TOP
441 //            OR all active clients are using HOTWORD source
442 //        AND no call is active
443 //            OR client has CAPTURE_AUDIO_OUTPUT privileged permission
444 //    OR the client is the current InputMethodService
445 //        AND a RTT call is active AND the source is VOICE_RECOGNITION
446 //    OR Any client
447 //        AND The assistant is not on TOP
448 //        AND is on TOP or latest started
449 //        AND there is no active privacy sensitive capture or call
450 //            OR client has CAPTURE_AUDIO_OUTPUT privileged permission
451 
452 
453     sp<AudioRecordClient> topActive;
454     sp<AudioRecordClient> latestActive;
455     sp<AudioRecordClient> topSensitiveActive;
456     sp<AudioRecordClient> latestSensitiveActive;
457 
458     nsecs_t topStartNs = 0;
459     nsecs_t latestStartNs = 0;
460     nsecs_t topSensitiveStartNs = 0;
461     nsecs_t latestSensitiveStartNs = 0;
462     bool isA11yOnTop = mUidPolicy->isA11yOnTop();
463     bool isAssistantOnTop = false;
464     bool isSensitiveActive = false;
465     bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
466     bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
467     bool rttCallActive = (isInCall || isInCommunication)
468             && mUidPolicy->isRttEnabled();
469     bool onlyHotwordActive = true;
470 
471     // if Sensor Privacy is enabled then all recordings should be silenced.
472     if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
473         silenceAllRecordings_l();
474         return;
475     }
476 
477     for (size_t i =0; i < mAudioRecordClients.size(); i++) {
478         sp<AudioRecordClient> current = mAudioRecordClients[i];
479         if (!current->active) {
480             continue;
481         }
482 
483         app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
484         // clients which app is in IDLE state are not eligible for top active or
485         // latest active
486         if (appState == APP_STATE_IDLE) {
487             continue;
488         }
489 
490         bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
491         // Clients capturing for Accessibility services are not considered
492         // for top or latest active to avoid masking regular clients started before
493         if (!isAccessibility) {
494             bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
495             bool isPrivacySensitive =
496                     (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
497             if (appState == APP_STATE_TOP) {
498                 if (isPrivacySensitive) {
499                     if (current->startTimeNs > topSensitiveStartNs) {
500                         topSensitiveActive = current;
501                         topSensitiveStartNs = current->startTimeNs;
502                     }
503                 } else {
504                     if (current->startTimeNs > topStartNs) {
505                         topActive = current;
506                         topStartNs = current->startTimeNs;
507                     }
508                 }
509                 if (isAssistant) {
510                     isAssistantOnTop = true;
511                 }
512             }
513             // Clients capturing for HOTWORD are not considered
514             // for latest active to avoid masking regular clients started before
515             if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
516                     || ((isA11yOnTop || rttCallActive) && isAssistant))) {
517                 if (isPrivacySensitive) {
518                     if (current->startTimeNs > latestSensitiveStartNs) {
519                         latestSensitiveActive = current;
520                         latestSensitiveStartNs = current->startTimeNs;
521                     }
522                     isSensitiveActive = true;
523                 } else {
524                     if (current->startTimeNs > latestStartNs) {
525                         latestActive = current;
526                         latestStartNs = current->startTimeNs;
527                     }
528                 }
529             }
530         }
531         if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
532             onlyHotwordActive = false;
533         }
534     }
535 
536     // if no active client with UI on Top, consider latest active as top
537     if (topActive == nullptr) {
538         topActive = latestActive;
539         topStartNs = latestStartNs;
540     }
541     if (topSensitiveActive == nullptr) {
542         topSensitiveActive = latestSensitiveActive;
543         topSensitiveStartNs = latestSensitiveStartNs;
544     }
545 
546     // If both privacy sensitive and regular capture are active:
547     //  if the regular capture is privileged
548     //    allow concurrency
549     //  else
550     //    favor the privacy sensitive case
551     if (topActive != nullptr && topSensitiveActive != nullptr
552             && !topActive->canCaptureOutput) {
553         topActive = nullptr;
554     }
555 
556     for (size_t i =0; i < mAudioRecordClients.size(); i++) {
557         sp<AudioRecordClient> current = mAudioRecordClients[i];
558         if (!current->active) {
559             continue;
560         }
561 
562         audio_source_t source = current->attributes.source;
563         bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
564         bool isTopOrLatestSensitive = topSensitiveActive == nullptr ?
565                                  false : current->uid == topSensitiveActive->uid;
566 
567         auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
568             bool canCaptureCall = recordClient->canCaptureOutput;
569             return !(isInCall && !canCaptureCall);
570 //TODO(b/160260850): restore restriction to mode owner once fix for misbehaving apps is merged
571 //            bool canCaptureCommunication = recordClient->canCaptureOutput
572 //                || recordClient->uid == mPhoneStateOwnerUid
573 //                || isServiceUid(mPhoneStateOwnerUid);
574 //            return !(isInCall && !canCaptureCall)
575 //                && !(isInCommunication && !canCaptureCommunication);
576         };
577 
578         // By default allow capture if:
579         //     The assistant is not on TOP
580         //     AND is on TOP or latest started
581         //     AND there is no active privacy sensitive capture or call
582         //             OR client has CAPTURE_AUDIO_OUTPUT privileged permission
583         bool allowCapture = !isAssistantOnTop
584                 && (isTopOrLatestActive || isTopOrLatestSensitive)
585                 && !(isSensitiveActive
586                     && !(isTopOrLatestSensitive || current->canCaptureOutput))
587                 && canCaptureIfInCallOrCommunication(current);
588 
589         if (isVirtualSource(source)) {
590             // Allow capture for virtual (remote submix, call audio TX or RX...) sources
591             allowCapture = true;
592         } else if (mUidPolicy->isAssistantUid(current->uid)) {
593             // For assistant allow capture if:
594             //     An accessibility service is on TOP or a RTT call is active
595             //            AND the source is VOICE_RECOGNITION or HOTWORD
596             //     OR is on TOP AND uses VOICE_RECOGNITION
597             //            OR uses HOTWORD
598             //         AND there is no active privacy sensitive capture or call
599             //             OR client has CAPTURE_AUDIO_OUTPUT privileged permission
600             if (isA11yOnTop || rttCallActive) {
601                 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
602                     allowCapture = true;
603                 }
604             } else {
605                 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
606                         source == AUDIO_SOURCE_HOTWORD)
607                         && !(isSensitiveActive && !current->canCaptureOutput)
608                         && canCaptureIfInCallOrCommunication(current)) {
609                     allowCapture = true;
610                 }
611             }
612         } else if (mUidPolicy->isA11yUid(current->uid)) {
613             // For accessibility service allow capture if:
614             //     The assistant is not on TOP
615             //         AND there is no active privacy sensitive capture or call
616             //             OR client has CAPTURE_AUDIO_OUTPUT privileged permission
617             //     OR
618             //         Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
619             if (!isAssistantOnTop
620                     && !(isSensitiveActive && !current->canCaptureOutput)
621                     && canCaptureIfInCallOrCommunication(current)) {
622                 allowCapture = true;
623             }
624             if (isA11yOnTop) {
625                 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
626                     allowCapture = true;
627                 }
628             }
629         } else if (source == AUDIO_SOURCE_HOTWORD) {
630             // For HOTWORD source allow capture when not on TOP if:
631             //     All active clients are using HOTWORD source
632             //     AND no call is active
633             //         OR client has CAPTURE_AUDIO_OUTPUT privileged permission
634             if (onlyHotwordActive
635                     && canCaptureIfInCallOrCommunication(current)) {
636                 allowCapture = true;
637             }
638         } else if (mUidPolicy->isCurrentImeUid(current->uid)) {
639             // For current InputMethodService allow capture if:
640             //     A RTT call is active AND the source is VOICE_RECOGNITION
641             if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
642                 allowCapture = true;
643             }
644         }
645         setAppState_l(current->portId,
646                       allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
647                                 APP_STATE_IDLE);
648     }
649 }
650 
silenceAllRecordings_l()651 void AudioPolicyService::silenceAllRecordings_l() {
652     for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
653         sp<AudioRecordClient> current = mAudioRecordClients[i];
654         if (!isVirtualSource(current->attributes.source)) {
655             setAppState_l(current->portId, APP_STATE_IDLE);
656         }
657     }
658 }
659 
660 /* static */
apmStatFromAmState(int amState)661 app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
662 
663     if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
664         return APP_STATE_IDLE;
665     } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
666       // include persistent services
667       return APP_STATE_TOP;
668     }
669     return APP_STATE_FOREGROUND;
670 }
671 
672 /* static */
isVirtualSource(audio_source_t source)673 bool AudioPolicyService::isVirtualSource(audio_source_t source)
674 {
675     switch (source) {
676         case AUDIO_SOURCE_VOICE_UPLINK:
677         case AUDIO_SOURCE_VOICE_DOWNLINK:
678         case AUDIO_SOURCE_VOICE_CALL:
679         case AUDIO_SOURCE_REMOTE_SUBMIX:
680         case AUDIO_SOURCE_FM_TUNER:
681         case AUDIO_SOURCE_ECHO_REFERENCE:
682             return true;
683         default:
684             break;
685     }
686     return false;
687 }
688 
setAppState_l(audio_port_handle_t portId,app_state_t state)689 void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
690 {
691     AutoCallerClear acc;
692 
693     if (mAudioPolicyManager) {
694         mAudioPolicyManager->setAppState(portId, state);
695     }
696     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
697     if (af) {
698         bool silenced = state == APP_STATE_IDLE;
699         af->setRecordSilenced(portId, silenced);
700     }
701 }
702 
dump(int fd,const Vector<String16> & args __unused)703 status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
704 {
705     if (!dumpAllowed()) {
706         dumpPermissionDenial(fd);
707     } else {
708         const bool locked = dumpTryLock(mLock);
709         if (!locked) {
710             String8 result(kDeadlockedString);
711             write(fd, result.string(), result.size());
712         }
713 
714         dumpInternals(fd);
715         if (mAudioCommandThread != 0) {
716             mAudioCommandThread->dump(fd);
717         }
718 
719         if (mAudioPolicyManager) {
720             mAudioPolicyManager->dump(fd);
721         }
722 
723         mPackageManager.dump(fd);
724 
725         dumpReleaseLock(mLock, locked);
726     }
727     return NO_ERROR;
728 }
729 
dumpPermissionDenial(int fd)730 status_t AudioPolicyService::dumpPermissionDenial(int fd)
731 {
732     const size_t SIZE = 256;
733     char buffer[SIZE];
734     String8 result;
735     snprintf(buffer, SIZE, "Permission Denial: "
736             "can't dump AudioPolicyService from pid=%d, uid=%d\n",
737             IPCThreadState::self()->getCallingPid(),
738             IPCThreadState::self()->getCallingUid());
739     result.append(buffer);
740     write(fd, result.string(), result.size());
741     return NO_ERROR;
742 }
743 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)744 status_t AudioPolicyService::onTransact(
745         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
746     switch (code) {
747         case SHELL_COMMAND_TRANSACTION: {
748             int in = data.readFileDescriptor();
749             int out = data.readFileDescriptor();
750             int err = data.readFileDescriptor();
751             int argc = data.readInt32();
752             Vector<String16> args;
753             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
754                args.add(data.readString16());
755             }
756             sp<IBinder> unusedCallback;
757             sp<IResultReceiver> resultReceiver;
758             status_t status;
759             if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
760                 return status;
761             }
762             if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
763                 return status;
764             }
765             status = shellCommand(in, out, err, args);
766             if (resultReceiver != nullptr) {
767                 resultReceiver->send(status);
768             }
769             return NO_ERROR;
770         }
771     }
772 
773     return BnAudioPolicyService::onTransact(code, data, reply, flags);
774 }
775 
776 // ------------------- Shell command implementation -------------------
777 
778 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,Vector<String16> & args)779 status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
780     if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
781         return PERMISSION_DENIED;
782     }
783     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
784         return BAD_VALUE;
785     }
786     if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
787         return handleSetUidState(args, err);
788     } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
789         return handleResetUidState(args, err);
790     } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
791         return handleGetUidState(args, out, err);
792     } else if (args.size() == 1 && args[0] == String16("help")) {
793         printHelp(out);
794         return NO_ERROR;
795     }
796     printHelp(err);
797     return BAD_VALUE;
798 }
799 
getUidForPackage(String16 packageName,int userId,uid_t & uid,int err)800 static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
801     if (userId < 0) {
802         ALOGE("Invalid user: %d", userId);
803         dprintf(err, "Invalid user: %d\n", userId);
804         return BAD_VALUE;
805     }
806 
807     PermissionController pc;
808     uid = pc.getPackageUid(packageName, 0);
809     if (uid <= 0) {
810         ALOGE("Unknown package: '%s'", String8(packageName).string());
811         dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
812         return BAD_VALUE;
813     }
814 
815     uid = multiuser_get_uid(userId, uid);
816     return NO_ERROR;
817 }
818 
handleSetUidState(Vector<String16> & args,int err)819 status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
820     // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
821     if (!(args.size() == 3 || args.size() == 5)) {
822         printHelp(err);
823         return BAD_VALUE;
824     }
825 
826     bool active = false;
827     if (args[2] == String16("active")) {
828         active = true;
829     } else if ((args[2] != String16("idle"))) {
830         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
831         return BAD_VALUE;
832     }
833 
834     int userId = 0;
835     if (args.size() >= 5 && args[3] == String16("--user")) {
836         userId = atoi(String8(args[4]));
837     }
838 
839     uid_t uid;
840     if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
841         return BAD_VALUE;
842     }
843 
844     sp<UidPolicy> uidPolicy;
845     {
846         Mutex::Autolock _l(mLock);
847         uidPolicy = mUidPolicy;
848     }
849     if (uidPolicy) {
850         uidPolicy->addOverrideUid(uid, active);
851         return NO_ERROR;
852     }
853     return NO_INIT;
854 }
855 
handleResetUidState(Vector<String16> & args,int err)856 status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
857     // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
858     if (!(args.size() == 2 || args.size() == 4)) {
859         printHelp(err);
860         return BAD_VALUE;
861     }
862 
863     int userId = 0;
864     if (args.size() >= 4 && args[2] == String16("--user")) {
865         userId = atoi(String8(args[3]));
866     }
867 
868     uid_t uid;
869     if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
870         return BAD_VALUE;
871     }
872 
873     sp<UidPolicy> uidPolicy;
874     {
875         Mutex::Autolock _l(mLock);
876         uidPolicy = mUidPolicy;
877     }
878     if (uidPolicy) {
879         uidPolicy->removeOverrideUid(uid);
880         return NO_ERROR;
881     }
882     return NO_INIT;
883 }
884 
handleGetUidState(Vector<String16> & args,int out,int err)885 status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
886     // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
887     if (!(args.size() == 2 || args.size() == 4)) {
888         printHelp(err);
889         return BAD_VALUE;
890     }
891 
892     int userId = 0;
893     if (args.size() >= 4 && args[2] == String16("--user")) {
894         userId = atoi(String8(args[3]));
895     }
896 
897     uid_t uid;
898     if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
899         return BAD_VALUE;
900     }
901 
902     sp<UidPolicy> uidPolicy;
903     {
904         Mutex::Autolock _l(mLock);
905         uidPolicy = mUidPolicy;
906     }
907     if (uidPolicy) {
908         return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
909     }
910     return NO_INIT;
911 }
912 
printHelp(int out)913 status_t AudioPolicyService::printHelp(int out) {
914     return dprintf(out, "Audio policy service commands:\n"
915         "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
916         "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
917         "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
918         "  help print this message\n");
919 }
920 
921 // -----------  AudioPolicyService::UidPolicy implementation ----------
922 
registerSelf()923 void AudioPolicyService::UidPolicy::registerSelf() {
924     status_t res = mAm.linkToDeath(this);
925     mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
926             | ActivityManager::UID_OBSERVER_IDLE
927             | ActivityManager::UID_OBSERVER_ACTIVE
928             | ActivityManager::UID_OBSERVER_PROCSTATE,
929             ActivityManager::PROCESS_STATE_UNKNOWN,
930             String16("audioserver"));
931     if (!res) {
932         Mutex::Autolock _l(mLock);
933         mObserverRegistered = true;
934     } else {
935         ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
936 
937         mAm.unregisterUidObserver(this);
938     }
939 }
940 
unregisterSelf()941 void AudioPolicyService::UidPolicy::unregisterSelf() {
942     mAm.unlinkToDeath(this);
943     mAm.unregisterUidObserver(this);
944     Mutex::Autolock _l(mLock);
945     mObserverRegistered = false;
946 }
947 
binderDied(__unused const wp<IBinder> & who)948 void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
949     Mutex::Autolock _l(mLock);
950     mCachedUids.clear();
951     mObserverRegistered = false;
952 }
953 
checkRegistered()954 void AudioPolicyService::UidPolicy::checkRegistered() {
955     bool needToReregister = false;
956     {
957         Mutex::Autolock _l(mLock);
958         needToReregister = !mObserverRegistered;
959     }
960     if (needToReregister) {
961         // Looks like ActivityManager has died previously, attempt to re-register.
962         registerSelf();
963     }
964 }
965 
isUidActive(uid_t uid)966 bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
967     if (isServiceUid(uid)) return true;
968     checkRegistered();
969     {
970         Mutex::Autolock _l(mLock);
971         auto overrideIter = mOverrideUids.find(uid);
972         if (overrideIter != mOverrideUids.end()) {
973             return overrideIter->second.first;
974         }
975         // In an absense of the ActivityManager, assume everything to be active.
976         if (!mObserverRegistered) return true;
977         auto cacheIter = mCachedUids.find(uid);
978         if (cacheIter != mCachedUids.end()) {
979             return cacheIter->second.first;
980         }
981     }
982     ActivityManager am;
983     bool active = am.isUidActive(uid, String16("audioserver"));
984     {
985         Mutex::Autolock _l(mLock);
986         mCachedUids.insert(std::pair<uid_t,
987                            std::pair<bool, int>>(uid, std::pair<bool, int>(active,
988                                                       ActivityManager::PROCESS_STATE_UNKNOWN)));
989     }
990     return active;
991 }
992 
getUidState(uid_t uid)993 int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
994     if (isServiceUid(uid)) {
995         return ActivityManager::PROCESS_STATE_TOP;
996     }
997     checkRegistered();
998     {
999         Mutex::Autolock _l(mLock);
1000         auto overrideIter = mOverrideUids.find(uid);
1001         if (overrideIter != mOverrideUids.end()) {
1002             if (overrideIter->second.first) {
1003                 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1004                     return overrideIter->second.second;
1005                 } else {
1006                     auto cacheIter = mCachedUids.find(uid);
1007                     if (cacheIter != mCachedUids.end()) {
1008                         return cacheIter->second.second;
1009                     }
1010                 }
1011             }
1012             return ActivityManager::PROCESS_STATE_UNKNOWN;
1013         }
1014         // In an absense of the ActivityManager, assume everything to be active.
1015         if (!mObserverRegistered) {
1016             return ActivityManager::PROCESS_STATE_TOP;
1017         }
1018         auto cacheIter = mCachedUids.find(uid);
1019         if (cacheIter != mCachedUids.end()) {
1020             if (cacheIter->second.first) {
1021                 return cacheIter->second.second;
1022             } else {
1023                 return ActivityManager::PROCESS_STATE_UNKNOWN;
1024             }
1025         }
1026     }
1027     ActivityManager am;
1028     bool active = am.isUidActive(uid, String16("audioserver"));
1029     int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1030     if (active) {
1031         state = am.getUidProcessState(uid, String16("audioserver"));
1032     }
1033     {
1034         Mutex::Autolock _l(mLock);
1035         mCachedUids.insert(std::pair<uid_t,
1036                            std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1037     }
1038 
1039     return state;
1040 }
1041 
onUidActive(uid_t uid)1042 void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
1043     updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
1044 }
1045 
onUidGone(uid_t uid,__unused bool disabled)1046 void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
1047     updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
1048 }
1049 
onUidIdle(uid_t uid,__unused bool disabled)1050 void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1051     updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
1052 }
1053 
onUidStateChanged(uid_t uid,int32_t procState,int64_t procStateSeq __unused,int32_t capability __unused)1054 void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1055                                                       int32_t procState,
1056                                                       int64_t procStateSeq __unused,
1057                                                       int32_t capability __unused) {
1058     if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1059         updateUid(&mCachedUids, uid, true, procState, true);
1060     }
1061 }
1062 
updateOverrideUid(uid_t uid,bool active,bool insert)1063 void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1064     updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1065 }
1066 
notifyService()1067 void AudioPolicyService::UidPolicy::notifyService() {
1068     sp<AudioPolicyService> service = mService.promote();
1069     if (service != nullptr) {
1070         service->updateUidStates();
1071     }
1072 }
1073 
updateUid(std::unordered_map<uid_t,std::pair<bool,int>> * uids,uid_t uid,bool active,int state,bool insert)1074 void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1075                                               std::pair<bool, int>> *uids,
1076                                               uid_t uid,
1077                                               bool active,
1078                                               int state,
1079                                               bool insert) {
1080     if (isServiceUid(uid)) {
1081         return;
1082     }
1083     bool wasActive = isUidActive(uid);
1084     int previousState = getUidState(uid);
1085     {
1086         Mutex::Autolock _l(mLock);
1087         updateUidLocked(uids, uid, active, state, insert);
1088     }
1089     if (wasActive != isUidActive(uid) || state != previousState) {
1090         notifyService();
1091     }
1092 }
1093 
updateUidLocked(std::unordered_map<uid_t,std::pair<bool,int>> * uids,uid_t uid,bool active,int state,bool insert)1094 void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1095                                                     std::pair<bool, int>> *uids,
1096                                                     uid_t uid,
1097                                                     bool active,
1098                                                     int state,
1099                                                     bool insert) {
1100     auto it = uids->find(uid);
1101     if (it != uids->end()) {
1102         if (insert) {
1103             if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1104                 it->second.first = active;
1105             }
1106             if (it->second.first) {
1107                 it->second.second = state;
1108             } else {
1109                 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1110             }
1111         } else {
1112             uids->erase(it);
1113         }
1114     } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1115         uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1116                                       std::pair<bool, int>(active, state)));
1117     }
1118 }
1119 
isA11yOnTop()1120 bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1121     for (const auto &uid : mCachedUids) {
1122         if (!isA11yUid(uid.first)) {
1123             continue;
1124         }
1125         if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1126                 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
1127             return true;
1128         }
1129     }
1130     return false;
1131 }
1132 
isA11yUid(uid_t uid)1133 bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1134 {
1135     std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1136     return it != mA11yUids.end();
1137 }
1138 
1139 // -----------  AudioPolicyService::SensorPrivacyService implementation ----------
registerSelf()1140 void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1141     SensorPrivacyManager spm;
1142     mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1143     spm.addSensorPrivacyListener(this);
1144 }
1145 
unregisterSelf()1146 void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1147     SensorPrivacyManager spm;
1148     spm.removeSensorPrivacyListener(this);
1149 }
1150 
isSensorPrivacyEnabled()1151 bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1152     return mSensorPrivacyEnabled;
1153 }
1154 
onSensorPrivacyChanged(bool enabled)1155 binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1156     mSensorPrivacyEnabled = enabled;
1157     sp<AudioPolicyService> service = mService.promote();
1158     if (service != nullptr) {
1159         service->updateUidStates();
1160     }
1161     return binder::Status::ok();
1162 }
1163 
1164 // -----------  AudioPolicyService::AudioCommandThread implementation ----------
1165 
AudioCommandThread(String8 name,const wp<AudioPolicyService> & service)1166 AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1167                                                            const wp<AudioPolicyService>& service)
1168     : Thread(false), mName(name), mService(service)
1169 {
1170 }
1171 
1172 
~AudioCommandThread()1173 AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1174 {
1175     if (!mAudioCommands.isEmpty()) {
1176         release_wake_lock(mName.string());
1177     }
1178     mAudioCommands.clear();
1179 }
1180 
onFirstRef()1181 void AudioPolicyService::AudioCommandThread::onFirstRef()
1182 {
1183     run(mName.string(), ANDROID_PRIORITY_AUDIO);
1184 }
1185 
threadLoop()1186 bool AudioPolicyService::AudioCommandThread::threadLoop()
1187 {
1188     nsecs_t waitTime = -1;
1189 
1190     mLock.lock();
1191     while (!exitPending())
1192     {
1193         sp<AudioPolicyService> svc;
1194         while (!mAudioCommands.isEmpty() && !exitPending()) {
1195             nsecs_t curTime = systemTime();
1196             // commands are sorted by increasing time stamp: execute them from index 0 and up
1197             if (mAudioCommands[0]->mTime <= curTime) {
1198                 sp<AudioCommand> command = mAudioCommands[0];
1199                 mAudioCommands.removeAt(0);
1200                 mLastCommand = command;
1201 
1202                 switch (command->mCommand) {
1203                 case SET_VOLUME: {
1204                     VolumeData *data = (VolumeData *)command->mParam.get();
1205                     ALOGV("AudioCommandThread() processing set volume stream %d, \
1206                             volume %f, output %d", data->mStream, data->mVolume, data->mIO);
1207                     mLock.unlock();
1208                     command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1209                                                                     data->mVolume,
1210                                                                     data->mIO);
1211                     mLock.lock();
1212                     }break;
1213                 case SET_PARAMETERS: {
1214                     ParametersData *data = (ParametersData *)command->mParam.get();
1215                     ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1216                             data->mKeyValuePairs.string(), data->mIO);
1217                     mLock.unlock();
1218                     command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
1219                     mLock.lock();
1220                     }break;
1221                 case SET_VOICE_VOLUME: {
1222                     VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1223                     ALOGV("AudioCommandThread() processing set voice volume volume %f",
1224                             data->mVolume);
1225                     mLock.unlock();
1226                     command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
1227                     mLock.lock();
1228                     }break;
1229                 case STOP_OUTPUT: {
1230                     StopOutputData *data = (StopOutputData *)command->mParam.get();
1231                     ALOGV("AudioCommandThread() processing stop output portId %d",
1232                             data->mPortId);
1233                     svc = mService.promote();
1234                     if (svc == 0) {
1235                         break;
1236                     }
1237                     mLock.unlock();
1238                     svc->doStopOutput(data->mPortId);
1239                     mLock.lock();
1240                     }break;
1241                 case RELEASE_OUTPUT: {
1242                     ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
1243                     ALOGV("AudioCommandThread() processing release output portId %d",
1244                             data->mPortId);
1245                     svc = mService.promote();
1246                     if (svc == 0) {
1247                         break;
1248                     }
1249                     mLock.unlock();
1250                     svc->doReleaseOutput(data->mPortId);
1251                     mLock.lock();
1252                     }break;
1253                 case CREATE_AUDIO_PATCH: {
1254                     CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1255                     ALOGV("AudioCommandThread() processing create audio patch");
1256                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1257                     if (af == 0) {
1258                         command->mStatus = PERMISSION_DENIED;
1259                     } else {
1260                         mLock.unlock();
1261                         command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
1262                         mLock.lock();
1263                     }
1264                     } break;
1265                 case RELEASE_AUDIO_PATCH: {
1266                     ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1267                     ALOGV("AudioCommandThread() processing release audio patch");
1268                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1269                     if (af == 0) {
1270                         command->mStatus = PERMISSION_DENIED;
1271                     } else {
1272                         mLock.unlock();
1273                         command->mStatus = af->releaseAudioPatch(data->mHandle);
1274                         mLock.lock();
1275                     }
1276                     } break;
1277                 case UPDATE_AUDIOPORT_LIST: {
1278                     ALOGV("AudioCommandThread() processing update audio port list");
1279                     svc = mService.promote();
1280                     if (svc == 0) {
1281                         break;
1282                     }
1283                     mLock.unlock();
1284                     svc->doOnAudioPortListUpdate();
1285                     mLock.lock();
1286                     }break;
1287                 case UPDATE_AUDIOPATCH_LIST: {
1288                     ALOGV("AudioCommandThread() processing update audio patch list");
1289                     svc = mService.promote();
1290                     if (svc == 0) {
1291                         break;
1292                     }
1293                     mLock.unlock();
1294                     svc->doOnAudioPatchListUpdate();
1295                     mLock.lock();
1296                     }break;
1297                 case CHANGED_AUDIOVOLUMEGROUP: {
1298                     AudioVolumeGroupData *data =
1299                             static_cast<AudioVolumeGroupData *>(command->mParam.get());
1300                     ALOGV("AudioCommandThread() processing update audio volume group");
1301                     svc = mService.promote();
1302                     if (svc == 0) {
1303                         break;
1304                     }
1305                     mLock.unlock();
1306                     svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1307                     mLock.lock();
1308                     }break;
1309                 case SET_AUDIOPORT_CONFIG: {
1310                     SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1311                     ALOGV("AudioCommandThread() processing set port config");
1312                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1313                     if (af == 0) {
1314                         command->mStatus = PERMISSION_DENIED;
1315                     } else {
1316                         mLock.unlock();
1317                         command->mStatus = af->setAudioPortConfig(&data->mConfig);
1318                         mLock.lock();
1319                     }
1320                     } break;
1321                 case DYN_POLICY_MIX_STATE_UPDATE: {
1322                     DynPolicyMixStateUpdateData *data =
1323                             (DynPolicyMixStateUpdateData *)command->mParam.get();
1324                     ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1325                             data->mRegId.string(), data->mState);
1326                     svc = mService.promote();
1327                     if (svc == 0) {
1328                         break;
1329                     }
1330                     mLock.unlock();
1331                     svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1332                     mLock.lock();
1333                     } break;
1334                 case RECORDING_CONFIGURATION_UPDATE: {
1335                     RecordingConfigurationUpdateData *data =
1336                             (RecordingConfigurationUpdateData *)command->mParam.get();
1337                     ALOGV("AudioCommandThread() processing recording configuration update");
1338                     svc = mService.promote();
1339                     if (svc == 0) {
1340                         break;
1341                     }
1342                     mLock.unlock();
1343                     svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
1344                             &data->mClientConfig, data->mClientEffects,
1345                             &data->mDeviceConfig, data->mEffects,
1346                             data->mPatchHandle, data->mSource);
1347                     mLock.lock();
1348                     } break;
1349                 case SET_EFFECT_SUSPENDED: {
1350                     SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1351                     ALOGV("AudioCommandThread() processing set effect suspended");
1352                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1353                     if (af != 0) {
1354                         mLock.unlock();
1355                         af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1356                         mLock.lock();
1357                     }
1358                     } break;
1359                 case AUDIO_MODULES_UPDATE: {
1360                     ALOGV("AudioCommandThread() processing audio modules update");
1361                     svc = mService.promote();
1362                     if (svc == 0) {
1363                         break;
1364                     }
1365                     mLock.unlock();
1366                     svc->doOnNewAudioModulesAvailable();
1367                     mLock.lock();
1368                     } break;
1369 
1370                 default:
1371                     ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
1372                 }
1373                 {
1374                     Mutex::Autolock _l(command->mLock);
1375                     if (command->mWaitStatus) {
1376                         command->mWaitStatus = false;
1377                         command->mCond.signal();
1378                     }
1379                 }
1380                 waitTime = -1;
1381                 // release mLock before releasing strong reference on the service as
1382                 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1383                 // acquires mLock.
1384                 mLock.unlock();
1385                 svc.clear();
1386                 mLock.lock();
1387             } else {
1388                 waitTime = mAudioCommands[0]->mTime - curTime;
1389                 break;
1390             }
1391         }
1392 
1393         // release delayed commands wake lock if the queue is empty
1394         if (mAudioCommands.isEmpty()) {
1395             release_wake_lock(mName.string());
1396         }
1397 
1398         // At this stage we have either an empty command queue or the first command in the queue
1399         // has a finite delay. So unless we are exiting it is safe to wait.
1400         if (!exitPending()) {
1401             ALOGV("AudioCommandThread() going to sleep");
1402             if (waitTime == -1) {
1403                 mWaitWorkCV.wait(mLock);
1404             } else {
1405                 mWaitWorkCV.waitRelative(mLock, waitTime);
1406             }
1407         }
1408     }
1409     // release delayed commands wake lock before quitting
1410     if (!mAudioCommands.isEmpty()) {
1411         release_wake_lock(mName.string());
1412     }
1413     mLock.unlock();
1414     return false;
1415 }
1416 
dump(int fd)1417 status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1418 {
1419     const size_t SIZE = 256;
1420     char buffer[SIZE];
1421     String8 result;
1422 
1423     snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1424     result.append(buffer);
1425     write(fd, result.string(), result.size());
1426 
1427     const bool locked = dumpTryLock(mLock);
1428     if (!locked) {
1429         String8 result2(kCmdDeadlockedString);
1430         write(fd, result2.string(), result2.size());
1431     }
1432 
1433     snprintf(buffer, SIZE, "- Commands:\n");
1434     result = String8(buffer);
1435     result.append("   Command Time        Wait pParam\n");
1436     for (size_t i = 0; i < mAudioCommands.size(); i++) {
1437         mAudioCommands[i]->dump(buffer, SIZE);
1438         result.append(buffer);
1439     }
1440     result.append("  Last Command\n");
1441     if (mLastCommand != 0) {
1442         mLastCommand->dump(buffer, SIZE);
1443         result.append(buffer);
1444     } else {
1445         result.append("     none\n");
1446     }
1447 
1448     write(fd, result.string(), result.size());
1449 
1450     dumpReleaseLock(mLock, locked);
1451 
1452     return NO_ERROR;
1453 }
1454 
volumeCommand(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)1455 status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
1456                                                                float volume,
1457                                                                audio_io_handle_t output,
1458                                                                int delayMs)
1459 {
1460     sp<AudioCommand> command = new AudioCommand();
1461     command->mCommand = SET_VOLUME;
1462     sp<VolumeData> data = new VolumeData();
1463     data->mStream = stream;
1464     data->mVolume = volume;
1465     data->mIO = output;
1466     command->mParam = data;
1467     command->mWaitStatus = true;
1468     ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
1469             stream, volume, output);
1470     return sendCommand(command, delayMs);
1471 }
1472 
parametersCommand(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)1473 status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
1474                                                                    const char *keyValuePairs,
1475                                                                    int delayMs)
1476 {
1477     sp<AudioCommand> command = new AudioCommand();
1478     command->mCommand = SET_PARAMETERS;
1479     sp<ParametersData> data = new ParametersData();
1480     data->mIO = ioHandle;
1481     data->mKeyValuePairs = String8(keyValuePairs);
1482     command->mParam = data;
1483     command->mWaitStatus = true;
1484     ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
1485             keyValuePairs, ioHandle, delayMs);
1486     return sendCommand(command, delayMs);
1487 }
1488 
voiceVolumeCommand(float volume,int delayMs)1489 status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1490 {
1491     sp<AudioCommand> command = new AudioCommand();
1492     command->mCommand = SET_VOICE_VOLUME;
1493     sp<VoiceVolumeData> data = new VoiceVolumeData();
1494     data->mVolume = volume;
1495     command->mParam = data;
1496     command->mWaitStatus = true;
1497     ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
1498     return sendCommand(command, delayMs);
1499 }
1500 
setEffectSuspendedCommand(int effectId,audio_session_t sessionId,bool suspended)1501 void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1502                                                                        audio_session_t sessionId,
1503                                                                        bool suspended)
1504 {
1505     sp<AudioCommand> command = new AudioCommand();
1506     command->mCommand = SET_EFFECT_SUSPENDED;
1507     sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1508     data->mEffectId = effectId;
1509     data->mSessionId = sessionId;
1510     data->mSuspended = suspended;
1511     command->mParam = data;
1512     ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1513         effectId, sessionId, suspended);
1514     sendCommand(command);
1515 }
1516 
1517 
stopOutputCommand(audio_port_handle_t portId)1518 void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
1519 {
1520     sp<AudioCommand> command = new AudioCommand();
1521     command->mCommand = STOP_OUTPUT;
1522     sp<StopOutputData> data = new StopOutputData();
1523     data->mPortId = portId;
1524     command->mParam = data;
1525     ALOGV("AudioCommandThread() adding stop output portId %d", portId);
1526     sendCommand(command);
1527 }
1528 
releaseOutputCommand(audio_port_handle_t portId)1529 void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
1530 {
1531     sp<AudioCommand> command = new AudioCommand();
1532     command->mCommand = RELEASE_OUTPUT;
1533     sp<ReleaseOutputData> data = new ReleaseOutputData();
1534     data->mPortId = portId;
1535     command->mParam = data;
1536     ALOGV("AudioCommandThread() adding release output portId %d", portId);
1537     sendCommand(command);
1538 }
1539 
createAudioPatchCommand(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)1540 status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1541                                                 const struct audio_patch *patch,
1542                                                 audio_patch_handle_t *handle,
1543                                                 int delayMs)
1544 {
1545     status_t status = NO_ERROR;
1546 
1547     sp<AudioCommand> command = new AudioCommand();
1548     command->mCommand = CREATE_AUDIO_PATCH;
1549     CreateAudioPatchData *data = new CreateAudioPatchData();
1550     data->mPatch = *patch;
1551     data->mHandle = *handle;
1552     command->mParam = data;
1553     command->mWaitStatus = true;
1554     ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1555     status = sendCommand(command, delayMs);
1556     if (status == NO_ERROR) {
1557         *handle = data->mHandle;
1558     }
1559     return status;
1560 }
1561 
releaseAudioPatchCommand(audio_patch_handle_t handle,int delayMs)1562 status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1563                                                  int delayMs)
1564 {
1565     sp<AudioCommand> command = new AudioCommand();
1566     command->mCommand = RELEASE_AUDIO_PATCH;
1567     ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1568     data->mHandle = handle;
1569     command->mParam = data;
1570     command->mWaitStatus = true;
1571     ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1572     return sendCommand(command, delayMs);
1573 }
1574 
updateAudioPortListCommand()1575 void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1576 {
1577     sp<AudioCommand> command = new AudioCommand();
1578     command->mCommand = UPDATE_AUDIOPORT_LIST;
1579     ALOGV("AudioCommandThread() adding update audio port list");
1580     sendCommand(command);
1581 }
1582 
updateAudioPatchListCommand()1583 void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1584 {
1585     sp<AudioCommand>command = new AudioCommand();
1586     command->mCommand = UPDATE_AUDIOPATCH_LIST;
1587     ALOGV("AudioCommandThread() adding update audio patch list");
1588     sendCommand(command);
1589 }
1590 
changeAudioVolumeGroupCommand(volume_group_t group,int flags)1591 void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1592                                                                            int flags)
1593 {
1594     sp<AudioCommand>command = new AudioCommand();
1595     command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1596     AudioVolumeGroupData *data= new AudioVolumeGroupData();
1597     data->mGroup = group;
1598     data->mFlags = flags;
1599     command->mParam = data;
1600     ALOGV("AudioCommandThread() adding audio volume group changed");
1601     sendCommand(command);
1602 }
1603 
setAudioPortConfigCommand(const struct audio_port_config * config,int delayMs)1604 status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1605                                             const struct audio_port_config *config, int delayMs)
1606 {
1607     sp<AudioCommand> command = new AudioCommand();
1608     command->mCommand = SET_AUDIOPORT_CONFIG;
1609     SetAudioPortConfigData *data = new SetAudioPortConfigData();
1610     data->mConfig = *config;
1611     command->mParam = data;
1612     command->mWaitStatus = true;
1613     ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1614     return sendCommand(command, delayMs);
1615 }
1616 
dynamicPolicyMixStateUpdateCommand(const String8 & regId,int32_t state)1617 void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
1618         const String8& regId, int32_t state)
1619 {
1620     sp<AudioCommand> command = new AudioCommand();
1621     command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1622     DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1623     data->mRegId = regId;
1624     data->mState = state;
1625     command->mParam = data;
1626     ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1627             regId.string(), state);
1628     sendCommand(command);
1629 }
1630 
recordingConfigurationUpdateCommand(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)1631 void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
1632                                                 int event,
1633                                                 const record_client_info_t *clientInfo,
1634                                                 const audio_config_base_t *clientConfig,
1635                                                 std::vector<effect_descriptor_t> clientEffects,
1636                                                 const audio_config_base_t *deviceConfig,
1637                                                 std::vector<effect_descriptor_t> effects,
1638                                                 audio_patch_handle_t patchHandle,
1639                                                 audio_source_t source)
1640 {
1641     sp<AudioCommand>command = new AudioCommand();
1642     command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1643     RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1644     data->mEvent = event;
1645     data->mClientInfo = *clientInfo;
1646     data->mClientConfig = *clientConfig;
1647     data->mClientEffects = clientEffects;
1648     data->mDeviceConfig = *deviceConfig;
1649     data->mEffects = effects;
1650     data->mPatchHandle = patchHandle;
1651     data->mSource = source;
1652     command->mParam = data;
1653     ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1654             event, clientInfo->source, clientInfo->uid);
1655     sendCommand(command);
1656 }
1657 
audioModulesUpdateCommand()1658 void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1659 {
1660     sp<AudioCommand> command = new AudioCommand();
1661     command->mCommand = AUDIO_MODULES_UPDATE;
1662     sendCommand(command);
1663 }
1664 
sendCommand(sp<AudioCommand> & command,int delayMs)1665 status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1666 {
1667     {
1668         Mutex::Autolock _l(mLock);
1669         insertCommand_l(command, delayMs);
1670         mWaitWorkCV.signal();
1671     }
1672     Mutex::Autolock _l(command->mLock);
1673     while (command->mWaitStatus) {
1674         nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1675         if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1676             command->mStatus = TIMED_OUT;
1677             command->mWaitStatus = false;
1678         }
1679     }
1680     return command->mStatus;
1681 }
1682 
1683 // insertCommand_l() must be called with mLock held
insertCommand_l(sp<AudioCommand> & command,int delayMs)1684 void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
1685 {
1686     ssize_t i;  // not size_t because i will count down to -1
1687     Vector < sp<AudioCommand> > removedCommands;
1688     command->mTime = systemTime() + milliseconds(delayMs);
1689 
1690     // acquire wake lock to make sure delayed commands are processed
1691     if (mAudioCommands.isEmpty()) {
1692         acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1693     }
1694 
1695     // check same pending commands with later time stamps and eliminate them
1696     for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
1697         sp<AudioCommand> command2 = mAudioCommands[i];
1698         // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1699         if (command2->mTime <= command->mTime) break;
1700 
1701         // create audio patch or release audio patch commands are equivalent
1702         // with regard to filtering
1703         if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1704                 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1705             if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1706                     (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1707                 continue;
1708             }
1709         } else if (command2->mCommand != command->mCommand) continue;
1710 
1711         switch (command->mCommand) {
1712         case SET_PARAMETERS: {
1713             ParametersData *data = (ParametersData *)command->mParam.get();
1714             ParametersData *data2 = (ParametersData *)command2->mParam.get();
1715             if (data->mIO != data2->mIO) break;
1716             ALOGV("Comparing parameter command %s to new command %s",
1717                     data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
1718             AudioParameter param = AudioParameter(data->mKeyValuePairs);
1719             AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1720             for (size_t j = 0; j < param.size(); j++) {
1721                 String8 key;
1722                 String8 value;
1723                 param.getAt(j, key, value);
1724                 for (size_t k = 0; k < param2.size(); k++) {
1725                     String8 key2;
1726                     String8 value2;
1727                     param2.getAt(k, key2, value2);
1728                     if (key2 == key) {
1729                         param2.remove(key2);
1730                         ALOGV("Filtering out parameter %s", key2.string());
1731                         break;
1732                     }
1733                 }
1734             }
1735             // if all keys have been filtered out, remove the command.
1736             // otherwise, update the key value pairs
1737             if (param2.size() == 0) {
1738                 removedCommands.add(command2);
1739             } else {
1740                 data2->mKeyValuePairs = param2.toString();
1741             }
1742             command->mTime = command2->mTime;
1743             // force delayMs to non 0 so that code below does not request to wait for
1744             // command status as the command is now delayed
1745             delayMs = 1;
1746         } break;
1747 
1748         case SET_VOLUME: {
1749             VolumeData *data = (VolumeData *)command->mParam.get();
1750             VolumeData *data2 = (VolumeData *)command2->mParam.get();
1751             if (data->mIO != data2->mIO) break;
1752             if (data->mStream != data2->mStream) break;
1753             ALOGV("Filtering out volume command on output %d for stream %d",
1754                     data->mIO, data->mStream);
1755             removedCommands.add(command2);
1756             command->mTime = command2->mTime;
1757             // force delayMs to non 0 so that code below does not request to wait for
1758             // command status as the command is now delayed
1759             delayMs = 1;
1760         } break;
1761 
1762         case SET_VOICE_VOLUME: {
1763             VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1764             VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
1765             ALOGV("Filtering out voice volume command value %f replaced by %f",
1766                   data2->mVolume, data->mVolume);
1767             removedCommands.add(command2);
1768             command->mTime = command2->mTime;
1769             // force delayMs to non 0 so that code below does not request to wait for
1770             // command status as the command is now delayed
1771             delayMs = 1;
1772         } break;
1773 
1774         case CREATE_AUDIO_PATCH:
1775         case RELEASE_AUDIO_PATCH: {
1776             audio_patch_handle_t handle;
1777             struct audio_patch patch;
1778             if (command->mCommand == CREATE_AUDIO_PATCH) {
1779                 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
1780                 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
1781             } else {
1782                 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
1783                 memset(&patch, 0, sizeof(patch));
1784             }
1785             audio_patch_handle_t handle2;
1786             struct audio_patch patch2;
1787             if (command2->mCommand == CREATE_AUDIO_PATCH) {
1788                 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
1789                 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
1790             } else {
1791                 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
1792                 memset(&patch2, 0, sizeof(patch2));
1793             }
1794             if (handle != handle2) break;
1795             /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
1796                same output. */
1797             if( (command->mCommand == CREATE_AUDIO_PATCH) &&
1798                 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
1799                 bool isOutputDiff = false;
1800                 if (patch.num_sources == patch2.num_sources) {
1801                     for (unsigned count = 0; count < patch.num_sources; count++) {
1802                         if (patch.sources[count].id != patch2.sources[count].id) {
1803                             isOutputDiff = true;
1804                             break;
1805                         }
1806                     }
1807                     if (isOutputDiff)
1808                        break;
1809                 }
1810             }
1811             ALOGV("Filtering out %s audio patch command for handle %d",
1812                   (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
1813             removedCommands.add(command2);
1814             command->mTime = command2->mTime;
1815             // force delayMs to non 0 so that code below does not request to wait for
1816             // command status as the command is now delayed
1817             delayMs = 1;
1818         } break;
1819 
1820         case DYN_POLICY_MIX_STATE_UPDATE: {
1821 
1822         } break;
1823 
1824         case RECORDING_CONFIGURATION_UPDATE: {
1825 
1826         } break;
1827 
1828         default:
1829             break;
1830         }
1831     }
1832 
1833     // remove filtered commands
1834     for (size_t j = 0; j < removedCommands.size(); j++) {
1835         // removed commands always have time stamps greater than current command
1836         for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
1837             if (mAudioCommands[k].get() == removedCommands[j].get()) {
1838                 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
1839                 mAudioCommands.removeAt(k);
1840                 break;
1841             }
1842         }
1843     }
1844     removedCommands.clear();
1845 
1846     // Disable wait for status if delay is not 0.
1847     // Except for create audio patch command because the returned patch handle
1848     // is needed by audio policy manager
1849     if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
1850         command->mWaitStatus = false;
1851     }
1852 
1853     // insert command at the right place according to its time stamp
1854     ALOGV("inserting command: %d at index %zd, num commands %zu",
1855             command->mCommand, i+1, mAudioCommands.size());
1856     mAudioCommands.insertAt(command, i + 1);
1857 }
1858 
exit()1859 void AudioPolicyService::AudioCommandThread::exit()
1860 {
1861     ALOGV("AudioCommandThread::exit");
1862     {
1863         AutoMutex _l(mLock);
1864         requestExit();
1865         mWaitWorkCV.signal();
1866     }
1867     // Note that we can call it from the thread loop if all other references have been released
1868     // but it will safely return WOULD_BLOCK in this case
1869     requestExitAndWait();
1870 }
1871 
dump(char * buffer,size_t size)1872 void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1873 {
1874     snprintf(buffer, size, "   %02d      %06d.%03d  %01u    %p\n",
1875             mCommand,
1876             (int)ns2s(mTime),
1877             (int)ns2ms(mTime)%1000,
1878             mWaitStatus,
1879             mParam.get());
1880 }
1881 
1882 /******* helpers for the service_ops callbacks defined below *********/
setParameters(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)1883 void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1884                                        const char *keyValuePairs,
1885                                        int delayMs)
1886 {
1887     mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
1888                                            delayMs);
1889 }
1890 
setStreamVolume(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)1891 int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1892                                         float volume,
1893                                         audio_io_handle_t output,
1894                                         int delayMs)
1895 {
1896     return (int)mAudioCommandThread->volumeCommand(stream, volume,
1897                                                    output, delayMs);
1898 }
1899 
setVoiceVolume(float volume,int delayMs)1900 int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1901 {
1902     return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1903 }
1904 
setEffectSuspended(int effectId,audio_session_t sessionId,bool suspended)1905 void AudioPolicyService::setEffectSuspended(int effectId,
1906                                             audio_session_t sessionId,
1907                                             bool suspended)
1908 {
1909     mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
1910 }
1911 
onNewAudioModulesAvailable()1912 void AudioPolicyService::onNewAudioModulesAvailable()
1913 {
1914     mOutputCommandThread->audioModulesUpdateCommand();
1915 }
1916 
1917 
1918 extern "C" {
1919 audio_module_handle_t aps_load_hw_module(void *service __unused,
1920                                              const char *name);
1921 audio_io_handle_t aps_open_output(void *service __unused,
1922                                          audio_devices_t *pDevices,
1923                                          uint32_t *pSamplingRate,
1924                                          audio_format_t *pFormat,
1925                                          audio_channel_mask_t *pChannelMask,
1926                                          uint32_t *pLatencyMs,
1927                                          audio_output_flags_t flags);
1928 
1929 audio_io_handle_t aps_open_output_on_module(void *service __unused,
1930                                                    audio_module_handle_t module,
1931                                                    audio_devices_t *pDevices,
1932                                                    uint32_t *pSamplingRate,
1933                                                    audio_format_t *pFormat,
1934                                                    audio_channel_mask_t *pChannelMask,
1935                                                    uint32_t *pLatencyMs,
1936                                                    audio_output_flags_t flags,
1937                                                    const audio_offload_info_t *offloadInfo);
1938 audio_io_handle_t aps_open_dup_output(void *service __unused,
1939                                                  audio_io_handle_t output1,
1940                                                  audio_io_handle_t output2);
1941 int aps_close_output(void *service __unused, audio_io_handle_t output);
1942 int aps_suspend_output(void *service __unused, audio_io_handle_t output);
1943 int aps_restore_output(void *service __unused, audio_io_handle_t output);
1944 audio_io_handle_t aps_open_input(void *service __unused,
1945                                         audio_devices_t *pDevices,
1946                                         uint32_t *pSamplingRate,
1947                                         audio_format_t *pFormat,
1948                                         audio_channel_mask_t *pChannelMask,
1949                                         audio_in_acoustics_t acoustics __unused);
1950 audio_io_handle_t aps_open_input_on_module(void *service __unused,
1951                                                   audio_module_handle_t module,
1952                                                   audio_devices_t *pDevices,
1953                                                   uint32_t *pSamplingRate,
1954                                                   audio_format_t *pFormat,
1955                                                   audio_channel_mask_t *pChannelMask);
1956 int aps_close_input(void *service __unused, audio_io_handle_t input);
1957 int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
1958 int aps_move_effects(void *service __unused, audio_session_t session,
1959                                 audio_io_handle_t src_output,
1960                                 audio_io_handle_t dst_output);
1961 char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
1962                                      const char *keys);
1963 void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1964                                    const char *kv_pairs, int delay_ms);
1965 int aps_set_stream_volume(void *service, audio_stream_type_t stream,
1966                                      float volume, audio_io_handle_t output,
1967                                      int delay_ms);
1968 int aps_set_voice_volume(void *service, float volume, int delay_ms);
1969 };
1970 
1971 } // namespace android
1972