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