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 "AudioPolicyIntefaceImpl"
18 //#define LOG_NDEBUG 0
19 
20 #include "AudioPolicyService.h"
21 #include "TypeConverter.h"
22 #include <media/MediaAnalyticsItem.h>
23 #include <media/AudioPolicy.h>
24 #include <utils/Log.h>
25 
26 namespace android {
27 
28 
29 // ----------------------------------------------------------------------------
30 
doOnNewAudioModulesAvailable()31 void AudioPolicyService::doOnNewAudioModulesAvailable()
32 {
33     if (mAudioPolicyManager == NULL) return;
34     Mutex::Autolock _l(mLock);
35     AutoCallerClear acc;
36     mAudioPolicyManager->onNewAudioModulesAvailable();
37 }
38 
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)39 status_t AudioPolicyService::setDeviceConnectionState(audio_devices_t device,
40                                                   audio_policy_dev_state_t state,
41                                                   const char *device_address,
42                                                   const char *device_name,
43                                                   audio_format_t encodedFormat)
44 {
45     if (mAudioPolicyManager == NULL) {
46         return NO_INIT;
47     }
48     if (!settingsAllowed()) {
49         return PERMISSION_DENIED;
50     }
51     if (state != AUDIO_POLICY_DEVICE_STATE_AVAILABLE &&
52             state != AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
53         return BAD_VALUE;
54     }
55 
56     ALOGV("setDeviceConnectionState()");
57     Mutex::Autolock _l(mLock);
58     AutoCallerClear acc;
59     return mAudioPolicyManager->setDeviceConnectionState(device, state,
60                                                          device_address, device_name, encodedFormat);
61 }
62 
getDeviceConnectionState(audio_devices_t device,const char * device_address)63 audio_policy_dev_state_t AudioPolicyService::getDeviceConnectionState(
64                                                               audio_devices_t device,
65                                                               const char *device_address)
66 {
67     if (mAudioPolicyManager == NULL) {
68         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
69     }
70     AutoCallerClear acc;
71     return mAudioPolicyManager->getDeviceConnectionState(device,
72                                                       device_address);
73 }
74 
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name,audio_format_t encodedFormat)75 status_t AudioPolicyService::handleDeviceConfigChange(audio_devices_t device,
76                                                   const char *device_address,
77                                                   const char *device_name,
78                                                   audio_format_t encodedFormat)
79 {
80     if (mAudioPolicyManager == NULL) {
81         return NO_INIT;
82     }
83     if (!settingsAllowed()) {
84         return PERMISSION_DENIED;
85     }
86 
87     ALOGV("handleDeviceConfigChange()");
88     Mutex::Autolock _l(mLock);
89     AutoCallerClear acc;
90     return mAudioPolicyManager->handleDeviceConfigChange(device, device_address,
91                                                          device_name, encodedFormat);
92 }
93 
setPhoneState(audio_mode_t state)94 status_t AudioPolicyService::setPhoneState(audio_mode_t state)
95 {
96     if (mAudioPolicyManager == NULL) {
97         return NO_INIT;
98     }
99     if (!settingsAllowed()) {
100         return PERMISSION_DENIED;
101     }
102     if (uint32_t(state) >= AUDIO_MODE_CNT) {
103         return BAD_VALUE;
104     }
105 
106     ALOGV("setPhoneState()");
107 
108     // acquire lock before calling setMode() so that setMode() + setPhoneState() are an atomic
109     // operation from policy manager standpoint (no other operation (e.g track start or stop)
110     // can be interleaved).
111     Mutex::Autolock _l(mLock);
112     // TODO: check if it is more appropriate to do it in platform specific policy manager
113     AudioSystem::setMode(state);
114 
115     AutoCallerClear acc;
116     mAudioPolicyManager->setPhoneState(state);
117     mPhoneState = state;
118     return NO_ERROR;
119 }
120 
getPhoneState()121 audio_mode_t AudioPolicyService::getPhoneState()
122 {
123     Mutex::Autolock _l(mLock);
124     return mPhoneState;
125 }
126 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)127 status_t AudioPolicyService::setForceUse(audio_policy_force_use_t usage,
128                                          audio_policy_forced_cfg_t config)
129 {
130     if (mAudioPolicyManager == NULL) {
131         return NO_INIT;
132     }
133 
134     if (!modifyAudioRoutingAllowed()) {
135         return PERMISSION_DENIED;
136     }
137 
138     if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
139         return BAD_VALUE;
140     }
141     if (config < 0 || config >= AUDIO_POLICY_FORCE_CFG_CNT) {
142         return BAD_VALUE;
143     }
144     ALOGV("setForceUse()");
145     Mutex::Autolock _l(mLock);
146     AutoCallerClear acc;
147     mAudioPolicyManager->setForceUse(usage, config);
148     return NO_ERROR;
149 }
150 
getForceUse(audio_policy_force_use_t usage)151 audio_policy_forced_cfg_t AudioPolicyService::getForceUse(audio_policy_force_use_t usage)
152 {
153     if (mAudioPolicyManager == NULL) {
154         return AUDIO_POLICY_FORCE_NONE;
155     }
156     if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
157         return AUDIO_POLICY_FORCE_NONE;
158     }
159     AutoCallerClear acc;
160     return mAudioPolicyManager->getForceUse(usage);
161 }
162 
getOutput(audio_stream_type_t stream)163 audio_io_handle_t AudioPolicyService::getOutput(audio_stream_type_t stream)
164 {
165     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
166         return AUDIO_IO_HANDLE_NONE;
167     }
168     if (mAudioPolicyManager == NULL) {
169         return AUDIO_IO_HANDLE_NONE;
170     }
171     ALOGV("getOutput()");
172     Mutex::Autolock _l(mLock);
173     AutoCallerClear acc;
174     return mAudioPolicyManager->getOutput(stream);
175 }
176 
getOutputForAttr(audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,pid_t pid,uid_t uid,const audio_config_t * config,audio_output_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId,std::vector<audio_io_handle_t> * secondaryOutputs)177 status_t AudioPolicyService::getOutputForAttr(audio_attributes_t *attr,
178                                               audio_io_handle_t *output,
179                                               audio_session_t session,
180                                               audio_stream_type_t *stream,
181                                               pid_t pid,
182                                               uid_t uid,
183                                               const audio_config_t *config,
184                                               audio_output_flags_t flags,
185                                               audio_port_handle_t *selectedDeviceId,
186                                               audio_port_handle_t *portId,
187                                               std::vector<audio_io_handle_t> *secondaryOutputs)
188 {
189     if (mAudioPolicyManager == NULL) {
190         return NO_INIT;
191     }
192     ALOGV("getOutputForAttr()");
193     Mutex::Autolock _l(mLock);
194 
195     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
196     if (!isAudioServerOrMediaServerUid(callingUid) || uid == (uid_t)-1) {
197         ALOGW_IF(uid != (uid_t)-1 && uid != callingUid,
198                 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, uid);
199         uid = callingUid;
200     }
201     if (!mPackageManager.allowPlaybackCapture(uid)) {
202         attr->flags |= AUDIO_FLAG_NO_MEDIA_PROJECTION;
203     }
204     if (((attr->flags & (AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE)) != 0)
205             && !bypassInterruptionPolicyAllowed(pid, uid)) {
206         attr->flags &= ~(AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE);
207     }
208     audio_output_flags_t originalFlags = flags;
209     AutoCallerClear acc;
210     status_t result = mAudioPolicyManager->getOutputForAttr(attr, output, session, stream, uid,
211                                                  config,
212                                                  &flags, selectedDeviceId, portId,
213                                                  secondaryOutputs);
214 
215     // FIXME: Introduce a way to check for the the telephony device before opening the output
216     if ((result == NO_ERROR) &&
217         (flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) &&
218         !modifyPhoneStateAllowed(pid, uid)) {
219         // If the app tries to play music through the telephony device and doesn't have permission
220         // the fallback to the default output device.
221         mAudioPolicyManager->releaseOutput(*portId);
222         flags = originalFlags;
223         *selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
224         *portId = AUDIO_PORT_HANDLE_NONE;
225         secondaryOutputs->clear();
226         result = mAudioPolicyManager->getOutputForAttr(attr, output, session, stream, uid, config,
227                                                        &flags, selectedDeviceId, portId,
228                                                        secondaryOutputs);
229     }
230 
231     if (result == NO_ERROR) {
232         sp <AudioPlaybackClient> client =
233             new AudioPlaybackClient(*attr, *output, uid, pid, session, *selectedDeviceId, *stream);
234         mAudioPlaybackClients.add(*portId, client);
235     }
236     return result;
237 }
238 
getPlaybackClientAndEffects(audio_port_handle_t portId,sp<AudioPlaybackClient> & client,sp<AudioPolicyEffects> & effects,const char * context)239 void AudioPolicyService::getPlaybackClientAndEffects(audio_port_handle_t portId,
240                                                      sp<AudioPlaybackClient>& client,
241                                                      sp<AudioPolicyEffects>& effects,
242                                                      const char *context)
243 {
244     Mutex::Autolock _l(mLock);
245     const ssize_t index = mAudioPlaybackClients.indexOfKey(portId);
246     if (index < 0) {
247         ALOGE("%s AudioTrack client not found for portId %d", context, portId);
248         return;
249     }
250     client = mAudioPlaybackClients.valueAt(index);
251     effects = mAudioPolicyEffects;
252 }
253 
startOutput(audio_port_handle_t portId)254 status_t AudioPolicyService::startOutput(audio_port_handle_t portId)
255 {
256     if (mAudioPolicyManager == NULL) {
257         return NO_INIT;
258     }
259     ALOGV("startOutput()");
260     sp<AudioPlaybackClient> client;
261     sp<AudioPolicyEffects>audioPolicyEffects;
262 
263     getPlaybackClientAndEffects(portId, client, audioPolicyEffects, __func__);
264 
265     if (audioPolicyEffects != 0) {
266         // create audio processors according to stream
267         status_t status = audioPolicyEffects->addOutputSessionEffects(
268             client->io, client->stream, client->session);
269         if (status != NO_ERROR && status != ALREADY_EXISTS) {
270             ALOGW("Failed to add effects on session %d", client->session);
271         }
272     }
273     Mutex::Autolock _l(mLock);
274     AutoCallerClear acc;
275     status_t status = mAudioPolicyManager->startOutput(portId);
276     if (status == NO_ERROR) {
277         client->active = true;
278     }
279     return status;
280 }
281 
stopOutput(audio_port_handle_t portId)282 status_t AudioPolicyService::stopOutput(audio_port_handle_t portId)
283 {
284     if (mAudioPolicyManager == NULL) {
285         return NO_INIT;
286     }
287     ALOGV("stopOutput()");
288     mOutputCommandThread->stopOutputCommand(portId);
289     return NO_ERROR;
290 }
291 
doStopOutput(audio_port_handle_t portId)292 status_t  AudioPolicyService::doStopOutput(audio_port_handle_t portId)
293 {
294     ALOGV("doStopOutput");
295     sp<AudioPlaybackClient> client;
296     sp<AudioPolicyEffects>audioPolicyEffects;
297 
298     getPlaybackClientAndEffects(portId, client, audioPolicyEffects, __func__);
299 
300     if (audioPolicyEffects != 0) {
301         // release audio processors from the stream
302         status_t status = audioPolicyEffects->releaseOutputSessionEffects(
303             client->io, client->stream, client->session);
304         if (status != NO_ERROR && status != ALREADY_EXISTS) {
305             ALOGW("Failed to release effects on session %d", client->session);
306         }
307     }
308     Mutex::Autolock _l(mLock);
309     AutoCallerClear acc;
310     status_t status = mAudioPolicyManager->stopOutput(portId);
311     if (status == NO_ERROR) {
312         client->active = false;
313     }
314     return status;
315 }
316 
releaseOutput(audio_port_handle_t portId)317 void AudioPolicyService::releaseOutput(audio_port_handle_t portId)
318 {
319     if (mAudioPolicyManager == NULL) {
320         return;
321     }
322     ALOGV("releaseOutput()");
323     mOutputCommandThread->releaseOutputCommand(portId);
324 }
325 
doReleaseOutput(audio_port_handle_t portId)326 void AudioPolicyService::doReleaseOutput(audio_port_handle_t portId)
327 {
328     ALOGV("doReleaseOutput from tid %d", gettid());
329     sp<AudioPlaybackClient> client;
330     sp<AudioPolicyEffects> audioPolicyEffects;
331 
332     getPlaybackClientAndEffects(portId, client, audioPolicyEffects, __func__);
333 
334     if (audioPolicyEffects != 0 && client->active) {
335         // clean up effects if output was not stopped before being released
336         audioPolicyEffects->releaseOutputSessionEffects(
337             client->io, client->stream, client->session);
338     }
339     Mutex::Autolock _l(mLock);
340     mAudioPlaybackClients.removeItem(portId);
341 
342     // called from internal thread: no need to clear caller identity
343     mAudioPolicyManager->releaseOutput(portId);
344 }
345 
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_unique_id_t riid,audio_session_t session,pid_t pid,uid_t uid,const String16 & opPackageName,const audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId)346 status_t AudioPolicyService::getInputForAttr(const audio_attributes_t *attr,
347                                              audio_io_handle_t *input,
348                                              audio_unique_id_t riid,
349                                              audio_session_t session,
350                                              pid_t pid,
351                                              uid_t uid,
352                                              const String16& opPackageName,
353                                              const audio_config_base_t *config,
354                                              audio_input_flags_t flags,
355                                              audio_port_handle_t *selectedDeviceId,
356                                              audio_port_handle_t *portId)
357 {
358     if (mAudioPolicyManager == NULL) {
359         return NO_INIT;
360     }
361 
362     audio_source_t inputSource = attr->source;
363     if (inputSource == AUDIO_SOURCE_DEFAULT) {
364         inputSource = AUDIO_SOURCE_MIC;
365     }
366 
367     // already checked by client, but double-check in case the client wrapper is bypassed
368     if ((inputSource < AUDIO_SOURCE_DEFAULT)
369             || (inputSource >= AUDIO_SOURCE_CNT
370                 && inputSource != AUDIO_SOURCE_HOTWORD
371                 && inputSource != AUDIO_SOURCE_FM_TUNER
372                 && inputSource != AUDIO_SOURCE_ECHO_REFERENCE)) {
373         return BAD_VALUE;
374     }
375 
376     bool updatePid = (pid == -1);
377     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
378     if (!isAudioServerOrMediaServerUid(callingUid)) {
379         ALOGW_IF(uid != (uid_t)-1 && uid != callingUid,
380                 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, uid);
381         uid = callingUid;
382         updatePid = true;
383     }
384 
385     if (updatePid) {
386         const pid_t callingPid = IPCThreadState::self()->getCallingPid();
387         ALOGW_IF(pid != (pid_t)-1 && pid != callingPid,
388                  "%s uid %d pid %d tried to pass itself off as pid %d",
389                  __func__, callingUid, callingPid, pid);
390         pid = callingPid;
391     }
392 
393     // check calling permissions
394     if (!recordingAllowed(opPackageName, pid, uid)) {
395         ALOGE("%s permission denied: recording not allowed for uid %d pid %d",
396                 __func__, uid, pid);
397         return PERMISSION_DENIED;
398     }
399 
400     bool canCaptureOutput = captureAudioOutputAllowed(pid, uid);
401     if ((inputSource == AUDIO_SOURCE_VOICE_UPLINK ||
402         inputSource == AUDIO_SOURCE_VOICE_DOWNLINK ||
403         inputSource == AUDIO_SOURCE_VOICE_CALL ||
404         inputSource == AUDIO_SOURCE_ECHO_REFERENCE) &&
405         !canCaptureOutput) {
406         return PERMISSION_DENIED;
407     }
408 
409     bool canCaptureHotword = captureHotwordAllowed(opPackageName, pid, uid);
410     if ((inputSource == AUDIO_SOURCE_HOTWORD) && !canCaptureHotword) {
411         return BAD_VALUE;
412     }
413 
414     sp<AudioPolicyEffects>audioPolicyEffects;
415     {
416         status_t status;
417         AudioPolicyInterface::input_type_t inputType;
418 
419         Mutex::Autolock _l(mLock);
420         {
421             AutoCallerClear acc;
422             // the audio_in_acoustics_t parameter is ignored by get_input()
423             status = mAudioPolicyManager->getInputForAttr(attr, input, riid, session, uid,
424                                                          config,
425                                                          flags, selectedDeviceId,
426                                                          &inputType, portId);
427         }
428         audioPolicyEffects = mAudioPolicyEffects;
429 
430         if (status == NO_ERROR) {
431             // enforce permission (if any) required for each type of input
432             switch (inputType) {
433             case AudioPolicyInterface::API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK:
434                 // this use case has been validated in audio service with a MediaProjection token,
435                 // and doesn't rely on regular permissions
436             case AudioPolicyInterface::API_INPUT_LEGACY:
437                 break;
438             case AudioPolicyInterface::API_INPUT_TELEPHONY_RX:
439                 // FIXME: use the same permission as for remote submix for now.
440             case AudioPolicyInterface::API_INPUT_MIX_CAPTURE:
441                 if (!canCaptureOutput) {
442                     ALOGE("getInputForAttr() permission denied: capture not allowed");
443                     status = PERMISSION_DENIED;
444                 }
445                 break;
446             case AudioPolicyInterface::API_INPUT_MIX_EXT_POLICY_REROUTE:
447                 if (!modifyAudioRoutingAllowed()) {
448                     ALOGE("getInputForAttr() permission denied: modify audio routing not allowed");
449                     status = PERMISSION_DENIED;
450                 }
451                 break;
452             case AudioPolicyInterface::API_INPUT_INVALID:
453             default:
454                 LOG_ALWAYS_FATAL("getInputForAttr() encountered an invalid input type %d",
455                         (int)inputType);
456             }
457         }
458 
459         if (status != NO_ERROR) {
460             if (status == PERMISSION_DENIED) {
461                 AutoCallerClear acc;
462                 mAudioPolicyManager->releaseInput(*portId);
463             }
464             return status;
465         }
466 
467         sp<AudioRecordClient> client = new AudioRecordClient(*attr, *input, uid, pid, session,
468                                                              *selectedDeviceId, opPackageName,
469                                                              canCaptureOutput, canCaptureHotword);
470         mAudioRecordClients.add(*portId, client);
471     }
472 
473     if (audioPolicyEffects != 0) {
474         // create audio pre processors according to input source
475         status_t status = audioPolicyEffects->addInputEffects(*input, inputSource, session);
476         if (status != NO_ERROR && status != ALREADY_EXISTS) {
477             ALOGW("Failed to add effects on input %d", *input);
478         }
479     }
480     return NO_ERROR;
481 }
482 
getDeviceTypeStrForPortId(audio_port_handle_t portId)483 std::string AudioPolicyService::getDeviceTypeStrForPortId(audio_port_handle_t portId) {
484     struct audio_port port = {};
485     port.id = portId;
486     status_t status = mAudioPolicyManager->getAudioPort(&port);
487     if (status == NO_ERROR && port.type == AUDIO_PORT_TYPE_DEVICE) {
488         return toString(port.ext.device.type);
489     }
490     return {};
491 }
492 
startInput(audio_port_handle_t portId)493 status_t AudioPolicyService::startInput(audio_port_handle_t portId)
494 {
495     if (mAudioPolicyManager == NULL) {
496         return NO_INIT;
497     }
498     sp<AudioRecordClient> client;
499     {
500         Mutex::Autolock _l(mLock);
501 
502         ssize_t index = mAudioRecordClients.indexOfKey(portId);
503         if (index < 0) {
504             return INVALID_OPERATION;
505         }
506         client = mAudioRecordClients.valueAt(index);
507     }
508 
509     // check calling permissions
510     if (!startRecording(client->opPackageName, client->pid, client->uid)) {
511         ALOGE("%s permission denied: recording not allowed for uid %d pid %d",
512                 __func__, client->uid, client->pid);
513         return PERMISSION_DENIED;
514     }
515 
516     Mutex::Autolock _l(mLock);
517 
518     client->active = true;
519     client->startTimeNs = systemTime();
520     updateUidStates_l();
521 
522     status_t status;
523     {
524         AutoCallerClear acc;
525         status = mAudioPolicyManager->startInput(portId);
526 
527     }
528 
529     // including successes gets very verbose
530     // but once we cut over to westworld, log them all.
531     if (status != NO_ERROR) {
532 
533         static constexpr char kAudioPolicy[] = "audiopolicy";
534 
535         static constexpr char kAudioPolicyStatus[] = "android.media.audiopolicy.status";
536         static constexpr char kAudioPolicyRqstSrc[] = "android.media.audiopolicy.rqst.src";
537         static constexpr char kAudioPolicyRqstPkg[] = "android.media.audiopolicy.rqst.pkg";
538         static constexpr char kAudioPolicyRqstSession[] = "android.media.audiopolicy.rqst.session";
539         static constexpr char kAudioPolicyRqstDevice[] =
540                 "android.media.audiopolicy.rqst.device";
541         static constexpr char kAudioPolicyActiveSrc[] = "android.media.audiopolicy.active.src";
542         static constexpr char kAudioPolicyActivePkg[] = "android.media.audiopolicy.active.pkg";
543         static constexpr char kAudioPolicyActiveSession[] =
544                 "android.media.audiopolicy.active.session";
545         static constexpr char kAudioPolicyActiveDevice[] =
546                 "android.media.audiopolicy.active.device";
547 
548         MediaAnalyticsItem *item = MediaAnalyticsItem::create(kAudioPolicy);
549         if (item != NULL) {
550 
551             item->setInt32(kAudioPolicyStatus, status);
552 
553             item->setCString(kAudioPolicyRqstSrc,
554                              toString(client->attributes.source).c_str());
555             item->setInt32(kAudioPolicyRqstSession, client->session);
556             if (client->opPackageName.size() != 0) {
557                 item->setCString(kAudioPolicyRqstPkg,
558                                  std::string(String8(client->opPackageName).string()).c_str());
559             } else {
560                 item->setCString(kAudioPolicyRqstPkg, std::to_string(client->uid).c_str());
561             }
562             item->setCString(
563                     kAudioPolicyRqstDevice, getDeviceTypeStrForPortId(client->deviceId).c_str());
564 
565             int count = mAudioRecordClients.size();
566             for (int i = 0; i < count ; i++) {
567                 if (portId == mAudioRecordClients.keyAt(i)) {
568                     continue;
569                 }
570                 sp<AudioRecordClient> other = mAudioRecordClients.valueAt(i);
571                 if (other->active) {
572                     // keeps the last of the clients marked active
573                     item->setCString(kAudioPolicyActiveSrc,
574                                      toString(other->attributes.source).c_str());
575                     item->setInt32(kAudioPolicyActiveSession, other->session);
576                     if (other->opPackageName.size() != 0) {
577                         item->setCString(kAudioPolicyActivePkg,
578                              std::string(String8(other->opPackageName).string()).c_str());
579                     } else {
580                         item->setCString(kAudioPolicyRqstPkg,
581                                          std::to_string(other->uid).c_str());
582                     }
583                     item->setCString(kAudioPolicyActiveDevice,
584                                      getDeviceTypeStrForPortId(other->deviceId).c_str());
585                 }
586             }
587             item->selfrecord();
588             delete item;
589             item = NULL;
590         }
591     }
592 
593     if (status != NO_ERROR) {
594         client->active = false;
595         client->startTimeNs = 0;
596         updateUidStates_l();
597         finishRecording(client->opPackageName, client->uid);
598     }
599 
600     return status;
601 }
602 
stopInput(audio_port_handle_t portId)603 status_t AudioPolicyService::stopInput(audio_port_handle_t portId)
604 {
605     if (mAudioPolicyManager == NULL) {
606         return NO_INIT;
607     }
608 
609     Mutex::Autolock _l(mLock);
610 
611     ssize_t index = mAudioRecordClients.indexOfKey(portId);
612     if (index < 0) {
613         return INVALID_OPERATION;
614     }
615     sp<AudioRecordClient> client = mAudioRecordClients.valueAt(index);
616 
617     client->active = false;
618     client->startTimeNs = 0;
619 
620     updateUidStates_l();
621 
622     // finish the recording app op
623     finishRecording(client->opPackageName, client->uid);
624     AutoCallerClear acc;
625     return mAudioPolicyManager->stopInput(portId);
626 }
627 
releaseInput(audio_port_handle_t portId)628 void AudioPolicyService::releaseInput(audio_port_handle_t portId)
629 {
630     if (mAudioPolicyManager == NULL) {
631         return;
632     }
633     sp<AudioPolicyEffects>audioPolicyEffects;
634     sp<AudioRecordClient> client;
635     {
636         Mutex::Autolock _l(mLock);
637         audioPolicyEffects = mAudioPolicyEffects;
638         ssize_t index = mAudioRecordClients.indexOfKey(portId);
639         if (index < 0) {
640             return;
641         }
642         client = mAudioRecordClients.valueAt(index);
643 
644         if (client->active) {
645             ALOGW("%s releasing active client portId %d", __FUNCTION__, portId);
646             client->active = false;
647             client->startTimeNs = 0;
648             updateUidStates_l();
649         }
650 
651         mAudioRecordClients.removeItem(portId);
652     }
653     if (client == 0) {
654         return;
655     }
656     if (audioPolicyEffects != 0) {
657         // release audio processors from the input
658         status_t status = audioPolicyEffects->releaseInputEffects(client->io, client->session);
659         if(status != NO_ERROR) {
660             ALOGW("Failed to release effects on input %d", client->io);
661         }
662     }
663     {
664         Mutex::Autolock _l(mLock);
665         AutoCallerClear acc;
666         mAudioPolicyManager->releaseInput(portId);
667     }
668 }
669 
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)670 status_t AudioPolicyService::initStreamVolume(audio_stream_type_t stream,
671                                             int indexMin,
672                                             int indexMax)
673 {
674     if (mAudioPolicyManager == NULL) {
675         return NO_INIT;
676     }
677     if (!settingsAllowed()) {
678         return PERMISSION_DENIED;
679     }
680     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
681         return BAD_VALUE;
682     }
683     Mutex::Autolock _l(mLock);
684     AutoCallerClear acc;
685     mAudioPolicyManager->initStreamVolume(stream, indexMin, indexMax);
686     return NO_ERROR;
687 }
688 
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)689 status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,
690                                                   int index,
691                                                   audio_devices_t device)
692 {
693     if (mAudioPolicyManager == NULL) {
694         return NO_INIT;
695     }
696     if (!settingsAllowed()) {
697         return PERMISSION_DENIED;
698     }
699     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
700         return BAD_VALUE;
701     }
702     Mutex::Autolock _l(mLock);
703     AutoCallerClear acc;
704     return mAudioPolicyManager->setStreamVolumeIndex(stream,
705                                                     index,
706                                                     device);
707 }
708 
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)709 status_t AudioPolicyService::getStreamVolumeIndex(audio_stream_type_t stream,
710                                                   int *index,
711                                                   audio_devices_t device)
712 {
713     if (mAudioPolicyManager == NULL) {
714         return NO_INIT;
715     }
716     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
717         return BAD_VALUE;
718     }
719     Mutex::Autolock _l(mLock);
720     AutoCallerClear acc;
721     return mAudioPolicyManager->getStreamVolumeIndex(stream,
722                                                     index,
723                                                     device);
724 }
725 
setVolumeIndexForAttributes(const audio_attributes_t & attributes,int index,audio_devices_t device)726 status_t AudioPolicyService::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
727                                                          int index, audio_devices_t device)
728 {
729     if (mAudioPolicyManager == NULL) {
730         return NO_INIT;
731     }
732     if (!settingsAllowed()) {
733         return PERMISSION_DENIED;
734     }
735     Mutex::Autolock _l(mLock);
736     AutoCallerClear acc;
737     return mAudioPolicyManager->setVolumeIndexForAttributes(attributes, index, device);
738 }
739 
getVolumeIndexForAttributes(const audio_attributes_t & attributes,int & index,audio_devices_t device)740 status_t AudioPolicyService::getVolumeIndexForAttributes(const audio_attributes_t &attributes,
741                                                          int &index, audio_devices_t device)
742 {
743     if (mAudioPolicyManager == NULL) {
744         return NO_INIT;
745     }
746     Mutex::Autolock _l(mLock);
747     AutoCallerClear acc;
748     return mAudioPolicyManager->getVolumeIndexForAttributes(attributes, index, device);
749 }
750 
getMinVolumeIndexForAttributes(const audio_attributes_t & attributes,int & index)751 status_t AudioPolicyService::getMinVolumeIndexForAttributes(const audio_attributes_t &attributes,
752                                                             int &index)
753 {
754     if (mAudioPolicyManager == NULL) {
755         return NO_INIT;
756     }
757     Mutex::Autolock _l(mLock);
758     AutoCallerClear acc;
759     return mAudioPolicyManager->getMinVolumeIndexForAttributes(attributes, index);
760 }
761 
getMaxVolumeIndexForAttributes(const audio_attributes_t & attributes,int & index)762 status_t AudioPolicyService::getMaxVolumeIndexForAttributes(const audio_attributes_t &attributes,
763                                                             int &index)
764 {
765     if (mAudioPolicyManager == NULL) {
766         return NO_INIT;
767     }
768     Mutex::Autolock _l(mLock);
769     AutoCallerClear acc;
770     return mAudioPolicyManager->getMaxVolumeIndexForAttributes(attributes, index);
771 }
772 
getStrategyForStream(audio_stream_type_t stream)773 uint32_t AudioPolicyService::getStrategyForStream(audio_stream_type_t stream)
774 {
775     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
776         return PRODUCT_STRATEGY_NONE;
777     }
778     if (mAudioPolicyManager == NULL) {
779         return PRODUCT_STRATEGY_NONE;
780     }
781     // DO NOT LOCK, may be called from AudioFlinger with lock held, reaching deadlock
782     AutoCallerClear acc;
783     return mAudioPolicyManager->getStrategyForStream(stream);
784 }
785 
786 //audio policy: use audio_device_t appropriately
787 
getDevicesForStream(audio_stream_type_t stream)788 audio_devices_t AudioPolicyService::getDevicesForStream(audio_stream_type_t stream)
789 {
790     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
791         return AUDIO_DEVICE_NONE;
792     }
793     if (mAudioPolicyManager == NULL) {
794         return AUDIO_DEVICE_NONE;
795     }
796     Mutex::Autolock _l(mLock);
797     AutoCallerClear acc;
798     return mAudioPolicyManager->getDevicesForStream(stream);
799 }
800 
getOutputForEffect(const effect_descriptor_t * desc)801 audio_io_handle_t AudioPolicyService::getOutputForEffect(const effect_descriptor_t *desc)
802 {
803     // FIXME change return type to status_t, and return NO_INIT here
804     if (mAudioPolicyManager == NULL) {
805         return 0;
806     }
807     Mutex::Autolock _l(mLock);
808     AutoCallerClear acc;
809     return mAudioPolicyManager->getOutputForEffect(desc);
810 }
811 
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,audio_session_t session,int id)812 status_t AudioPolicyService::registerEffect(const effect_descriptor_t *desc,
813                                 audio_io_handle_t io,
814                                 uint32_t strategy,
815                                 audio_session_t session,
816                                 int id)
817 {
818     if (mAudioPolicyManager == NULL) {
819         return NO_INIT;
820     }
821     Mutex::Autolock _l(mLock);
822     AutoCallerClear acc;
823     return mAudioPolicyManager->registerEffect(desc, io, strategy, session, id);
824 }
825 
unregisterEffect(int id)826 status_t AudioPolicyService::unregisterEffect(int id)
827 {
828     if (mAudioPolicyManager == NULL) {
829         return NO_INIT;
830     }
831     Mutex::Autolock _l(mLock);
832     AutoCallerClear acc;
833     return mAudioPolicyManager->unregisterEffect(id);
834 }
835 
setEffectEnabled(int id,bool enabled)836 status_t AudioPolicyService::setEffectEnabled(int id, bool enabled)
837 {
838     if (mAudioPolicyManager == NULL) {
839         return NO_INIT;
840     }
841     Mutex::Autolock _l(mLock);
842     AutoCallerClear acc;
843     return mAudioPolicyManager->setEffectEnabled(id, enabled);
844 }
845 
moveEffectsToIo(const std::vector<int> & ids,audio_io_handle_t io)846 status_t AudioPolicyService::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
847 {
848     if (mAudioPolicyManager == NULL) {
849         return NO_INIT;
850     }
851     Mutex::Autolock _l(mLock);
852     AutoCallerClear acc;
853     return mAudioPolicyManager->moveEffectsToIo(ids, io);
854 }
855 
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const856 bool AudioPolicyService::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
857 {
858     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
859         return false;
860     }
861     if (mAudioPolicyManager == NULL) {
862         return false;
863     }
864     Mutex::Autolock _l(mLock);
865     AutoCallerClear acc;
866     return mAudioPolicyManager->isStreamActive(stream, inPastMs);
867 }
868 
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const869 bool AudioPolicyService::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
870 {
871     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
872         return false;
873     }
874     if (mAudioPolicyManager == NULL) {
875         return false;
876     }
877     Mutex::Autolock _l(mLock);
878     AutoCallerClear acc;
879     return mAudioPolicyManager->isStreamActiveRemotely(stream, inPastMs);
880 }
881 
isSourceActive(audio_source_t source) const882 bool AudioPolicyService::isSourceActive(audio_source_t source) const
883 {
884     if (mAudioPolicyManager == NULL) {
885         return false;
886     }
887     Mutex::Autolock _l(mLock);
888     AutoCallerClear acc;
889     return mAudioPolicyManager->isSourceActive(source);
890 }
891 
getAudioPolicyEffects(sp<AudioPolicyEffects> & audioPolicyEffects)892 status_t AudioPolicyService::getAudioPolicyEffects(sp<AudioPolicyEffects>& audioPolicyEffects)
893 {
894     if (mAudioPolicyManager == NULL) {
895         return NO_INIT;
896     }
897     {
898         Mutex::Autolock _l(mLock);
899         audioPolicyEffects = mAudioPolicyEffects;
900     }
901     if (audioPolicyEffects == 0) {
902         return NO_INIT;
903     }
904 
905     return OK;
906 }
907 
queryDefaultPreProcessing(audio_session_t audioSession,effect_descriptor_t * descriptors,uint32_t * count)908 status_t AudioPolicyService::queryDefaultPreProcessing(audio_session_t audioSession,
909                                                        effect_descriptor_t *descriptors,
910                                                        uint32_t *count)
911 {
912     sp<AudioPolicyEffects>audioPolicyEffects;
913     status_t status = getAudioPolicyEffects(audioPolicyEffects);
914     if (status != OK) {
915         *count = 0;
916         return status;
917     }
918     return audioPolicyEffects->queryDefaultInputEffects(
919             (audio_session_t)audioSession, descriptors, count);
920 }
921 
addSourceDefaultEffect(const effect_uuid_t * type,const String16 & opPackageName,const effect_uuid_t * uuid,int32_t priority,audio_source_t source,audio_unique_id_t * id)922 status_t AudioPolicyService::addSourceDefaultEffect(const effect_uuid_t *type,
923                                                     const String16& opPackageName,
924                                                     const effect_uuid_t *uuid,
925                                                     int32_t priority,
926                                                     audio_source_t source,
927                                                     audio_unique_id_t* id)
928 {
929     sp<AudioPolicyEffects>audioPolicyEffects;
930     status_t status = getAudioPolicyEffects(audioPolicyEffects);
931     if (status != OK) {
932         return status;
933     }
934     if (!modifyDefaultAudioEffectsAllowed()) {
935         return PERMISSION_DENIED;
936     }
937     return audioPolicyEffects->addSourceDefaultEffect(
938             type, opPackageName, uuid, priority, source, id);
939 }
940 
addStreamDefaultEffect(const effect_uuid_t * type,const String16 & opPackageName,const effect_uuid_t * uuid,int32_t priority,audio_usage_t usage,audio_unique_id_t * id)941 status_t AudioPolicyService::addStreamDefaultEffect(const effect_uuid_t *type,
942                                                     const String16& opPackageName,
943                                                     const effect_uuid_t *uuid,
944                                                     int32_t priority,
945                                                     audio_usage_t usage,
946                                                     audio_unique_id_t* id)
947 {
948     sp<AudioPolicyEffects>audioPolicyEffects;
949     status_t status = getAudioPolicyEffects(audioPolicyEffects);
950     if (status != OK) {
951         return status;
952     }
953     if (!modifyDefaultAudioEffectsAllowed()) {
954         return PERMISSION_DENIED;
955     }
956     return audioPolicyEffects->addStreamDefaultEffect(
957             type, opPackageName, uuid, priority, usage, id);
958 }
959 
removeSourceDefaultEffect(audio_unique_id_t id)960 status_t AudioPolicyService::removeSourceDefaultEffect(audio_unique_id_t id)
961 {
962     sp<AudioPolicyEffects>audioPolicyEffects;
963     status_t status = getAudioPolicyEffects(audioPolicyEffects);
964     if (status != OK) {
965         return status;
966     }
967     if (!modifyDefaultAudioEffectsAllowed()) {
968         return PERMISSION_DENIED;
969     }
970     return audioPolicyEffects->removeSourceDefaultEffect(id);
971 }
972 
removeStreamDefaultEffect(audio_unique_id_t id)973 status_t AudioPolicyService::removeStreamDefaultEffect(audio_unique_id_t id)
974 {
975     sp<AudioPolicyEffects>audioPolicyEffects;
976     status_t status = getAudioPolicyEffects(audioPolicyEffects);
977     if (status != OK) {
978         return status;
979     }
980     if (!modifyDefaultAudioEffectsAllowed()) {
981         return PERMISSION_DENIED;
982     }
983     return audioPolicyEffects->removeStreamDefaultEffect(id);
984 }
985 
setAllowedCapturePolicy(uid_t uid,audio_flags_mask_t capturePolicy)986 status_t AudioPolicyService::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy) {
987     Mutex::Autolock _l(mLock);
988     if (mAudioPolicyManager == NULL) {
989         ALOGV("%s() mAudioPolicyManager == NULL", __func__);
990         return NO_INIT;
991     }
992     return mAudioPolicyManager->setAllowedCapturePolicy(uid, capturePolicy);
993 }
994 
isOffloadSupported(const audio_offload_info_t & info)995 bool AudioPolicyService::isOffloadSupported(const audio_offload_info_t& info)
996 {
997     if (mAudioPolicyManager == NULL) {
998         ALOGV("mAudioPolicyManager == NULL");
999         return false;
1000     }
1001     Mutex::Autolock _l(mLock);
1002     AutoCallerClear acc;
1003     return mAudioPolicyManager->isOffloadSupported(info);
1004 }
1005 
isDirectOutputSupported(const audio_config_base_t & config,const audio_attributes_t & attributes)1006 bool AudioPolicyService::isDirectOutputSupported(const audio_config_base_t& config,
1007                                                  const audio_attributes_t& attributes) {
1008     if (mAudioPolicyManager == NULL) {
1009         ALOGV("mAudioPolicyManager == NULL");
1010         return false;
1011     }
1012     Mutex::Autolock _l(mLock);
1013     return mAudioPolicyManager->isDirectOutputSupported(config, attributes);
1014 }
1015 
1016 
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)1017 status_t AudioPolicyService::listAudioPorts(audio_port_role_t role,
1018                                             audio_port_type_t type,
1019                                             unsigned int *num_ports,
1020                                             struct audio_port *ports,
1021                                             unsigned int *generation)
1022 {
1023     Mutex::Autolock _l(mLock);
1024     if (mAudioPolicyManager == NULL) {
1025         return NO_INIT;
1026     }
1027     AutoCallerClear acc;
1028     return mAudioPolicyManager->listAudioPorts(role, type, num_ports, ports, generation);
1029 }
1030 
getAudioPort(struct audio_port * port)1031 status_t AudioPolicyService::getAudioPort(struct audio_port *port)
1032 {
1033     Mutex::Autolock _l(mLock);
1034     if (mAudioPolicyManager == NULL) {
1035         return NO_INIT;
1036     }
1037     AutoCallerClear acc;
1038     return mAudioPolicyManager->getAudioPort(port);
1039 }
1040 
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)1041 status_t AudioPolicyService::createAudioPatch(const struct audio_patch *patch,
1042         audio_patch_handle_t *handle)
1043 {
1044     Mutex::Autolock _l(mLock);
1045     if(!modifyAudioRoutingAllowed()) {
1046         return PERMISSION_DENIED;
1047     }
1048     if (mAudioPolicyManager == NULL) {
1049         return NO_INIT;
1050     }
1051     AutoCallerClear acc;
1052     return mAudioPolicyManager->createAudioPatch(patch, handle,
1053                                                   IPCThreadState::self()->getCallingUid());
1054 }
1055 
releaseAudioPatch(audio_patch_handle_t handle)1056 status_t AudioPolicyService::releaseAudioPatch(audio_patch_handle_t handle)
1057 {
1058     Mutex::Autolock _l(mLock);
1059     if(!modifyAudioRoutingAllowed()) {
1060         return PERMISSION_DENIED;
1061     }
1062     if (mAudioPolicyManager == NULL) {
1063         return NO_INIT;
1064     }
1065     AutoCallerClear acc;
1066     return mAudioPolicyManager->releaseAudioPatch(handle,
1067                                                      IPCThreadState::self()->getCallingUid());
1068 }
1069 
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)1070 status_t AudioPolicyService::listAudioPatches(unsigned int *num_patches,
1071         struct audio_patch *patches,
1072         unsigned int *generation)
1073 {
1074     Mutex::Autolock _l(mLock);
1075     if (mAudioPolicyManager == NULL) {
1076         return NO_INIT;
1077     }
1078     AutoCallerClear acc;
1079     return mAudioPolicyManager->listAudioPatches(num_patches, patches, generation);
1080 }
1081 
setAudioPortConfig(const struct audio_port_config * config)1082 status_t AudioPolicyService::setAudioPortConfig(const struct audio_port_config *config)
1083 {
1084     Mutex::Autolock _l(mLock);
1085     if(!modifyAudioRoutingAllowed()) {
1086         return PERMISSION_DENIED;
1087     }
1088     if (mAudioPolicyManager == NULL) {
1089         return NO_INIT;
1090     }
1091     AutoCallerClear acc;
1092     return mAudioPolicyManager->setAudioPortConfig(config);
1093 }
1094 
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)1095 status_t AudioPolicyService::acquireSoundTriggerSession(audio_session_t *session,
1096                                        audio_io_handle_t *ioHandle,
1097                                        audio_devices_t *device)
1098 {
1099     Mutex::Autolock _l(mLock);
1100     if (mAudioPolicyManager == NULL) {
1101         return NO_INIT;
1102     }
1103     AutoCallerClear acc;
1104     return mAudioPolicyManager->acquireSoundTriggerSession(session, ioHandle, device);
1105 }
1106 
releaseSoundTriggerSession(audio_session_t session)1107 status_t AudioPolicyService::releaseSoundTriggerSession(audio_session_t session)
1108 {
1109     Mutex::Autolock _l(mLock);
1110     if (mAudioPolicyManager == NULL) {
1111         return NO_INIT;
1112     }
1113     AutoCallerClear acc;
1114     return mAudioPolicyManager->releaseSoundTriggerSession(session);
1115 }
1116 
registerPolicyMixes(const Vector<AudioMix> & mixes,bool registration)1117 status_t AudioPolicyService::registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration)
1118 {
1119     Mutex::Autolock _l(mLock);
1120 
1121     // loopback|render only need a MediaProjection (checked in caller AudioService.java)
1122     bool needModifyAudioRouting = std::any_of(mixes.begin(), mixes.end(), [](auto& mix) {
1123             return !is_mix_loopback_render(mix.mRouteFlags); });
1124     if (needModifyAudioRouting && !modifyAudioRoutingAllowed()) {
1125         return PERMISSION_DENIED;
1126     }
1127 
1128     bool needCaptureMediaOutput = std::any_of(mixes.begin(), mixes.end(), [](auto& mix) {
1129             return mix.mAllowPrivilegedPlaybackCapture; });
1130     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1131     const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1132     if (needCaptureMediaOutput && !captureMediaOutputAllowed(callingPid, callingUid)) {
1133         return PERMISSION_DENIED;
1134     }
1135 
1136     if (mAudioPolicyManager == NULL) {
1137         return NO_INIT;
1138     }
1139     AutoCallerClear acc;
1140     if (registration) {
1141         return mAudioPolicyManager->registerPolicyMixes(mixes);
1142     } else {
1143         return mAudioPolicyManager->unregisterPolicyMixes(mixes);
1144     }
1145 }
1146 
setUidDeviceAffinities(uid_t uid,const Vector<AudioDeviceTypeAddr> & devices)1147 status_t AudioPolicyService::setUidDeviceAffinities(uid_t uid,
1148         const Vector<AudioDeviceTypeAddr>& devices) {
1149     Mutex::Autolock _l(mLock);
1150     if(!modifyAudioRoutingAllowed()) {
1151         return PERMISSION_DENIED;
1152     }
1153     if (mAudioPolicyManager == NULL) {
1154         return NO_INIT;
1155     }
1156     AutoCallerClear acc;
1157     return mAudioPolicyManager->setUidDeviceAffinities(uid, devices);
1158 }
1159 
removeUidDeviceAffinities(uid_t uid)1160 status_t AudioPolicyService::removeUidDeviceAffinities(uid_t uid) {
1161     Mutex::Autolock _l(mLock);
1162     if(!modifyAudioRoutingAllowed()) {
1163         return PERMISSION_DENIED;
1164     }
1165     if (mAudioPolicyManager == NULL) {
1166         return NO_INIT;
1167     }
1168     AutoCallerClear acc;
1169     return mAudioPolicyManager->removeUidDeviceAffinities(uid);
1170 }
1171 
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId)1172 status_t AudioPolicyService::startAudioSource(const struct audio_port_config *source,
1173                                               const audio_attributes_t *attributes,
1174                                               audio_port_handle_t *portId)
1175 {
1176     Mutex::Autolock _l(mLock);
1177     if (mAudioPolicyManager == NULL) {
1178         return NO_INIT;
1179     }
1180     // startAudioSource should be created as the calling uid
1181     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1182     AutoCallerClear acc;
1183     return mAudioPolicyManager->startAudioSource(source, attributes, portId, callingUid);
1184 }
1185 
stopAudioSource(audio_port_handle_t portId)1186 status_t AudioPolicyService::stopAudioSource(audio_port_handle_t portId)
1187 {
1188     Mutex::Autolock _l(mLock);
1189     if (mAudioPolicyManager == NULL) {
1190         return NO_INIT;
1191     }
1192     AutoCallerClear acc;
1193     return mAudioPolicyManager->stopAudioSource(portId);
1194 }
1195 
setMasterMono(bool mono)1196 status_t AudioPolicyService::setMasterMono(bool mono)
1197 {
1198     if (mAudioPolicyManager == NULL) {
1199         return NO_INIT;
1200     }
1201     if (!settingsAllowed()) {
1202         return PERMISSION_DENIED;
1203     }
1204     Mutex::Autolock _l(mLock);
1205     AutoCallerClear acc;
1206     return mAudioPolicyManager->setMasterMono(mono);
1207 }
1208 
getMasterMono(bool * mono)1209 status_t AudioPolicyService::getMasterMono(bool *mono)
1210 {
1211     if (mAudioPolicyManager == NULL) {
1212         return NO_INIT;
1213     }
1214     Mutex::Autolock _l(mLock);
1215     AutoCallerClear acc;
1216     return mAudioPolicyManager->getMasterMono(mono);
1217 }
1218 
1219 
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)1220 float AudioPolicyService::getStreamVolumeDB(
1221             audio_stream_type_t stream, int index, audio_devices_t device)
1222 {
1223     if (mAudioPolicyManager == NULL) {
1224         return NAN;
1225     }
1226     Mutex::Autolock _l(mLock);
1227     AutoCallerClear acc;
1228     return mAudioPolicyManager->getStreamVolumeDB(stream, index, device);
1229 }
1230 
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled,bool reported)1231 status_t AudioPolicyService::getSurroundFormats(unsigned int *numSurroundFormats,
1232                                                 audio_format_t *surroundFormats,
1233                                                 bool *surroundFormatsEnabled,
1234                                                 bool reported)
1235 {
1236     if (mAudioPolicyManager == NULL) {
1237         return NO_INIT;
1238     }
1239     Mutex::Autolock _l(mLock);
1240     AutoCallerClear acc;
1241     return mAudioPolicyManager->getSurroundFormats(numSurroundFormats, surroundFormats,
1242                                                    surroundFormatsEnabled, reported);
1243 }
1244 
getHwOffloadEncodingFormatsSupportedForA2DP(std::vector<audio_format_t> * formats)1245 status_t AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP(
1246                                         std::vector<audio_format_t> *formats)
1247 {
1248     if (mAudioPolicyManager == NULL) {
1249         return NO_INIT;
1250     }
1251     Mutex::Autolock _l(mLock);
1252     AutoCallerClear acc;
1253     return mAudioPolicyManager->getHwOffloadEncodingFormatsSupportedForA2DP(formats);
1254 }
1255 
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)1256 status_t AudioPolicyService::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
1257 {
1258     if (mAudioPolicyManager == NULL) {
1259         return NO_INIT;
1260     }
1261     Mutex::Autolock _l(mLock);
1262     AutoCallerClear acc;
1263     return mAudioPolicyManager->setSurroundFormatEnabled(audioFormat, enabled);
1264 }
1265 
setAssistantUid(uid_t uid)1266 status_t AudioPolicyService::setAssistantUid(uid_t uid)
1267 {
1268     Mutex::Autolock _l(mLock);
1269     mUidPolicy->setAssistantUid(uid);
1270     return NO_ERROR;
1271 }
1272 
setA11yServicesUids(const std::vector<uid_t> & uids)1273 status_t AudioPolicyService::setA11yServicesUids(const std::vector<uid_t>& uids)
1274 {
1275     Mutex::Autolock _l(mLock);
1276     mUidPolicy->setA11yUids(uids);
1277     return NO_ERROR;
1278 }
1279 
isHapticPlaybackSupported()1280 bool AudioPolicyService::isHapticPlaybackSupported()
1281 {
1282     if (mAudioPolicyManager == NULL) {
1283         ALOGW("%s, mAudioPolicyManager == NULL", __func__);
1284         return false;
1285     }
1286     Mutex::Autolock _l(mLock);
1287     AutoCallerClear acc;
1288     return mAudioPolicyManager->isHapticPlaybackSupported();
1289 }
1290 
listAudioProductStrategies(AudioProductStrategyVector & strategies)1291 status_t AudioPolicyService::listAudioProductStrategies(AudioProductStrategyVector &strategies)
1292 {
1293     if (mAudioPolicyManager == NULL) {
1294         return NO_INIT;
1295     }
1296     Mutex::Autolock _l(mLock);
1297     return mAudioPolicyManager->listAudioProductStrategies(strategies);
1298 }
1299 
getProductStrategyFromAudioAttributes(const AudioAttributes & aa,product_strategy_t & productStrategy)1300 status_t AudioPolicyService::getProductStrategyFromAudioAttributes(
1301         const AudioAttributes &aa, product_strategy_t &productStrategy)
1302 {
1303     if (mAudioPolicyManager == NULL) {
1304         return NO_INIT;
1305     }
1306     Mutex::Autolock _l(mLock);
1307     return mAudioPolicyManager->getProductStrategyFromAudioAttributes(aa, productStrategy);
1308 }
1309 
listAudioVolumeGroups(AudioVolumeGroupVector & groups)1310 status_t AudioPolicyService::listAudioVolumeGroups(AudioVolumeGroupVector &groups)
1311 {
1312     if (mAudioPolicyManager == NULL) {
1313         return NO_INIT;
1314     }
1315     Mutex::Autolock _l(mLock);
1316     return mAudioPolicyManager->listAudioVolumeGroups(groups);
1317 }
1318 
getVolumeGroupFromAudioAttributes(const AudioAttributes & aa,volume_group_t & volumeGroup)1319 status_t AudioPolicyService::getVolumeGroupFromAudioAttributes(const AudioAttributes &aa,
1320                                                                volume_group_t &volumeGroup)
1321 {
1322     if (mAudioPolicyManager == NULL) {
1323         return NO_INIT;
1324     }
1325     Mutex::Autolock _l(mLock);
1326     return mAudioPolicyManager->getVolumeGroupFromAudioAttributes(aa, volumeGroup);
1327 }
1328 
setRttEnabled(bool enabled)1329 status_t AudioPolicyService::setRttEnabled(bool enabled)
1330 {
1331     Mutex::Autolock _l(mLock);
1332     mUidPolicy->setRttEnabled(enabled);
1333     return NO_ERROR;
1334 }
1335 
setPreferredDeviceForStrategy(product_strategy_t strategy,const AudioDeviceTypeAddr & device)1336 status_t AudioPolicyService::setPreferredDeviceForStrategy(product_strategy_t strategy,
1337                                                    const AudioDeviceTypeAddr &device)
1338 {
1339     if (mAudioPolicyManager == NULL) {
1340         return NO_INIT;
1341     }
1342     Mutex::Autolock _l(mLock);
1343     return mAudioPolicyManager->setPreferredDeviceForStrategy(strategy, device);
1344 }
1345 
removePreferredDeviceForStrategy(product_strategy_t strategy)1346 status_t AudioPolicyService::removePreferredDeviceForStrategy(product_strategy_t strategy)
1347 {
1348     if (mAudioPolicyManager == NULL) {
1349         return NO_INIT;
1350     }
1351     Mutex::Autolock _l(mLock);
1352     return mAudioPolicyManager->removePreferredDeviceForStrategy(strategy);
1353 }
1354 
getPreferredDeviceForStrategy(product_strategy_t strategy,AudioDeviceTypeAddr & device)1355 status_t AudioPolicyService::getPreferredDeviceForStrategy(product_strategy_t strategy,
1356                                                    AudioDeviceTypeAddr &device)
1357 {
1358     if (mAudioPolicyManager == NULL) {
1359         return NO_INIT;
1360     }
1361     Mutex::Autolock _l(mLock);
1362     return mAudioPolicyManager->getPreferredDeviceForStrategy(strategy, device);
1363 }
1364 
1365 } // namespace android
1366