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 "AudioPolicyInterfaceImpl"
18 //#define LOG_NDEBUG 0
19 
20 #include "AudioPolicyService.h"
21 #include "AudioRecordClient.h"
22 #include "TypeConverter.h"
23 
24 #include <android/content/AttributionSourceState.h>
25 #include <android_media_audiopolicy.h>
26 #include <media/AidlConversion.h>
27 #include <media/AudioPolicy.h>
28 #include <media/AudioValidator.h>
29 #include <media/MediaMetricsItem.h>
30 #include <media/PolicyAidlConversion.h>
31 #include <utils/Log.h>
32 
33 #define VALUE_OR_RETURN_BINDER_STATUS(x) \
34     ({ auto _tmp = (x); \
35        if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \
36        std::move(_tmp.value()); })
37 
38 #define RETURN_BINDER_STATUS_IF_ERROR(x) \
39     if (status_t _tmp = (x); _tmp != OK) return aidl_utils::binderStatusFromStatusT(_tmp);
40 
41 #define RETURN_IF_BINDER_ERROR(x)      \
42     {                                  \
43         binder::Status _tmp = (x);     \
44         if (!_tmp.isOk()) return _tmp; \
45     }
46 
47 #define MAX_ITEMS_PER_LIST 1024
48 
49 namespace android {
50 namespace audiopolicy_flags = android::media::audiopolicy;
51 using binder::Status;
52 using aidl_utils::binderStatusFromStatusT;
53 using com::android::media::permission::NativePermissionController;
54 using content::AttributionSourceState;
55 using media::audio::common::AudioConfig;
56 using media::audio::common::AudioConfigBase;
57 using media::audio::common::AudioDevice;
58 using media::audio::common::AudioDeviceAddress;
59 using media::audio::common::AudioDeviceDescription;
60 using media::audio::common::AudioFormatDescription;
61 using media::audio::common::AudioMode;
62 using media::audio::common::AudioOffloadInfo;
63 using media::audio::common::AudioSource;
64 using media::audio::common::AudioStreamType;
65 using media::audio::common::AudioUsage;
66 using media::audio::common::AudioUuid;
67 using media::audio::common::Int;
68 
69 constexpr int kDefaultVirtualDeviceId = 0;
70 
71 const std::vector<audio_usage_t>& SYSTEM_USAGES = {
72     AUDIO_USAGE_CALL_ASSISTANT,
73     AUDIO_USAGE_EMERGENCY,
74     AUDIO_USAGE_SAFETY,
75     AUDIO_USAGE_VEHICLE_STATUS,
76     AUDIO_USAGE_ANNOUNCEMENT
77 };
78 
isSystemUsage(audio_usage_t usage)79 bool isSystemUsage(audio_usage_t usage) {
80     return std::find(std::begin(SYSTEM_USAGES), std::end(SYSTEM_USAGES), usage)
81         != std::end(SYSTEM_USAGES);
82 }
83 
isSupportedSystemUsage(audio_usage_t usage)84 bool AudioPolicyService::isSupportedSystemUsage(audio_usage_t usage) {
85     return std::find(std::begin(mSupportedSystemUsages), std::end(mSupportedSystemUsages), usage)
86         != std::end(mSupportedSystemUsages);
87 }
88 
validateUsage(const audio_attributes_t & attr)89 status_t AudioPolicyService::validateUsage(const audio_attributes_t& attr) {
90      return validateUsage(attr, getCallingAttributionSource());
91 }
92 
validateUsage(const audio_attributes_t & attr,const AttributionSourceState & attributionSource)93 status_t AudioPolicyService::validateUsage(const audio_attributes_t& attr,
94         const AttributionSourceState& attributionSource) {
95     if (isSystemUsage(attr.usage)) {
96         if (isSupportedSystemUsage(attr.usage)) {
97             if (attr.usage == AUDIO_USAGE_CALL_ASSISTANT
98                     && ((attr.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0)) {
99                 if (!callAudioInterceptionAllowed(attributionSource)) {
100                     ALOGE("%s: call audio interception not allowed for attribution source: %s",
101                            __func__, attributionSource.toString().c_str());
102                     return PERMISSION_DENIED;
103                 }
104             } else if (!modifyAudioRoutingAllowed(attributionSource)) {
105                 ALOGE("%s: modify audio routing not allowed for attribution source: %s",
106                         __func__, attributionSource.toString().c_str());
107                 return PERMISSION_DENIED;
108             }
109         } else {
110             return BAD_VALUE;
111         }
112     }
113     return NO_ERROR;
114 }
115 
116 
117 
118 // ----------------------------------------------------------------------------
119 
doOnNewAudioModulesAvailable()120 void AudioPolicyService::doOnNewAudioModulesAvailable()
121 {
122     if (mAudioPolicyManager == NULL) return;
123     audio_utils::lock_guard _l(mMutex);
124     AutoCallerClear acc;
125     mAudioPolicyManager->onNewAudioModulesAvailable();
126 }
127 
setDeviceConnectionState(media::AudioPolicyDeviceState stateAidl,const android::media::audio::common::AudioPort & port,const AudioFormatDescription & encodedFormatAidl)128 Status AudioPolicyService::setDeviceConnectionState(
129         media::AudioPolicyDeviceState stateAidl,
130         const android::media::audio::common::AudioPort& port,
131         const AudioFormatDescription& encodedFormatAidl) {
132     audio_policy_dev_state_t state = VALUE_OR_RETURN_BINDER_STATUS(
133             aidl2legacy_AudioPolicyDeviceState_audio_policy_dev_state_t(stateAidl));
134     audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS(
135             aidl2legacy_AudioFormatDescription_audio_format_t(encodedFormatAidl));
136 
137     if (mAudioPolicyManager == NULL) {
138         return binderStatusFromStatusT(NO_INIT);
139     }
140     if (!settingsAllowed()) {
141         return binderStatusFromStatusT(PERMISSION_DENIED);
142     }
143     if (state != AUDIO_POLICY_DEVICE_STATE_AVAILABLE &&
144             state != AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
145         return binderStatusFromStatusT(BAD_VALUE);
146     }
147 
148     ALOGV("setDeviceConnectionState()");
149     audio_utils::lock_guard _l(mMutex);
150     AutoCallerClear acc;
151     status_t status = mAudioPolicyManager->setDeviceConnectionState(
152             state, port, encodedFormat);
153     if (status == NO_ERROR) {
154         onCheckSpatializer_l();
155     }
156     return binderStatusFromStatusT(status);
157 }
158 
getDeviceConnectionState(const AudioDevice & deviceAidl,media::AudioPolicyDeviceState * _aidl_return)159 Status AudioPolicyService::getDeviceConnectionState(const AudioDevice& deviceAidl,
160                                                     media::AudioPolicyDeviceState* _aidl_return) {
161     audio_devices_t device;
162     std::string address;
163     RETURN_BINDER_STATUS_IF_ERROR(
164             aidl2legacy_AudioDevice_audio_device(deviceAidl, &device, &address));
165     if (mAudioPolicyManager == NULL) {
166         *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
167                 legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState(
168                         AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
169         return Status::ok();
170     }
171     audio_utils::lock_guard _l(mMutex);
172     AutoCallerClear acc;
173     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
174             legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState(
175                     mAudioPolicyManager->getDeviceConnectionState(
176                             device, address.c_str())));
177     return Status::ok();
178 }
179 
handleDeviceConfigChange(const AudioDevice & deviceAidl,const std::string & deviceNameAidl,const AudioFormatDescription & encodedFormatAidl)180 Status AudioPolicyService::handleDeviceConfigChange(
181         const AudioDevice& deviceAidl,
182         const std::string& deviceNameAidl,
183         const AudioFormatDescription& encodedFormatAidl) {
184     audio_devices_t device;
185     std::string address;
186     RETURN_BINDER_STATUS_IF_ERROR(
187             aidl2legacy_AudioDevice_audio_device(deviceAidl, &device, &address));
188     audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS(
189             aidl2legacy_AudioFormatDescription_audio_format_t(encodedFormatAidl));
190 
191     if (mAudioPolicyManager == NULL) {
192         return binderStatusFromStatusT(NO_INIT);
193     }
194     if (!settingsAllowed()) {
195         return binderStatusFromStatusT(PERMISSION_DENIED);
196     }
197 
198     ALOGV("handleDeviceConfigChange()");
199     audio_utils::lock_guard _l(mMutex);
200     AutoCallerClear acc;
201     status_t status =  mAudioPolicyManager->handleDeviceConfigChange(
202             device, address.c_str(), deviceNameAidl.c_str(), encodedFormat);
203 
204     if (status == NO_ERROR) {
205        onCheckSpatializer_l();
206     }
207     return binderStatusFromStatusT(status);
208 }
209 
setPhoneState(AudioMode stateAidl,int32_t uidAidl)210 Status AudioPolicyService::setPhoneState(AudioMode stateAidl, int32_t uidAidl)
211 {
212     audio_mode_t state = VALUE_OR_RETURN_BINDER_STATUS(
213             aidl2legacy_AudioMode_audio_mode_t(stateAidl));
214     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
215     if (mAudioPolicyManager == NULL) {
216         return binderStatusFromStatusT(NO_INIT);
217     }
218     if (!settingsAllowed()) {
219         return binderStatusFromStatusT(PERMISSION_DENIED);
220     }
221     if (uint32_t(state) >= AUDIO_MODE_CNT) {
222         return binderStatusFromStatusT(BAD_VALUE);
223     }
224 
225     ALOGV("setPhoneState()");
226 
227     // acquire lock before calling setMode() so that setMode() + setPhoneState() are an atomic
228     // operation from policy manager standpoint (no other operation (e.g track start or stop)
229     // can be interleaved).
230     audio_utils::lock_guard _l(mMutex);
231     // TODO: check if it is more appropriate to do it in platform specific policy manager
232 
233     // Audio HAL mode conversion for call redirect modes
234     audio_mode_t halMode = state;
235     if (state == AUDIO_MODE_CALL_REDIRECT) {
236         halMode = AUDIO_MODE_CALL_SCREEN;
237     } else if (state == AUDIO_MODE_COMMUNICATION_REDIRECT) {
238         halMode = AUDIO_MODE_NORMAL;
239     }
240     AudioSystem::setMode(halMode);
241 
242     AutoCallerClear acc;
243     mAudioPolicyManager->setPhoneState(state);
244     mPhoneState = state;
245     mPhoneStateOwnerUid = uid;
246     updateUidStates_l();
247     return Status::ok();
248 }
249 
getPhoneState(AudioMode * _aidl_return)250 Status AudioPolicyService::getPhoneState(AudioMode* _aidl_return) {
251     audio_utils::lock_guard _l(mMutex);
252     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_mode_t_AudioMode(mPhoneState));
253     return Status::ok();
254 }
255 
setForceUse(media::AudioPolicyForceUse usageAidl,media::AudioPolicyForcedConfig configAidl)256 Status AudioPolicyService::setForceUse(media::AudioPolicyForceUse usageAidl,
257                                        media::AudioPolicyForcedConfig configAidl)
258 {
259     audio_policy_force_use_t usage = VALUE_OR_RETURN_BINDER_STATUS(
260             aidl2legacy_AudioPolicyForceUse_audio_policy_force_use_t(usageAidl));
261     audio_policy_forced_cfg_t config = VALUE_OR_RETURN_BINDER_STATUS(
262             aidl2legacy_AudioPolicyForcedConfig_audio_policy_forced_cfg_t(configAidl));
263 
264     if (mAudioPolicyManager == NULL) {
265         return binderStatusFromStatusT(NO_INIT);
266     }
267 
268     if (!modifyAudioRoutingAllowed()) {
269         return binderStatusFromStatusT(PERMISSION_DENIED);
270     }
271 
272     if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
273         return binderStatusFromStatusT(BAD_VALUE);
274     }
275     if (config < 0 || config >= AUDIO_POLICY_FORCE_CFG_CNT) {
276         return binderStatusFromStatusT(BAD_VALUE);
277     }
278     ALOGV("setForceUse()");
279     audio_utils::lock_guard _l(mMutex);
280     AutoCallerClear acc;
281     mAudioPolicyManager->setForceUse(usage, config);
282     onCheckSpatializer_l();
283     return Status::ok();
284 }
285 
getForceUse(media::AudioPolicyForceUse usageAidl,media::AudioPolicyForcedConfig * _aidl_return)286 Status AudioPolicyService::getForceUse(media::AudioPolicyForceUse usageAidl,
287                                        media::AudioPolicyForcedConfig* _aidl_return) {
288     audio_policy_force_use_t usage = VALUE_OR_RETURN_BINDER_STATUS(
289             aidl2legacy_AudioPolicyForceUse_audio_policy_force_use_t(usageAidl));
290 
291     if (mAudioPolicyManager == NULL) {
292         return binderStatusFromStatusT(NO_INIT);
293     }
294     if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
295         *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
296             legacy2aidl_audio_policy_forced_cfg_t_AudioPolicyForcedConfig(AUDIO_POLICY_FORCE_NONE));
297         return Status::ok();
298     }
299     AutoCallerClear acc;
300     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
301             legacy2aidl_audio_policy_forced_cfg_t_AudioPolicyForcedConfig(
302                     mAudioPolicyManager->getForceUse(usage)));
303     return Status::ok();
304 }
305 
getOutput(AudioStreamType streamAidl,int32_t * _aidl_return)306 Status AudioPolicyService::getOutput(AudioStreamType streamAidl, int32_t* _aidl_return)
307 {
308     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
309             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
310 
311     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT
312           && stream != AUDIO_STREAM_ASSISTANT && stream != AUDIO_STREAM_CALL_ASSISTANT) {
313         *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
314             legacy2aidl_audio_io_handle_t_int32_t(AUDIO_IO_HANDLE_NONE));
315         return Status::ok();
316     }
317     if (mAudioPolicyManager == NULL) {
318         return binderStatusFromStatusT(NO_INIT);
319     }
320     ALOGV("getOutput()");
321     audio_utils::lock_guard _l(mMutex);
322     AutoCallerClear acc;
323     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
324             legacy2aidl_audio_io_handle_t_int32_t(mAudioPolicyManager->getOutput(stream)));
325     return Status::ok();
326 }
327 
getOutputForAttr(const media::audio::common::AudioAttributes & attrAidl,int32_t sessionAidl,const AttributionSourceState & attributionSource,const AudioConfig & configAidl,int32_t flagsAidl,int32_t selectedDeviceIdAidl,media::GetOutputForAttrResponse * _aidl_return)328 Status AudioPolicyService::getOutputForAttr(const media::audio::common::AudioAttributes& attrAidl,
329                                             int32_t sessionAidl,
330                                             const AttributionSourceState& attributionSource,
331                                             const AudioConfig& configAidl,
332                                             int32_t flagsAidl,
333                                             int32_t selectedDeviceIdAidl,
334                                             media::GetOutputForAttrResponse* _aidl_return)
335 {
336     audio_attributes_t attr = VALUE_OR_RETURN_BINDER_STATUS(
337             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
338     audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS(
339             aidl2legacy_int32_t_audio_session_t(sessionAidl));
340     audio_stream_type_t stream = AUDIO_STREAM_DEFAULT;
341     audio_config_t config = VALUE_OR_RETURN_BINDER_STATUS(
342             aidl2legacy_AudioConfig_audio_config_t(configAidl, false /*isInput*/));
343     audio_output_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS(
344             aidl2legacy_int32_t_audio_output_flags_t_mask(flagsAidl));
345     audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS(
346             aidl2legacy_int32_t_audio_port_handle_t(selectedDeviceIdAidl));
347 
348     audio_io_handle_t output;
349     audio_port_handle_t portId;
350     std::vector<audio_io_handle_t> secondaryOutputs;
351 
352     if (mAudioPolicyManager == NULL) {
353         return binderStatusFromStatusT(NO_INIT);
354     }
355 
356     RETURN_IF_BINDER_ERROR(
357             binderStatusFromStatusT(AudioValidator::validateAudioAttributes(attr, "68953950")));
358     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr, attributionSource)));
359 
360     ALOGV("%s()", __func__);
361     audio_utils::lock_guard _l(mMutex);
362 
363     if (!mPackageManager.allowPlaybackCapture(VALUE_OR_RETURN_BINDER_STATUS(
364         aidl2legacy_int32_t_uid_t(attributionSource.uid)))) {
365         attr.flags = static_cast<audio_flags_mask_t>(attr.flags | AUDIO_FLAG_NO_MEDIA_PROJECTION);
366     }
367     if (((attr.flags & (AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE)) != 0)
368             && !bypassInterruptionPolicyAllowed(attributionSource)) {
369         attr.flags = static_cast<audio_flags_mask_t>(
370                 attr.flags & ~(AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE));
371     }
372 
373     if (attr.content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
374         if (!accessUltrasoundAllowed(attributionSource)) {
375             ALOGE("%s: permission denied: ultrasound not allowed for uid %d pid %d",
376                     __func__, attributionSource.uid, attributionSource.pid);
377             return binderStatusFromStatusT(PERMISSION_DENIED);
378         }
379     }
380 
381     AutoCallerClear acc;
382     AudioPolicyInterface::output_type_t outputType;
383     bool isSpatialized = false;
384     bool isBitPerfect = false;
385     status_t result = mAudioPolicyManager->getOutputForAttr(&attr, &output, session,
386                                                             &stream,
387                                                             attributionSource,
388                                                             &config,
389                                                             &flags, &selectedDeviceId, &portId,
390                                                             &secondaryOutputs,
391                                                             &outputType,
392                                                             &isSpatialized,
393                                                             &isBitPerfect);
394 
395     // FIXME: Introduce a way to check for the the telephony device before opening the output
396     if (result == NO_ERROR) {
397         // enforce permission (if any) required for each type of input
398         switch (outputType) {
399         case AudioPolicyInterface::API_OUTPUT_LEGACY:
400             break;
401         case AudioPolicyInterface::API_OUTPUT_TELEPHONY_TX:
402             if (((attr.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0)
403                 && !callAudioInterceptionAllowed(attributionSource)) {
404                 ALOGE("%s() permission denied: call redirection not allowed for uid %d",
405                     __func__, attributionSource.uid);
406                 result = PERMISSION_DENIED;
407             } else if (!modifyPhoneStateAllowed(attributionSource)) {
408                 ALOGE("%s() permission denied: modify phone state not allowed for uid %d",
409                     __func__, attributionSource.uid);
410                 result = PERMISSION_DENIED;
411             }
412             break;
413         case AudioPolicyInterface::API_OUT_MIX_PLAYBACK:
414             if (!modifyAudioRoutingAllowed(attributionSource)) {
415                 ALOGE("%s() permission denied: modify audio routing not allowed for uid %d",
416                     __func__, attributionSource.uid);
417                 result = PERMISSION_DENIED;
418             }
419             break;
420         case AudioPolicyInterface::API_OUTPUT_INVALID:
421         default:
422             LOG_ALWAYS_FATAL("%s() encountered an invalid output type %d",
423                 __func__, (int)outputType);
424         }
425     }
426 
427     if (result == NO_ERROR) {
428         attr = VALUE_OR_RETURN_BINDER_STATUS(
429                 mUsecaseValidator->verifyAudioAttributes(output, attributionSource, attr));
430 
431         sp<AudioPlaybackClient> client =
432                 new AudioPlaybackClient(attr, output, attributionSource, session,
433                     portId, selectedDeviceId, stream, isSpatialized);
434         mAudioPlaybackClients.add(portId, client);
435 
436         _aidl_return->output = VALUE_OR_RETURN_BINDER_STATUS(
437                 legacy2aidl_audio_io_handle_t_int32_t(output));
438         _aidl_return->stream = VALUE_OR_RETURN_BINDER_STATUS(
439                 legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
440         _aidl_return->selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS(
441                 legacy2aidl_audio_port_handle_t_int32_t(selectedDeviceId));
442         _aidl_return->portId = VALUE_OR_RETURN_BINDER_STATUS(
443                 legacy2aidl_audio_port_handle_t_int32_t(portId));
444         _aidl_return->secondaryOutputs = VALUE_OR_RETURN_BINDER_STATUS(
445                 convertContainer<std::vector<int32_t>>(secondaryOutputs,
446                                                        legacy2aidl_audio_io_handle_t_int32_t));
447         _aidl_return->isSpatialized = isSpatialized;
448         _aidl_return->isBitPerfect = isBitPerfect;
449         _aidl_return->attr = VALUE_OR_RETURN_BINDER_STATUS(
450                 legacy2aidl_audio_attributes_t_AudioAttributes(attr));
451     } else {
452         _aidl_return->configBase.format = VALUE_OR_RETURN_BINDER_STATUS(
453                 legacy2aidl_audio_format_t_AudioFormatDescription(config.format));
454         _aidl_return->configBase.channelMask = VALUE_OR_RETURN_BINDER_STATUS(
455                 legacy2aidl_audio_channel_mask_t_AudioChannelLayout(
456                         config.channel_mask, false /*isInput*/));
457         _aidl_return->configBase.sampleRate = config.sample_rate;
458     }
459     return binderStatusFromStatusT(result);
460 }
461 
getPlaybackClientAndEffects(audio_port_handle_t portId,sp<AudioPlaybackClient> & client,sp<AudioPolicyEffects> & effects,const char * context)462 void AudioPolicyService::getPlaybackClientAndEffects(audio_port_handle_t portId,
463                                                      sp<AudioPlaybackClient>& client,
464                                                      sp<AudioPolicyEffects>& effects,
465                                                      const char *context)
466 {
467     audio_utils::lock_guard _l(mMutex);
468     const ssize_t index = mAudioPlaybackClients.indexOfKey(portId);
469     if (index < 0) {
470         ALOGE("%s AudioTrack client not found for portId %d", context, portId);
471         return;
472     }
473     client = mAudioPlaybackClients.valueAt(index);
474     effects = mAudioPolicyEffects;
475 }
476 
startOutput(int32_t portIdAidl)477 Status AudioPolicyService::startOutput(int32_t portIdAidl)
478 {
479     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
480             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
481     if (mAudioPolicyManager == NULL) {
482         return binderStatusFromStatusT(NO_INIT);
483     }
484     ALOGV("startOutput()");
485     sp<AudioPlaybackClient> client;
486     sp<AudioPolicyEffects> audioPolicyEffects;
487 
488     getPlaybackClientAndEffects(portId, client, audioPolicyEffects, __func__);
489 
490     if (audioPolicyEffects != 0) {
491         // create audio processors according to stream
492         status_t status = audioPolicyEffects->addOutputSessionEffects(client->io, client->stream,
493                                                                       client->session);
494         if (status != NO_ERROR && status != ALREADY_EXISTS) {
495             ALOGW("Failed to add effects on session %d", client->session);
496         }
497     }
498     audio_utils::lock_guard _l(mMutex);
499     AutoCallerClear acc;
500     status_t status = mAudioPolicyManager->startOutput(portId);
501     if (status == NO_ERROR) {
502         //TODO b/257922898: decide if/how we need to handle attributes update when playback starts
503         // or during playback
504         (void)mUsecaseValidator->startClient(client->io, client->portId, client->attributionSource,
505                 client->attributes, nullptr /* callback */);
506         client->active = true;
507         onUpdateActiveSpatializerTracks_l();
508     }
509     return binderStatusFromStatusT(status);
510 }
511 
stopOutput(int32_t portIdAidl)512 Status AudioPolicyService::stopOutput(int32_t portIdAidl)
513 {
514     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
515             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
516     if (mAudioPolicyManager == NULL) {
517         return binderStatusFromStatusT(NO_INIT);
518     }
519     ALOGV("stopOutput()");
520     mOutputCommandThread->stopOutputCommand(portId);
521     return Status::ok();
522 }
523 
doStopOutput(audio_port_handle_t portId)524 status_t  AudioPolicyService::doStopOutput(audio_port_handle_t portId)
525 {
526     ALOGV("doStopOutput");
527     sp<AudioPlaybackClient> client;
528     sp<AudioPolicyEffects>audioPolicyEffects;
529 
530     getPlaybackClientAndEffects(portId, client, audioPolicyEffects, __func__);
531 
532     if (audioPolicyEffects != 0) {
533         // release audio processors from the stream
534         status_t status = audioPolicyEffects->releaseOutputSessionEffects(
535             client->io, client->stream, client->session);
536         if (status != NO_ERROR && status != ALREADY_EXISTS) {
537             ALOGW("Failed to release effects on session %d", client->session);
538         }
539     }
540     audio_utils::lock_guard _l(mMutex);
541     AutoCallerClear acc;
542     status_t status = mAudioPolicyManager->stopOutput(portId);
543     if (status == NO_ERROR) {
544         client->active = false;
545         onUpdateActiveSpatializerTracks_l();
546         mUsecaseValidator->stopClient(client->io, client->portId);
547     }
548     return status;
549 }
550 
releaseOutput(int32_t portIdAidl)551 Status AudioPolicyService::releaseOutput(int32_t portIdAidl)
552 {
553     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
554             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
555     if (mAudioPolicyManager == NULL) {
556         return binderStatusFromStatusT(NO_INIT);
557     }
558     ALOGV("releaseOutput()");
559     mOutputCommandThread->releaseOutputCommand(portId);
560     return Status::ok();
561 }
562 
doReleaseOutput(audio_port_handle_t portId)563 void AudioPolicyService::doReleaseOutput(audio_port_handle_t portId)
564 {
565     ALOGV("doReleaseOutput from tid %d", gettid());
566     sp<AudioPlaybackClient> client;
567     sp<AudioPolicyEffects> audioPolicyEffects;
568 
569     getPlaybackClientAndEffects(portId, client, audioPolicyEffects, __func__);
570 
571     if (audioPolicyEffects != 0 && client->active) {
572         // clean up effects if output was not stopped before being released
573         audioPolicyEffects->releaseOutputSessionEffects(
574             client->io, client->stream, client->session);
575     }
576     audio_utils::lock_guard _l(mMutex);
577     if (client != nullptr && client->active) {
578         onUpdateActiveSpatializerTracks_l();
579     }
580     mAudioPlaybackClients.removeItem(portId);
581     // called from internal thread: no need to clear caller identity
582     mAudioPolicyManager->releaseOutput(portId);
583 }
584 
getInputForAttr(const media::audio::common::AudioAttributes & attrAidl,int32_t inputAidl,int32_t riidAidl,int32_t sessionAidl,const AttributionSourceState & attributionSource,const AudioConfigBase & configAidl,int32_t flagsAidl,int32_t selectedDeviceIdAidl,media::GetInputForAttrResponse * _aidl_return)585 Status AudioPolicyService::getInputForAttr(const media::audio::common::AudioAttributes& attrAidl,
586                                            int32_t inputAidl,
587                                            int32_t riidAidl,
588                                            int32_t sessionAidl,
589                                            const AttributionSourceState& attributionSource,
590                                            const AudioConfigBase& configAidl,
591                                            int32_t flagsAidl,
592                                            int32_t selectedDeviceIdAidl,
593                                            media::GetInputForAttrResponse* _aidl_return) {
594     audio_attributes_t attr = VALUE_OR_RETURN_BINDER_STATUS(
595             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
596     audio_io_handle_t input = VALUE_OR_RETURN_BINDER_STATUS(
597             aidl2legacy_int32_t_audio_io_handle_t(inputAidl));
598     audio_unique_id_t riid = VALUE_OR_RETURN_BINDER_STATUS(
599             aidl2legacy_int32_t_audio_unique_id_t(riidAidl));
600     audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS(
601             aidl2legacy_int32_t_audio_session_t(sessionAidl));
602     audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS(
603             aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, true /*isInput*/));
604     audio_input_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS(
605             aidl2legacy_int32_t_audio_input_flags_t_mask(flagsAidl));
606     audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS(
607                 aidl2legacy_int32_t_audio_port_handle_t(selectedDeviceIdAidl));
608 
609     audio_port_handle_t portId;
610 
611     if (mAudioPolicyManager == NULL) {
612         return binderStatusFromStatusT(NO_INIT);
613     }
614 
615     RETURN_IF_BINDER_ERROR(
616             binderStatusFromStatusT(AudioValidator::validateAudioAttributes(attr, "68953950")));
617 
618     audio_source_t inputSource = attr.source;
619     if (inputSource == AUDIO_SOURCE_DEFAULT) {
620         inputSource = AUDIO_SOURCE_MIC;
621     }
622 
623     // already checked by client, but double-check in case the client wrapper is bypassed
624     if ((inputSource < AUDIO_SOURCE_DEFAULT)
625             || (inputSource >= AUDIO_SOURCE_CNT
626                 && inputSource != AUDIO_SOURCE_HOTWORD
627                 && inputSource != AUDIO_SOURCE_FM_TUNER
628                 && inputSource != AUDIO_SOURCE_ECHO_REFERENCE
629                 && inputSource != AUDIO_SOURCE_ULTRASOUND)) {
630         return binderStatusFromStatusT(BAD_VALUE);
631     }
632 
633     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr,
634             attributionSource)));
635 
636     uint32_t virtualDeviceId = kDefaultVirtualDeviceId;
637 
638     // check calling permissions.
639     // Capturing from the following sources does not require permission RECORD_AUDIO
640     // as the captured audio does not come from a microphone:
641     // - FM_TUNER source is controlled by captureTunerAudioInputAllowed() or
642     // captureAudioOutputAllowed() (deprecated).
643     // - REMOTE_SUBMIX source is controlled by captureAudioOutputAllowed() if the input
644     // type is API_INPUT_MIX_EXT_POLICY_REROUTE and by AudioService if a media projection
645     // is used and input type is API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK
646     // - ECHO_REFERENCE source is controlled by captureAudioOutputAllowed()
647     if (!(recordingAllowed(attributionSource, inputSource)
648             || inputSource == AUDIO_SOURCE_FM_TUNER
649             || inputSource == AUDIO_SOURCE_REMOTE_SUBMIX
650             || inputSource == AUDIO_SOURCE_ECHO_REFERENCE)) {
651         ALOGE("%s permission denied: recording not allowed for %s",
652                 __func__, attributionSource.toString().c_str());
653         return binderStatusFromStatusT(PERMISSION_DENIED);
654     }
655 
656     bool canCaptureOutput = captureAudioOutputAllowed(attributionSource);
657     bool canInterceptCallAudio = callAudioInterceptionAllowed(attributionSource);
658     bool isCallAudioSource = inputSource == AUDIO_SOURCE_VOICE_UPLINK
659              || inputSource == AUDIO_SOURCE_VOICE_DOWNLINK
660              || inputSource == AUDIO_SOURCE_VOICE_CALL;
661 
662     if (isCallAudioSource && !canInterceptCallAudio && !canCaptureOutput) {
663         return binderStatusFromStatusT(PERMISSION_DENIED);
664     }
665     if (inputSource == AUDIO_SOURCE_ECHO_REFERENCE
666             && !canCaptureOutput) {
667         return binderStatusFromStatusT(PERMISSION_DENIED);
668     }
669     if (inputSource == AUDIO_SOURCE_FM_TUNER
670         && !canCaptureOutput
671         && !captureTunerAudioInputAllowed(attributionSource)) {
672         return binderStatusFromStatusT(PERMISSION_DENIED);
673     }
674 
675     bool canCaptureHotword = captureHotwordAllowed(attributionSource);
676     if ((inputSource == AUDIO_SOURCE_HOTWORD) && !canCaptureHotword) {
677         return binderStatusFromStatusT(PERMISSION_DENIED);
678     }
679 
680     if (((flags & (AUDIO_INPUT_FLAG_HW_HOTWORD |
681                         AUDIO_INPUT_FLAG_HOTWORD_TAP |
682                         AUDIO_INPUT_FLAG_HW_LOOKBACK)) != 0)
683             && !canCaptureHotword) {
684         ALOGE("%s: permission denied: hotword mode not allowed"
685               " for uid %d pid %d", __func__, attributionSource.uid, attributionSource.pid);
686         return binderStatusFromStatusT(PERMISSION_DENIED);
687     }
688 
689     if (attr.source == AUDIO_SOURCE_ULTRASOUND) {
690         if (!accessUltrasoundAllowed(attributionSource)) {
691             ALOGE("%s: permission denied: ultrasound not allowed for uid %d pid %d",
692                     __func__, attributionSource.uid, attributionSource.pid);
693             return binderStatusFromStatusT(PERMISSION_DENIED);
694         }
695     }
696 
697     sp<AudioPolicyEffects>audioPolicyEffects;
698     {
699         status_t status;
700         AudioPolicyInterface::input_type_t inputType;
701 
702         audio_utils::lock_guard _l(mMutex);
703         {
704             AutoCallerClear acc;
705             // the audio_in_acoustics_t parameter is ignored by get_input()
706             status = mAudioPolicyManager->getInputForAttr(&attr, &input, riid, session,
707                                                           attributionSource, &config,
708                                                           flags, &selectedDeviceId,
709                                                           &inputType, &portId,
710                                                           &virtualDeviceId);
711 
712         }
713         audioPolicyEffects = mAudioPolicyEffects;
714 
715         if (status == NO_ERROR) {
716             // enforce permission (if any) required for each type of input
717             switch (inputType) {
718             case AudioPolicyInterface::API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK:
719                 // this use case has been validated in audio service with a MediaProjection token,
720                 // and doesn't rely on regular permissions
721             case AudioPolicyInterface::API_INPUT_LEGACY:
722                 break;
723             case AudioPolicyInterface::API_INPUT_TELEPHONY_RX:
724                 if ((attr.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0
725                         && canInterceptCallAudio) {
726                     break;
727                 }
728                 // FIXME: use the same permission as for remote submix for now.
729                 FALLTHROUGH_INTENDED;
730             case AudioPolicyInterface::API_INPUT_MIX_CAPTURE:
731                 if (!canCaptureOutput) {
732                     ALOGE("%s permission denied: capture not allowed", __func__);
733                     status = PERMISSION_DENIED;
734                 }
735                 break;
736             case AudioPolicyInterface::API_INPUT_MIX_EXT_POLICY_REROUTE:
737                 if (!(modifyAudioRoutingAllowed(attributionSource)
738                         || ((attr.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0
739                             && canInterceptCallAudio))) {
740                     ALOGE("%s permission denied for remote submix capture", __func__);
741                     status = PERMISSION_DENIED;
742                 }
743                 break;
744             case AudioPolicyInterface::API_INPUT_INVALID:
745             default:
746                 LOG_ALWAYS_FATAL("%s encountered an invalid input type %d",
747                         __func__, (int)inputType);
748             }
749 
750             if (audiopolicy_flags::record_audio_device_aware_permission()) {
751                 // enforce device-aware RECORD_AUDIO permission
752                 if (virtualDeviceId != kDefaultVirtualDeviceId &&
753                     !recordingAllowed(attributionSource, virtualDeviceId, inputSource)) {
754                     status = PERMISSION_DENIED;
755                 }
756             }
757         }
758 
759         if (status != NO_ERROR) {
760             if (status == PERMISSION_DENIED) {
761                 AutoCallerClear acc;
762                 mAudioPolicyManager->releaseInput(portId);
763             } else {
764                 _aidl_return->config = VALUE_OR_RETURN_BINDER_STATUS(
765                         legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/));
766             }
767             return binderStatusFromStatusT(status);
768         }
769 
770         sp<AudioRecordClient> client = new AudioRecordClient(attr, input, session, portId,
771                                                              selectedDeviceId, attributionSource,
772                                                              virtualDeviceId,
773                                                              canCaptureOutput, canCaptureHotword,
774                                                              mOutputCommandThread);
775         mAudioRecordClients.add(portId, client);
776     }
777 
778     if (audioPolicyEffects != 0) {
779         // create audio pre processors according to input source
780         status_t status = audioPolicyEffects->addInputEffects(input, inputSource, session);
781         if (status != NO_ERROR && status != ALREADY_EXISTS) {
782             ALOGW("Failed to add effects on input %d", input);
783         }
784     }
785 
786     _aidl_return->input = VALUE_OR_RETURN_BINDER_STATUS(
787             legacy2aidl_audio_io_handle_t_int32_t(input));
788     _aidl_return->selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS(
789             legacy2aidl_audio_port_handle_t_int32_t(selectedDeviceId));
790     _aidl_return->portId = VALUE_OR_RETURN_BINDER_STATUS(
791             legacy2aidl_audio_port_handle_t_int32_t(portId));
792     return Status::ok();
793 }
794 
getDeviceTypeStrForPortId(audio_port_handle_t portId)795 std::string AudioPolicyService::getDeviceTypeStrForPortId(audio_port_handle_t portId) {
796     struct audio_port_v7 port = {};
797     port.id = portId;
798     status_t status = mAudioPolicyManager->getAudioPort(&port);
799     if (status == NO_ERROR && port.type == AUDIO_PORT_TYPE_DEVICE) {
800         return toString(port.ext.device.type);
801     }
802     return {};
803 }
804 
startInput(int32_t portIdAidl)805 Status AudioPolicyService::startInput(int32_t portIdAidl)
806 {
807     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
808             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
809 
810     if (mAudioPolicyManager == NULL) {
811         return binderStatusFromStatusT(NO_INIT);
812     }
813     sp<AudioRecordClient> client;
814     {
815         audio_utils::lock_guard _l(mMutex);
816 
817         ssize_t index = mAudioRecordClients.indexOfKey(portId);
818         if (index < 0) {
819             return binderStatusFromStatusT(INVALID_OPERATION);
820         }
821         client = mAudioRecordClients.valueAt(index);
822     }
823 
824     std::stringstream msg;
825     msg << "Audio recording on session " << client->session;
826 
827     // check calling permissions
828     if (!(startRecording(client->attributionSource, client->virtualDeviceId,
829                          String16(msg.str().c_str()), client->attributes.source)
830             || client->attributes.source == AUDIO_SOURCE_FM_TUNER
831             || client->attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX
832             || client->attributes.source == AUDIO_SOURCE_ECHO_REFERENCE)) {
833         ALOGE("%s permission denied: recording not allowed for attribution source %s",
834                 __func__, client->attributionSource.toString().c_str());
835         return binderStatusFromStatusT(PERMISSION_DENIED);
836     }
837 
838     audio_utils::lock_guard _l(mMutex);
839 
840     ALOGW_IF(client->silenced, "startInput on silenced input for port %d, uid %d. Unsilencing.",
841             portIdAidl,
842             client->attributionSource.uid);
843 
844     if (client->active) {
845         ALOGE("Client should never be active before startInput. Uid %d port %d",
846                 client->attributionSource.uid, portId);
847         finishRecording(client->attributionSource, client->virtualDeviceId,
848                         client->attributes.source);
849         return binderStatusFromStatusT(INVALID_OPERATION);
850     }
851 
852     // Force the possibly silenced client to be unsilenced since we just called
853     // startRecording (i.e. we have assumed it is unsilenced).
854     // At this point in time, the client is inactive, so no calls to appops are sent in
855     // setAppState_l.
856     // This ensures existing clients have the same behavior as new clients (starting unsilenced).
857     // TODO(b/282076713)
858     setAppState_l(client, APP_STATE_TOP);
859 
860     client->active = true;
861     client->startTimeNs = systemTime();
862     // This call updates the silenced state, and since we are active, appropriately notifies appops
863     // if we silence the track.
864     updateUidStates_l();
865 
866     status_t status;
867     {
868         AutoCallerClear acc;
869         status = mAudioPolicyManager->startInput(portId);
870 
871     }
872 
873     // including successes gets very verbose
874     // but once we cut over to statsd, log them all.
875     if (status != NO_ERROR) {
876 
877         static constexpr char kAudioPolicy[] = "audiopolicy";
878 
879         static constexpr char kAudioPolicyStatus[] = "android.media.audiopolicy.status";
880         static constexpr char kAudioPolicyRqstSrc[] = "android.media.audiopolicy.rqst.src";
881         static constexpr char kAudioPolicyRqstPkg[] = "android.media.audiopolicy.rqst.pkg";
882         static constexpr char kAudioPolicyRqstSession[] = "android.media.audiopolicy.rqst.session";
883         static constexpr char kAudioPolicyRqstDevice[] =
884                 "android.media.audiopolicy.rqst.device";
885         static constexpr char kAudioPolicyActiveSrc[] = "android.media.audiopolicy.active.src";
886         static constexpr char kAudioPolicyActivePkg[] = "android.media.audiopolicy.active.pkg";
887         static constexpr char kAudioPolicyActiveSession[] =
888                 "android.media.audiopolicy.active.session";
889         static constexpr char kAudioPolicyActiveDevice[] =
890                 "android.media.audiopolicy.active.device";
891 
892         mediametrics::Item *item = mediametrics::Item::create(kAudioPolicy);
893         if (item != NULL) {
894 
895             item->setInt32(kAudioPolicyStatus, status);
896 
897             item->setCString(kAudioPolicyRqstSrc,
898                              toString(client->attributes.source).c_str());
899             item->setInt32(kAudioPolicyRqstSession, client->session);
900             if (client->attributionSource.packageName.has_value() &&
901                 client->attributionSource.packageName.value().size() != 0) {
902                 item->setCString(kAudioPolicyRqstPkg,
903                     client->attributionSource.packageName.value().c_str());
904             } else {
905                 item->setCString(kAudioPolicyRqstPkg,
906                     std::to_string(client->attributionSource.uid).c_str());
907             }
908             item->setCString(
909                     kAudioPolicyRqstDevice, getDeviceTypeStrForPortId(client->deviceId).c_str());
910 
911             int count = mAudioRecordClients.size();
912             for (int i = 0; i < count ; i++) {
913                 if (portId == mAudioRecordClients.keyAt(i)) {
914                     continue;
915                 }
916                 sp<AudioRecordClient> other = mAudioRecordClients.valueAt(i);
917                 if (other->active) {
918                     // keeps the last of the clients marked active
919                     item->setCString(kAudioPolicyActiveSrc,
920                                      toString(other->attributes.source).c_str());
921                     item->setInt32(kAudioPolicyActiveSession, other->session);
922                     if (other->attributionSource.packageName.has_value() &&
923                         other->attributionSource.packageName.value().size() != 0) {
924                         item->setCString(kAudioPolicyActivePkg,
925                             other->attributionSource.packageName.value().c_str());
926                     } else {
927                         item->setCString(kAudioPolicyRqstPkg, std::to_string(
928                             other->attributionSource.uid).c_str());
929                     }
930                     item->setCString(kAudioPolicyActiveDevice,
931                                      getDeviceTypeStrForPortId(other->deviceId).c_str());
932                 }
933             }
934             item->selfrecord();
935             delete item;
936             item = NULL;
937         }
938     }
939 
940     if (status != NO_ERROR) {
941         client->active = false;
942         client->startTimeNs = 0;
943         updateUidStates_l();
944         finishRecording(client->attributionSource, client->virtualDeviceId,
945                         client->attributes.source);
946     }
947 
948     return binderStatusFromStatusT(status);
949 }
950 
stopInput(int32_t portIdAidl)951 Status AudioPolicyService::stopInput(int32_t portIdAidl)
952 {
953     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
954             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
955 
956     if (mAudioPolicyManager == NULL) {
957         return binderStatusFromStatusT(NO_INIT);
958     }
959 
960     audio_utils::lock_guard _l(mMutex);
961 
962     ssize_t index = mAudioRecordClients.indexOfKey(portId);
963     if (index < 0) {
964         return binderStatusFromStatusT(INVALID_OPERATION);
965     }
966     sp<AudioRecordClient> client = mAudioRecordClients.valueAt(index);
967 
968     client->active = false;
969     client->startTimeNs = 0;
970 
971     updateUidStates_l();
972 
973     // finish the recording app op
974     finishRecording(client->attributionSource, client->virtualDeviceId, client->attributes.source);
975     AutoCallerClear acc;
976     return binderStatusFromStatusT(mAudioPolicyManager->stopInput(portId));
977 }
978 
releaseInput(int32_t portIdAidl)979 Status AudioPolicyService::releaseInput(int32_t portIdAidl)
980 {
981     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
982             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
983 
984     if (mAudioPolicyManager == NULL) {
985         return binderStatusFromStatusT(NO_INIT);
986     }
987     sp<AudioPolicyEffects>audioPolicyEffects;
988     sp<AudioRecordClient> client;
989     {
990         audio_utils::lock_guard _l(mMutex);
991         audioPolicyEffects = mAudioPolicyEffects;
992         ssize_t index = mAudioRecordClients.indexOfKey(portId);
993         if (index < 0) {
994             return Status::ok();
995         }
996         client = mAudioRecordClients.valueAt(index);
997 
998         if (client->active) {
999             ALOGW("%s releasing active client portId %d", __FUNCTION__, portId);
1000             client->active = false;
1001             client->startTimeNs = 0;
1002             updateUidStates_l();
1003         }
1004 
1005         mAudioRecordClients.removeItem(portId);
1006     }
1007     if (client == 0) {
1008         return Status::ok();
1009     }
1010     if (audioPolicyEffects != 0) {
1011         // release audio processors from the input
1012         status_t status = audioPolicyEffects->releaseInputEffects(client->io, client->session);
1013         if(status != NO_ERROR) {
1014             ALOGW("Failed to release effects on input %d", client->io);
1015         }
1016     }
1017     {
1018         audio_utils::lock_guard _l(mMutex);
1019         AutoCallerClear acc;
1020         mAudioPolicyManager->releaseInput(portId);
1021     }
1022     return Status::ok();
1023 }
1024 
setDeviceAbsoluteVolumeEnabled(const AudioDevice & deviceAidl,bool enabled,AudioStreamType streamToDriveAbsAidl)1025 Status AudioPolicyService::setDeviceAbsoluteVolumeEnabled(const AudioDevice& deviceAidl,
1026                                                           bool enabled,
1027                                                           AudioStreamType streamToDriveAbsAidl) {
1028     audio_stream_type_t streamToDriveAbs = VALUE_OR_RETURN_BINDER_STATUS(
1029             aidl2legacy_AudioStreamType_audio_stream_type_t(streamToDriveAbsAidl));
1030     audio_devices_t deviceType;
1031     std::string address;
1032     RETURN_BINDER_STATUS_IF_ERROR(
1033             aidl2legacy_AudioDevice_audio_device(deviceAidl, &deviceType, &address));
1034 
1035     if (mAudioPolicyManager == nullptr) {
1036         return binderStatusFromStatusT(NO_INIT);
1037     }
1038     if (!settingsAllowed()) {
1039         return binderStatusFromStatusT(PERMISSION_DENIED);
1040     }
1041     if (uint32_t(streamToDriveAbs) >= AUDIO_STREAM_PUBLIC_CNT) {
1042         return binderStatusFromStatusT(BAD_VALUE);
1043     }
1044     audio_utils::lock_guard _l(mMutex);
1045     AutoCallerClear acc;
1046     return binderStatusFromStatusT(
1047             mAudioPolicyManager->setDeviceAbsoluteVolumeEnabled(deviceType, address.c_str(),
1048                                                                 enabled, streamToDriveAbs));
1049 }
1050 
initStreamVolume(AudioStreamType streamAidl,int32_t indexMinAidl,int32_t indexMaxAidl)1051 Status AudioPolicyService::initStreamVolume(AudioStreamType streamAidl,
1052                                             int32_t indexMinAidl,
1053                                             int32_t indexMaxAidl) {
1054     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1055             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1056     int indexMin = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int>(indexMinAidl));
1057     int indexMax = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int>(indexMaxAidl));
1058 
1059     if (mAudioPolicyManager == NULL) {
1060         return binderStatusFromStatusT(NO_INIT);
1061     }
1062     if (!settingsAllowed()) {
1063         return binderStatusFromStatusT(PERMISSION_DENIED);
1064     }
1065     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
1066         return binderStatusFromStatusT(BAD_VALUE);
1067     }
1068     audio_utils::lock_guard _l(mMutex);
1069     AutoCallerClear acc;
1070     mAudioPolicyManager->initStreamVolume(stream, indexMin, indexMax);
1071     return binderStatusFromStatusT(NO_ERROR);
1072 }
1073 
setStreamVolumeIndex(AudioStreamType streamAidl,const AudioDeviceDescription & deviceAidl,int32_t indexAidl)1074 Status AudioPolicyService::setStreamVolumeIndex(AudioStreamType streamAidl,
1075                                                 const AudioDeviceDescription& deviceAidl,
1076                                                 int32_t indexAidl) {
1077     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1078             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1079     int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int>(indexAidl));
1080     audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
1081             aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
1082 
1083     if (mAudioPolicyManager == NULL) {
1084         return binderStatusFromStatusT(NO_INIT);
1085     }
1086     if (!settingsAllowed()) {
1087         return binderStatusFromStatusT(PERMISSION_DENIED);
1088     }
1089     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
1090         return binderStatusFromStatusT(BAD_VALUE);
1091     }
1092     audio_utils::lock_guard _l(mMutex);
1093     AutoCallerClear acc;
1094     return binderStatusFromStatusT(mAudioPolicyManager->setStreamVolumeIndex(stream,
1095                                                                              index,
1096                                                                              device));
1097 }
1098 
getStreamVolumeIndex(AudioStreamType streamAidl,const AudioDeviceDescription & deviceAidl,int32_t * _aidl_return)1099 Status AudioPolicyService::getStreamVolumeIndex(AudioStreamType streamAidl,
1100                                                 const AudioDeviceDescription& deviceAidl,
1101                                                 int32_t* _aidl_return) {
1102     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1103             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1104     audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
1105             aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
1106     int index;
1107 
1108     if (mAudioPolicyManager == NULL) {
1109         return binderStatusFromStatusT(NO_INIT);
1110     }
1111     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
1112         return binderStatusFromStatusT(BAD_VALUE);
1113     }
1114     audio_utils::lock_guard _l(mMutex);
1115     AutoCallerClear acc;
1116     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1117             mAudioPolicyManager->getStreamVolumeIndex(stream, &index, device)));
1118     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(index));
1119     return Status::ok();
1120 }
1121 
setVolumeIndexForAttributes(const media::audio::common::AudioAttributes & attrAidl,const AudioDeviceDescription & deviceAidl,int32_t indexAidl)1122 Status AudioPolicyService::setVolumeIndexForAttributes(
1123         const media::audio::common::AudioAttributes& attrAidl,
1124         const AudioDeviceDescription& deviceAidl, int32_t indexAidl) {
1125     audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS(
1126             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
1127     int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int>(indexAidl));
1128     audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
1129             aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
1130     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1131             AudioValidator::validateAudioAttributes(attributes, "169572641")));
1132 
1133     if (mAudioPolicyManager == NULL) {
1134         return binderStatusFromStatusT(NO_INIT);
1135     }
1136     if (!settingsAllowed()) {
1137         return binderStatusFromStatusT(PERMISSION_DENIED);
1138     }
1139     audio_utils::lock_guard _l(mMutex);
1140     AutoCallerClear acc;
1141     return binderStatusFromStatusT(
1142             mAudioPolicyManager->setVolumeIndexForAttributes(attributes, index, device));
1143 }
1144 
getVolumeIndexForAttributes(const media::audio::common::AudioAttributes & attrAidl,const AudioDeviceDescription & deviceAidl,int32_t * _aidl_return)1145 Status AudioPolicyService::getVolumeIndexForAttributes(
1146         const media::audio::common::AudioAttributes& attrAidl,
1147         const AudioDeviceDescription& deviceAidl, int32_t* _aidl_return) {
1148     audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS(
1149             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
1150     audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
1151             aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
1152     int index;
1153     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1154             AudioValidator::validateAudioAttributes(attributes, "169572641")));
1155 
1156     if (mAudioPolicyManager == NULL) {
1157         return binderStatusFromStatusT(NO_INIT);
1158     }
1159     audio_utils::lock_guard _l(mMutex);
1160     AutoCallerClear acc;
1161     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1162             mAudioPolicyManager->getVolumeIndexForAttributes(attributes, index, device)));
1163     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(index));
1164     return Status::ok();
1165 }
1166 
getMinVolumeIndexForAttributes(const media::audio::common::AudioAttributes & attrAidl,int32_t * _aidl_return)1167 Status AudioPolicyService::getMinVolumeIndexForAttributes(
1168         const media::audio::common::AudioAttributes& attrAidl, int32_t* _aidl_return) {
1169     audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS(
1170             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
1171     int index;
1172     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1173             AudioValidator::validateAudioAttributes(attributes, "169572641")));
1174 
1175     if (mAudioPolicyManager == NULL) {
1176         return binderStatusFromStatusT(NO_INIT);
1177     }
1178     audio_utils::lock_guard _l(mMutex);
1179     AutoCallerClear acc;
1180     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1181             mAudioPolicyManager->getMinVolumeIndexForAttributes(attributes, index)));
1182     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(index));
1183     return Status::ok();
1184 }
1185 
getMaxVolumeIndexForAttributes(const media::audio::common::AudioAttributes & attrAidl,int32_t * _aidl_return)1186 Status AudioPolicyService::getMaxVolumeIndexForAttributes(
1187         const media::audio::common::AudioAttributes& attrAidl, int32_t* _aidl_return) {
1188     audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS(
1189             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
1190     int index;
1191     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1192             AudioValidator::validateAudioAttributes(attributes, "169572641")));
1193 
1194     if (mAudioPolicyManager == NULL) {
1195         return binderStatusFromStatusT(NO_INIT);
1196     }
1197     audio_utils::lock_guard _l(mMutex);
1198     AutoCallerClear acc;
1199     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1200             mAudioPolicyManager->getMaxVolumeIndexForAttributes(attributes, index)));
1201     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(index));
1202     return Status::ok();
1203 }
1204 
getStrategyForStream(AudioStreamType streamAidl,int32_t * _aidl_return)1205 Status AudioPolicyService::getStrategyForStream(AudioStreamType streamAidl,
1206                                                 int32_t* _aidl_return) {
1207     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1208             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1209 
1210     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
1211         *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
1212                 convertReinterpret<int32_t>(PRODUCT_STRATEGY_NONE));
1213         return Status::ok();
1214     }
1215     if (mAudioPolicyManager == NULL) {
1216         return binderStatusFromStatusT(NO_INIT);
1217     }
1218 
1219     // DO NOT LOCK, may be called from AudioFlinger with lock held, reaching deadlock
1220     AutoCallerClear acc;
1221     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
1222             legacy2aidl_product_strategy_t_int32_t(
1223                     mAudioPolicyManager->getStrategyForStream(stream)));
1224     return Status::ok();
1225 }
1226 
getDevicesForAttributes(const media::audio::common::AudioAttributes & attrAidl,bool forVolume,std::vector<AudioDevice> * _aidl_return)1227 Status AudioPolicyService::getDevicesForAttributes(
1228         const media::audio::common::AudioAttributes& attrAidl,
1229         bool forVolume,
1230         std::vector<AudioDevice>* _aidl_return)
1231 {
1232     audio_attributes_t aa = VALUE_OR_RETURN_BINDER_STATUS(
1233             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
1234     AudioDeviceTypeAddrVector devices;
1235 
1236     if (mAudioPolicyManager == NULL) {
1237         return binderStatusFromStatusT(NO_INIT);
1238     }
1239     audio_utils::lock_guard _l(mMutex);
1240     AutoCallerClear acc;
1241     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1242             mAudioPolicyManager->getDevicesForAttributes(aa, &devices, forVolume)));
1243     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
1244             convertContainer<std::vector<AudioDevice>>(devices,
1245                                                        legacy2aidl_AudioDeviceTypeAddress));
1246     return Status::ok();
1247 }
1248 
getOutputForEffect(const media::EffectDescriptor & descAidl,int32_t * _aidl_return)1249 Status AudioPolicyService::getOutputForEffect(const media::EffectDescriptor& descAidl,
1250                                               int32_t* _aidl_return) {
1251     effect_descriptor_t desc = VALUE_OR_RETURN_BINDER_STATUS(
1252             aidl2legacy_EffectDescriptor_effect_descriptor_t(descAidl));
1253     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1254             AudioValidator::validateEffectDescriptor(desc, "73126106")));
1255 
1256     if (mAudioPolicyManager == NULL) {
1257         return binderStatusFromStatusT(NO_INIT);
1258     }
1259     audio_utils::lock_guard _l(mMutex);
1260     AutoCallerClear acc;
1261     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
1262             legacy2aidl_audio_io_handle_t_int32_t(mAudioPolicyManager->getOutputForEffect(&desc)));
1263     return Status::ok();
1264 }
1265 
registerEffect(const media::EffectDescriptor & descAidl,int32_t ioAidl,int32_t strategyAidl,int32_t sessionAidl,int32_t idAidl)1266 Status AudioPolicyService::registerEffect(const media::EffectDescriptor& descAidl, int32_t ioAidl,
1267                                           int32_t strategyAidl, int32_t sessionAidl,
1268                                           int32_t idAidl) {
1269     effect_descriptor_t desc = VALUE_OR_RETURN_BINDER_STATUS(
1270             aidl2legacy_EffectDescriptor_effect_descriptor_t(descAidl));
1271     audio_io_handle_t io = VALUE_OR_RETURN_BINDER_STATUS(
1272             aidl2legacy_int32_t_audio_io_handle_t(ioAidl));
1273     product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS(
1274             aidl2legacy_int32_t_product_strategy_t(strategyAidl));
1275     audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS(
1276             aidl2legacy_int32_t_audio_session_t(sessionAidl));
1277     int id = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(idAidl));
1278     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1279             AudioValidator::validateEffectDescriptor(desc, "73126106")));
1280 
1281     if (mAudioPolicyManager == NULL) {
1282         return binderStatusFromStatusT(NO_INIT);
1283     }
1284     audio_utils::lock_guard _l(mMutex);
1285     AutoCallerClear acc;
1286     return binderStatusFromStatusT(
1287             mAudioPolicyManager->registerEffect(&desc, io, strategy, session, id));
1288 }
1289 
unregisterEffect(int32_t idAidl)1290 Status AudioPolicyService::unregisterEffect(int32_t idAidl)
1291 {
1292     int id = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(idAidl));
1293     if (mAudioPolicyManager == NULL) {
1294         return binderStatusFromStatusT(NO_INIT);
1295     }
1296     audio_utils::lock_guard _l(mMutex);
1297     AutoCallerClear acc;
1298     return binderStatusFromStatusT(mAudioPolicyManager->unregisterEffect(id));
1299 }
1300 
setEffectEnabled(int32_t idAidl,bool enabled)1301 Status AudioPolicyService::setEffectEnabled(int32_t idAidl, bool enabled)
1302 {
1303     int id = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(idAidl));
1304     if (mAudioPolicyManager == NULL) {
1305         return binderStatusFromStatusT(NO_INIT);
1306     }
1307     audio_utils::lock_guard _l(mMutex);
1308     AutoCallerClear acc;
1309     return binderStatusFromStatusT(mAudioPolicyManager->setEffectEnabled(id, enabled));
1310 }
1311 
moveEffectsToIo(const std::vector<int32_t> & idsAidl,int32_t ioAidl)1312 Status AudioPolicyService::moveEffectsToIo(const std::vector<int32_t>& idsAidl, int32_t ioAidl)
1313 
1314 {
1315     const std::vector<int>& ids = VALUE_OR_RETURN_BINDER_STATUS(
1316             convertContainer<std::vector<int>>(idsAidl, convertReinterpret<int, int32_t>));
1317     audio_io_handle_t io = VALUE_OR_RETURN_BINDER_STATUS(
1318             aidl2legacy_int32_t_audio_io_handle_t(ioAidl));
1319     if (ids.size() > MAX_ITEMS_PER_LIST) {
1320         return binderStatusFromStatusT(BAD_VALUE);
1321     }
1322 
1323     if (mAudioPolicyManager == NULL) {
1324         return binderStatusFromStatusT(NO_INIT);
1325     }
1326     audio_utils::lock_guard _l(mMutex);
1327     AutoCallerClear acc;
1328     return binderStatusFromStatusT(mAudioPolicyManager->moveEffectsToIo(ids, io));
1329 }
1330 
isStreamActive(AudioStreamType streamAidl,int32_t inPastMsAidl,bool * _aidl_return)1331 Status AudioPolicyService::isStreamActive(AudioStreamType streamAidl, int32_t inPastMsAidl,
1332                                           bool* _aidl_return) {
1333     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1334             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1335     uint32_t inPastMs = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<uint32_t>(inPastMsAidl));
1336 
1337     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
1338         *_aidl_return = false;
1339         return Status::ok();
1340     }
1341     if (mAudioPolicyManager == NULL) {
1342         return binderStatusFromStatusT(NO_INIT);
1343     }
1344     audio_utils::lock_guard _l(mMutex);
1345     AutoCallerClear acc;
1346     *_aidl_return = mAudioPolicyManager->isStreamActive(stream, inPastMs);
1347     return Status::ok();
1348 }
1349 
isStreamActiveRemotely(AudioStreamType streamAidl,int32_t inPastMsAidl,bool * _aidl_return)1350 Status AudioPolicyService::isStreamActiveRemotely(AudioStreamType streamAidl,
1351                                                   int32_t inPastMsAidl,
1352                                                   bool* _aidl_return) {
1353     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1354             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1355     uint32_t inPastMs = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<uint32_t>(inPastMsAidl));
1356 
1357     if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) {
1358         *_aidl_return = false;
1359         return Status::ok();
1360     }
1361     if (mAudioPolicyManager == NULL) {
1362         return binderStatusFromStatusT(NO_INIT);
1363     }
1364     audio_utils::lock_guard _l(mMutex);
1365     AutoCallerClear acc;
1366     *_aidl_return = mAudioPolicyManager->isStreamActiveRemotely(stream, inPastMs);
1367     return Status::ok();
1368 }
1369 
isSourceActive(AudioSource sourceAidl,bool * _aidl_return)1370 Status AudioPolicyService::isSourceActive(AudioSource sourceAidl, bool* _aidl_return) {
1371     audio_source_t source = VALUE_OR_RETURN_BINDER_STATUS(
1372             aidl2legacy_AudioSource_audio_source_t(sourceAidl));
1373     if (mAudioPolicyManager == NULL) {
1374         return binderStatusFromStatusT(NO_INIT);
1375     }
1376     audio_utils::lock_guard _l(mMutex);
1377     AutoCallerClear acc;
1378     *_aidl_return = mAudioPolicyManager->isSourceActive(source);
1379     return Status::ok();
1380 }
1381 
getAudioPolicyEffects(sp<AudioPolicyEffects> & audioPolicyEffects)1382 status_t AudioPolicyService::getAudioPolicyEffects(sp<AudioPolicyEffects>& audioPolicyEffects)
1383 {
1384     if (mAudioPolicyManager == NULL) {
1385         return NO_INIT;
1386     }
1387     {
1388         audio_utils::lock_guard _l(mMutex);
1389         audioPolicyEffects = mAudioPolicyEffects;
1390     }
1391     if (audioPolicyEffects == 0) {
1392         return NO_INIT;
1393     }
1394 
1395     return OK;
1396 }
1397 
queryDefaultPreProcessing(int32_t audioSessionAidl,Int * countAidl,std::vector<media::EffectDescriptor> * _aidl_return)1398 Status AudioPolicyService::queryDefaultPreProcessing(
1399         int32_t audioSessionAidl,
1400         Int* countAidl,
1401         std::vector<media::EffectDescriptor>* _aidl_return) {
1402     audio_session_t audioSession = VALUE_OR_RETURN_BINDER_STATUS(
1403             aidl2legacy_int32_t_audio_session_t(audioSessionAidl));
1404     uint32_t count = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<uint32_t>(countAidl->value));
1405     if (count > AudioEffect::kMaxPreProcessing) {
1406         count = AudioEffect::kMaxPreProcessing;
1407     }
1408     uint32_t countReq = count;
1409     std::unique_ptr<effect_descriptor_t[]> descriptors(new effect_descriptor_t[count]);
1410 
1411     sp<AudioPolicyEffects> audioPolicyEffects;
1412     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(getAudioPolicyEffects(audioPolicyEffects)));
1413     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(audioPolicyEffects->queryDefaultInputEffects(
1414             (audio_session_t) audioSession, descriptors.get(), &count)));
1415     countReq = std::min(count, countReq);
1416     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1417             convertRange(descriptors.get(), descriptors.get() + countReq,
1418                          std::back_inserter(*_aidl_return),
1419                          legacy2aidl_effect_descriptor_t_EffectDescriptor)));
1420     countAidl->value = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<uint32_t>(count));
1421     return Status::ok();
1422 }
1423 
addSourceDefaultEffect(const AudioUuid & typeAidl,const std::string & opPackageNameAidl,const AudioUuid & uuidAidl,int32_t priority,AudioSource sourceAidl,int32_t * _aidl_return)1424 Status AudioPolicyService::addSourceDefaultEffect(const AudioUuid& typeAidl,
1425                                                   const std::string& opPackageNameAidl,
1426                                                   const AudioUuid& uuidAidl,
1427                                                   int32_t priority,
1428                                                   AudioSource sourceAidl,
1429                                                   int32_t* _aidl_return) {
1430     effect_uuid_t type = VALUE_OR_RETURN_BINDER_STATUS(
1431             aidl2legacy_AudioUuid_audio_uuid_t(typeAidl));
1432     String16 opPackageName = VALUE_OR_RETURN_BINDER_STATUS(
1433             aidl2legacy_string_view_String16(opPackageNameAidl));
1434     effect_uuid_t uuid = VALUE_OR_RETURN_BINDER_STATUS(
1435             aidl2legacy_AudioUuid_audio_uuid_t(uuidAidl));
1436     audio_source_t source = VALUE_OR_RETURN_BINDER_STATUS(
1437             aidl2legacy_AudioSource_audio_source_t(sourceAidl));
1438     audio_unique_id_t id;
1439 
1440     sp<AudioPolicyEffects>audioPolicyEffects;
1441     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(getAudioPolicyEffects(audioPolicyEffects)));
1442     if (!modifyDefaultAudioEffectsAllowed()) {
1443         return binderStatusFromStatusT(PERMISSION_DENIED);
1444     }
1445     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(audioPolicyEffects->addSourceDefaultEffect(
1446             &type, opPackageName, &uuid, priority, source, &id)));
1447     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_unique_id_t_int32_t(id));
1448     return Status::ok();
1449 }
1450 
addStreamDefaultEffect(const AudioUuid & typeAidl,const std::string & opPackageNameAidl,const AudioUuid & uuidAidl,int32_t priority,AudioUsage usageAidl,int32_t * _aidl_return)1451 Status AudioPolicyService::addStreamDefaultEffect(const AudioUuid& typeAidl,
1452                                                   const std::string& opPackageNameAidl,
1453                                                   const AudioUuid& uuidAidl,
1454                                                   int32_t priority, AudioUsage usageAidl,
1455                                                   int32_t* _aidl_return) {
1456     effect_uuid_t type = VALUE_OR_RETURN_BINDER_STATUS(
1457             aidl2legacy_AudioUuid_audio_uuid_t(typeAidl));
1458     String16 opPackageName = VALUE_OR_RETURN_BINDER_STATUS(
1459             aidl2legacy_string_view_String16(opPackageNameAidl));
1460     effect_uuid_t uuid = VALUE_OR_RETURN_BINDER_STATUS(
1461             aidl2legacy_AudioUuid_audio_uuid_t(uuidAidl));
1462     audio_usage_t usage = VALUE_OR_RETURN_BINDER_STATUS(
1463             aidl2legacy_AudioUsage_audio_usage_t(usageAidl));
1464     audio_unique_id_t id;
1465 
1466     sp<AudioPolicyEffects> audioPolicyEffects;
1467     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(getAudioPolicyEffects(audioPolicyEffects)));
1468     if (!modifyDefaultAudioEffectsAllowed()) {
1469         return binderStatusFromStatusT(PERMISSION_DENIED);
1470     }
1471     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(audioPolicyEffects->addStreamDefaultEffect(
1472             &type, opPackageName, &uuid, priority, usage, &id)));
1473     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_unique_id_t_int32_t(id));
1474     return Status::ok();
1475 }
1476 
removeSourceDefaultEffect(int32_t idAidl)1477 Status AudioPolicyService::removeSourceDefaultEffect(int32_t idAidl)
1478 {
1479     audio_unique_id_t id = VALUE_OR_RETURN_BINDER_STATUS(
1480             aidl2legacy_int32_t_audio_unique_id_t(idAidl));
1481     sp<AudioPolicyEffects>audioPolicyEffects;
1482     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(getAudioPolicyEffects(audioPolicyEffects)));
1483     if (!modifyDefaultAudioEffectsAllowed()) {
1484         return binderStatusFromStatusT(PERMISSION_DENIED);
1485     }
1486     return binderStatusFromStatusT(audioPolicyEffects->removeSourceDefaultEffect(id));
1487 }
1488 
removeStreamDefaultEffect(int32_t idAidl)1489 Status AudioPolicyService::removeStreamDefaultEffect(int32_t idAidl)
1490 {
1491     audio_unique_id_t id = VALUE_OR_RETURN_BINDER_STATUS(
1492             aidl2legacy_int32_t_audio_unique_id_t(idAidl));
1493     sp<AudioPolicyEffects>audioPolicyEffects;
1494     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(getAudioPolicyEffects(audioPolicyEffects)));
1495     if (!modifyDefaultAudioEffectsAllowed()) {
1496         return binderStatusFromStatusT(PERMISSION_DENIED);
1497     }
1498     return binderStatusFromStatusT(audioPolicyEffects->removeStreamDefaultEffect(id));
1499 }
1500 
setSupportedSystemUsages(const std::vector<AudioUsage> & systemUsagesAidl)1501 Status AudioPolicyService::setSupportedSystemUsages(
1502         const std::vector<AudioUsage>& systemUsagesAidl) {
1503     size_t size = systemUsagesAidl.size();
1504     if (size > MAX_ITEMS_PER_LIST) {
1505         size = MAX_ITEMS_PER_LIST;
1506     }
1507     std::vector<audio_usage_t> systemUsages;
1508     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1509             convertRange(systemUsagesAidl.begin(), systemUsagesAidl.begin() + size,
1510                          std::back_inserter(systemUsages), aidl2legacy_AudioUsage_audio_usage_t)));
1511 
1512     audio_utils::lock_guard _l(mMutex);
1513     if(!modifyAudioRoutingAllowed()) {
1514         return binderStatusFromStatusT(PERMISSION_DENIED);
1515     }
1516 
1517     bool areAllSystemUsages = std::all_of(begin(systemUsages), end(systemUsages),
1518         [](audio_usage_t usage) { return isSystemUsage(usage); });
1519     if (!areAllSystemUsages) {
1520         return binderStatusFromStatusT(BAD_VALUE);
1521     }
1522 
1523     mSupportedSystemUsages = systemUsages;
1524     return Status::ok();
1525 }
1526 
setAllowedCapturePolicy(int32_t uidAidl,int32_t capturePolicyAidl)1527 Status AudioPolicyService::setAllowedCapturePolicy(int32_t uidAidl, int32_t capturePolicyAidl) {
1528     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
1529     audio_flags_mask_t capturePolicy = VALUE_OR_RETURN_BINDER_STATUS(
1530             aidl2legacy_int32_t_audio_flags_mask_t_mask(capturePolicyAidl));
1531 
1532     audio_utils::lock_guard _l(mMutex);
1533     if (mAudioPolicyManager == NULL) {
1534         ALOGV("%s() mAudioPolicyManager == NULL", __func__);
1535         return binderStatusFromStatusT(NO_INIT);
1536     }
1537     return binderStatusFromStatusT(
1538             mAudioPolicyManager->setAllowedCapturePolicy(uid, capturePolicy));
1539 }
1540 
getOffloadSupport(const AudioOffloadInfo & infoAidl,media::AudioOffloadMode * _aidl_return)1541 Status AudioPolicyService::getOffloadSupport(const AudioOffloadInfo& infoAidl,
1542                                              media::AudioOffloadMode* _aidl_return) {
1543     audio_offload_info_t info = VALUE_OR_RETURN_BINDER_STATUS(
1544             aidl2legacy_AudioOffloadInfo_audio_offload_info_t(infoAidl));
1545     if (mAudioPolicyManager == NULL) {
1546         ALOGV("mAudioPolicyManager == NULL");
1547         return binderStatusFromStatusT(AUDIO_OFFLOAD_NOT_SUPPORTED);
1548     }
1549     audio_utils::lock_guard _l(mMutex);
1550     AutoCallerClear acc;
1551     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_offload_mode_t_AudioOffloadMode(
1552             mAudioPolicyManager->getOffloadSupport(info)));
1553     return Status::ok();
1554 }
1555 
isDirectOutputSupported(const AudioConfigBase & configAidl,const media::audio::common::AudioAttributes & attributesAidl,bool * _aidl_return)1556 Status AudioPolicyService::isDirectOutputSupported(
1557         const AudioConfigBase& configAidl,
1558         const media::audio::common::AudioAttributes& attributesAidl,
1559         bool* _aidl_return) {
1560     audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS(
1561             aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, false /*isInput*/));
1562     audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS(
1563             aidl2legacy_AudioAttributes_audio_attributes_t(attributesAidl));
1564     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1565             AudioValidator::validateAudioAttributes(attributes, "169572641")));
1566 
1567     if (mAudioPolicyManager == NULL) {
1568         ALOGV("mAudioPolicyManager == NULL");
1569         return binderStatusFromStatusT(NO_INIT);
1570     }
1571 
1572     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attributes)));
1573 
1574     audio_utils::lock_guard _l(mMutex);
1575     *_aidl_return = mAudioPolicyManager->isDirectOutputSupported(config, attributes);
1576     return Status::ok();
1577 }
1578 
1579 
listAudioPorts(media::AudioPortRole roleAidl,media::AudioPortType typeAidl,Int * count,std::vector<media::AudioPortFw> * portsAidl,int32_t * _aidl_return)1580 Status AudioPolicyService::listAudioPorts(media::AudioPortRole roleAidl,
1581                                           media::AudioPortType typeAidl, Int* count,
1582                                           std::vector<media::AudioPortFw>* portsAidl,
1583                                           int32_t* _aidl_return) {
1584     audio_port_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
1585             aidl2legacy_AudioPortRole_audio_port_role_t(roleAidl));
1586     audio_port_type_t type = VALUE_OR_RETURN_BINDER_STATUS(
1587             aidl2legacy_AudioPortType_audio_port_type_t(typeAidl));
1588     unsigned int num_ports = VALUE_OR_RETURN_BINDER_STATUS(
1589             convertIntegral<unsigned int>(count->value));
1590     if (num_ports > MAX_ITEMS_PER_LIST) {
1591         num_ports = MAX_ITEMS_PER_LIST;
1592     }
1593     unsigned int numPortsReq = num_ports;
1594     std::unique_ptr<audio_port_v7[]> ports(new audio_port_v7[num_ports]);
1595     unsigned int generation;
1596 
1597     audio_utils::lock_guard _l(mMutex);
1598     if (mAudioPolicyManager == NULL) {
1599         return binderStatusFromStatusT(NO_INIT);
1600     }
1601     AutoCallerClear acc;
1602     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1603             mAudioPolicyManager->listAudioPorts(role, type, &num_ports, ports.get(), &generation)));
1604     numPortsReq = std::min(numPortsReq, num_ports);
1605     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1606             convertRange(ports.get(), ports.get() + numPortsReq, std::back_inserter(*portsAidl),
1607                          legacy2aidl_audio_port_v7_AudioPortFw)));
1608     count->value = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(num_ports));
1609     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(generation));
1610     return Status::ok();
1611 }
1612 
listDeclaredDevicePorts(media::AudioPortRole role,std::vector<media::AudioPortFw> * _aidl_return)1613 Status AudioPolicyService::listDeclaredDevicePorts(media::AudioPortRole role,
1614                                                     std::vector<media::AudioPortFw>* _aidl_return) {
1615     audio_utils::lock_guard _l(mMutex);
1616     if (mAudioPolicyManager == NULL) {
1617         return binderStatusFromStatusT(NO_INIT);
1618     }
1619     AutoCallerClear acc;
1620     return binderStatusFromStatusT(mAudioPolicyManager->listDeclaredDevicePorts(
1621                     role, _aidl_return));
1622 }
1623 
getAudioPort(int portId,media::AudioPortFw * _aidl_return)1624 Status AudioPolicyService::getAudioPort(int portId,
1625                                         media::AudioPortFw* _aidl_return) {
1626     audio_port_v7 port{ .id = portId };
1627     audio_utils::lock_guard _l(mMutex);
1628     if (mAudioPolicyManager == NULL) {
1629         return binderStatusFromStatusT(NO_INIT);
1630     }
1631     AutoCallerClear acc;
1632     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(mAudioPolicyManager->getAudioPort(&port)));
1633     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
1634     return Status::ok();
1635 }
1636 
createAudioPatch(const media::AudioPatchFw & patchAidl,int32_t handleAidl,int32_t * _aidl_return)1637 Status AudioPolicyService::createAudioPatch(const media::AudioPatchFw& patchAidl,
1638                                             int32_t handleAidl,
1639                                             int32_t* _aidl_return) {
1640     audio_patch patch = VALUE_OR_RETURN_BINDER_STATUS(
1641             aidl2legacy_AudioPatchFw_audio_patch(patchAidl));
1642     audio_patch_handle_t handle = VALUE_OR_RETURN_BINDER_STATUS(
1643             aidl2legacy_int32_t_audio_port_handle_t(handleAidl));
1644     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(AudioValidator::validateAudioPatch(patch)));
1645 
1646     audio_utils::lock_guard _l(mMutex);
1647     if(!modifyAudioRoutingAllowed()) {
1648         return binderStatusFromStatusT(PERMISSION_DENIED);
1649     }
1650     if (mAudioPolicyManager == NULL) {
1651         return binderStatusFromStatusT(NO_INIT);
1652     }
1653     AutoCallerClear acc;
1654     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1655             mAudioPolicyManager->createAudioPatch(&patch, &handle,
1656                                                   IPCThreadState::self()->getCallingUid())));
1657     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_patch_handle_t_int32_t(handle));
1658     return Status::ok();
1659 }
1660 
releaseAudioPatch(int32_t handleAidl)1661 Status AudioPolicyService::releaseAudioPatch(int32_t handleAidl)
1662 {
1663     audio_patch_handle_t handle = VALUE_OR_RETURN_BINDER_STATUS(
1664             aidl2legacy_int32_t_audio_patch_handle_t(handleAidl));
1665     audio_utils::lock_guard _l(mMutex);
1666     if(!modifyAudioRoutingAllowed()) {
1667         return binderStatusFromStatusT(PERMISSION_DENIED);
1668     }
1669     if (mAudioPolicyManager == NULL) {
1670         return binderStatusFromStatusT(NO_INIT);
1671     }
1672     AutoCallerClear acc;
1673     return binderStatusFromStatusT(
1674             mAudioPolicyManager->releaseAudioPatch(handle,
1675                                                    IPCThreadState::self()->getCallingUid()));
1676 }
1677 
listAudioPatches(Int * count,std::vector<media::AudioPatchFw> * patchesAidl,int32_t * _aidl_return)1678 Status AudioPolicyService::listAudioPatches(Int* count,
1679                                             std::vector<media::AudioPatchFw>* patchesAidl,
1680                                             int32_t* _aidl_return) {
1681     unsigned int num_patches = VALUE_OR_RETURN_BINDER_STATUS(
1682             convertIntegral<unsigned int>(count->value));
1683     if (num_patches > MAX_ITEMS_PER_LIST) {
1684         num_patches = MAX_ITEMS_PER_LIST;
1685     }
1686     unsigned int numPatchesReq = num_patches;
1687     std::unique_ptr<audio_patch[]> patches(new audio_patch[num_patches]);
1688     unsigned int generation;
1689 
1690     audio_utils::lock_guard _l(mMutex);
1691     if (mAudioPolicyManager == NULL) {
1692         return binderStatusFromStatusT(NO_INIT);
1693     }
1694     AutoCallerClear acc;
1695     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1696             mAudioPolicyManager->listAudioPatches(&num_patches, patches.get(), &generation)));
1697     numPatchesReq = std::min(numPatchesReq, num_patches);
1698     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1699             convertRange(patches.get(), patches.get() + numPatchesReq,
1700                          std::back_inserter(*patchesAidl), legacy2aidl_audio_patch_AudioPatchFw)));
1701     count->value = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(num_patches));
1702     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int32_t>(generation));
1703     return Status::ok();
1704 }
1705 
setAudioPortConfig(const media::AudioPortConfigFw & configAidl)1706 Status AudioPolicyService::setAudioPortConfig(const media::AudioPortConfigFw& configAidl)
1707 {
1708     audio_port_config config = VALUE_OR_RETURN_BINDER_STATUS(
1709             aidl2legacy_AudioPortConfigFw_audio_port_config(configAidl));
1710     RETURN_IF_BINDER_ERROR(
1711             binderStatusFromStatusT(AudioValidator::validateAudioPortConfig(config)));
1712 
1713     audio_utils::lock_guard _l(mMutex);
1714     if(!modifyAudioRoutingAllowed()) {
1715         return binderStatusFromStatusT(PERMISSION_DENIED);
1716     }
1717     if (mAudioPolicyManager == NULL) {
1718         return binderStatusFromStatusT(NO_INIT);
1719     }
1720     AutoCallerClear acc;
1721     return binderStatusFromStatusT(mAudioPolicyManager->setAudioPortConfig(&config));
1722 }
1723 
acquireSoundTriggerSession(media::SoundTriggerSession * _aidl_return)1724 Status AudioPolicyService::acquireSoundTriggerSession(media::SoundTriggerSession* _aidl_return)
1725 {
1726     audio_session_t session;
1727     audio_io_handle_t ioHandle;
1728     audio_devices_t device;
1729 
1730     {
1731         audio_utils::lock_guard _l(mMutex);
1732         if (mAudioPolicyManager == NULL) {
1733             return binderStatusFromStatusT(NO_INIT);
1734         }
1735         AutoCallerClear acc;
1736         RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1737                 mAudioPolicyManager->acquireSoundTriggerSession(&session, &ioHandle, &device)));
1738     }
1739 
1740     _aidl_return->session = VALUE_OR_RETURN_BINDER_STATUS(
1741             legacy2aidl_audio_session_t_int32_t(session));
1742     _aidl_return->ioHandle = VALUE_OR_RETURN_BINDER_STATUS(
1743             legacy2aidl_audio_io_handle_t_int32_t(ioHandle));
1744     _aidl_return->device = VALUE_OR_RETURN_BINDER_STATUS(
1745             legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
1746     return Status::ok();
1747 }
1748 
releaseSoundTriggerSession(int32_t sessionAidl)1749 Status AudioPolicyService::releaseSoundTriggerSession(int32_t sessionAidl)
1750 {
1751     audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS(
1752             aidl2legacy_int32_t_audio_session_t(sessionAidl));
1753     audio_utils::lock_guard _l(mMutex);
1754     if (mAudioPolicyManager == NULL) {
1755         return binderStatusFromStatusT(NO_INIT);
1756     }
1757     AutoCallerClear acc;
1758     return binderStatusFromStatusT(mAudioPolicyManager->releaseSoundTriggerSession(session));
1759 }
1760 
registerPolicyMixes(const std::vector<media::AudioMix> & mixesAidl,bool registration)1761 Status AudioPolicyService::registerPolicyMixes(const std::vector<media::AudioMix>& mixesAidl,
1762                                                bool registration) {
1763     size_t size = mixesAidl.size();
1764     if (size > MAX_MIXES_PER_POLICY) {
1765         size = MAX_MIXES_PER_POLICY;
1766     }
1767     Vector<AudioMix> mixes;
1768     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1769             convertRange(mixesAidl.begin(), mixesAidl.begin() + size, std::back_inserter(mixes),
1770                          aidl2legacy_AudioMix)));
1771 
1772     audio_utils::lock_guard _l(mMutex);
1773 
1774     // loopback|render only need a MediaProjection (checked in caller AudioService.java)
1775     bool needModifyAudioRouting = std::any_of(mixes.begin(), mixes.end(), [](auto& mix) {
1776             return !is_mix_loopback_render(mix.mRouteFlags); });
1777     if (needModifyAudioRouting && !modifyAudioRoutingAllowed()) {
1778         return binderStatusFromStatusT(PERMISSION_DENIED);
1779     }
1780 
1781     // If one of the mixes has needCaptureVoiceCommunicationOutput set to true, then we
1782     // need to verify that the caller still has CAPTURE_VOICE_COMMUNICATION_OUTPUT
1783     bool needCaptureVoiceCommunicationOutput =
1784         std::any_of(mixes.begin(), mixes.end(), [](auto& mix) {
1785             return mix.mVoiceCommunicationCaptureAllowed; });
1786 
1787     bool needCaptureMediaOutput = std::any_of(mixes.begin(), mixes.end(), [](auto& mix) {
1788             return mix.mAllowPrivilegedMediaPlaybackCapture; });
1789 
1790     const AttributionSourceState attributionSource = getCallingAttributionSource();
1791 
1792 
1793     if (needCaptureMediaOutput && !captureMediaOutputAllowed(attributionSource)) {
1794         return binderStatusFromStatusT(PERMISSION_DENIED);
1795     }
1796 
1797     if (needCaptureVoiceCommunicationOutput &&
1798         !captureVoiceCommunicationOutputAllowed(attributionSource)) {
1799         return binderStatusFromStatusT(PERMISSION_DENIED);
1800     }
1801 
1802     if (mAudioPolicyManager == NULL) {
1803         return binderStatusFromStatusT(NO_INIT);
1804     }
1805     AutoCallerClear acc;
1806     if (registration) {
1807         return binderStatusFromStatusT(mAudioPolicyManager->registerPolicyMixes(mixes));
1808     } else {
1809         return binderStatusFromStatusT(mAudioPolicyManager->unregisterPolicyMixes(mixes));
1810     }
1811 }
1812 
1813 Status
getRegisteredPolicyMixes(std::vector<::android::media::AudioMix> * mixesAidl)1814 AudioPolicyService::getRegisteredPolicyMixes(std::vector<::android::media::AudioMix>* mixesAidl) {
1815     if (mAudioPolicyManager == nullptr) {
1816         return binderStatusFromStatusT(NO_INIT);
1817     }
1818 
1819     std::vector<AudioMix> mixes;
1820     int status = mAudioPolicyManager->getRegisteredPolicyMixes(mixes);
1821 
1822     for (const auto& mix : mixes) {
1823         media::AudioMix aidlMix = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_AudioMix(mix));
1824         mixesAidl->push_back(aidlMix);
1825     }
1826 
1827     return binderStatusFromStatusT(status);
1828 }
1829 
updatePolicyMixes(const::std::vector<::android::media::AudioMixUpdate> & updates)1830 Status AudioPolicyService::updatePolicyMixes(
1831         const ::std::vector<::android::media::AudioMixUpdate>& updates) {
1832     audio_utils::lock_guard _l(mMutex);
1833     for (const auto& update : updates) {
1834         AudioMix mix = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_AudioMix(update.audioMix));
1835         std::vector<AudioMixMatchCriterion> newCriteria =
1836                 VALUE_OR_RETURN_BINDER_STATUS(convertContainer<std::vector<AudioMixMatchCriterion>>(
1837                         update.newCriteria, aidl2legacy_AudioMixMatchCriterion));
1838         int status;
1839         if((status = mAudioPolicyManager->updatePolicyMix(mix, newCriteria)) != NO_ERROR) {
1840             return binderStatusFromStatusT(status);
1841         }
1842     }
1843     return binderStatusFromStatusT(NO_ERROR);
1844 }
1845 
setUidDeviceAffinities(int32_t uidAidl,const std::vector<AudioDevice> & devicesAidl)1846 Status AudioPolicyService::setUidDeviceAffinities(
1847         int32_t uidAidl,
1848         const std::vector<AudioDevice>& devicesAidl) {
1849     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
1850     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
1851             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
1852                                                         aidl2legacy_AudioDeviceTypeAddress));
1853 
1854     audio_utils::lock_guard _l(mMutex);
1855     if(!modifyAudioRoutingAllowed()) {
1856         return binderStatusFromStatusT(PERMISSION_DENIED);
1857     }
1858     if (mAudioPolicyManager == NULL) {
1859         return binderStatusFromStatusT(NO_INIT);
1860     }
1861     AutoCallerClear acc;
1862     return binderStatusFromStatusT(mAudioPolicyManager->setUidDeviceAffinities(uid, devices));
1863 }
1864 
removeUidDeviceAffinities(int32_t uidAidl)1865 Status AudioPolicyService::removeUidDeviceAffinities(int32_t uidAidl) {
1866     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
1867 
1868     audio_utils::lock_guard _l(mMutex);
1869     if(!modifyAudioRoutingAllowed()) {
1870         return binderStatusFromStatusT(PERMISSION_DENIED);
1871     }
1872     if (mAudioPolicyManager == NULL) {
1873         return binderStatusFromStatusT(NO_INIT);
1874     }
1875     AutoCallerClear acc;
1876     return binderStatusFromStatusT(mAudioPolicyManager->removeUidDeviceAffinities(uid));
1877 }
1878 
setUserIdDeviceAffinities(int32_t userIdAidl,const std::vector<AudioDevice> & devicesAidl)1879 Status AudioPolicyService::setUserIdDeviceAffinities(
1880         int32_t userIdAidl,
1881         const std::vector<AudioDevice>& devicesAidl) {
1882     int userId = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(userIdAidl));
1883     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
1884             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
1885                                                         aidl2legacy_AudioDeviceTypeAddress));
1886 
1887     audio_utils::lock_guard _l(mMutex);
1888     if(!modifyAudioRoutingAllowed()) {
1889         return binderStatusFromStatusT(PERMISSION_DENIED);
1890     }
1891     if (mAudioPolicyManager == NULL) {
1892         return binderStatusFromStatusT(NO_INIT);
1893     }
1894     AutoCallerClear acc;
1895     return binderStatusFromStatusT(mAudioPolicyManager->setUserIdDeviceAffinities(userId, devices));
1896 }
1897 
removeUserIdDeviceAffinities(int32_t userIdAidl)1898 Status AudioPolicyService::removeUserIdDeviceAffinities(int32_t userIdAidl) {
1899     int userId = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(userIdAidl));
1900 
1901     audio_utils::lock_guard _l(mMutex);
1902     if(!modifyAudioRoutingAllowed()) {
1903         return binderStatusFromStatusT(PERMISSION_DENIED);
1904     }
1905     if (mAudioPolicyManager == NULL) {
1906         return binderStatusFromStatusT(NO_INIT);
1907     }
1908     AutoCallerClear acc;
1909     return binderStatusFromStatusT(mAudioPolicyManager->removeUserIdDeviceAffinities(userId));
1910 }
1911 
startAudioSource(const media::AudioPortConfigFw & sourceAidl,const media::audio::common::AudioAttributes & attributesAidl,int32_t * _aidl_return)1912 Status AudioPolicyService::startAudioSource(const media::AudioPortConfigFw& sourceAidl,
1913         const media::audio::common::AudioAttributes& attributesAidl,
1914         int32_t* _aidl_return) {
1915     audio_port_config source = VALUE_OR_RETURN_BINDER_STATUS(
1916             aidl2legacy_AudioPortConfigFw_audio_port_config(sourceAidl));
1917     audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS(
1918             aidl2legacy_AudioAttributes_audio_attributes_t(attributesAidl));
1919     audio_port_handle_t portId;
1920     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1921             AudioValidator::validateAudioPortConfig(source)));
1922     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1923             AudioValidator::validateAudioAttributes(attributes, "68953950")));
1924 
1925     audio_utils::lock_guard _l(mMutex);
1926     if (mAudioPolicyManager == NULL) {
1927         return binderStatusFromStatusT(NO_INIT);
1928     }
1929 
1930     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attributes)));
1931 
1932     // startAudioSource should be created as the calling uid
1933     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1934     AutoCallerClear acc;
1935     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
1936             mAudioPolicyManager->startAudioSource(&source, &attributes, &portId, callingUid)));
1937     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
1938     return Status::ok();
1939 }
1940 
stopAudioSource(int32_t portIdAidl)1941 Status AudioPolicyService::stopAudioSource(int32_t portIdAidl)
1942 {
1943     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
1944             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
1945 
1946     audio_utils::lock_guard _l(mMutex);
1947     if (mAudioPolicyManager == NULL) {
1948         return binderStatusFromStatusT(NO_INIT);
1949     }
1950     AutoCallerClear acc;
1951     return binderStatusFromStatusT(mAudioPolicyManager->stopAudioSource(portId));
1952 }
1953 
setMasterMono(bool mono)1954 Status AudioPolicyService::setMasterMono(bool mono)
1955 {
1956     if (mAudioPolicyManager == NULL) {
1957         return binderStatusFromStatusT(NO_INIT);
1958     }
1959     if (!settingsAllowed()) {
1960         return binderStatusFromStatusT(PERMISSION_DENIED);
1961     }
1962     audio_utils::lock_guard _l(mMutex);
1963     AutoCallerClear acc;
1964     return binderStatusFromStatusT(mAudioPolicyManager->setMasterMono(mono));
1965 }
1966 
getMasterMono(bool * _aidl_return)1967 Status AudioPolicyService::getMasterMono(bool* _aidl_return)
1968 {
1969     if (mAudioPolicyManager == NULL) {
1970         return binderStatusFromStatusT(NO_INIT);
1971     }
1972     audio_utils::lock_guard _l(mMutex);
1973     AutoCallerClear acc;
1974     return binderStatusFromStatusT(mAudioPolicyManager->getMasterMono(_aidl_return));
1975 }
1976 
1977 
getStreamVolumeDB(AudioStreamType streamAidl,int32_t indexAidl,const AudioDeviceDescription & deviceAidl,float * _aidl_return)1978 Status AudioPolicyService::getStreamVolumeDB(
1979         AudioStreamType streamAidl, int32_t indexAidl,
1980         const AudioDeviceDescription& deviceAidl, float* _aidl_return) {
1981     audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS(
1982             aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl));
1983     int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<int>(indexAidl));
1984     audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
1985             aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
1986 
1987     if (mAudioPolicyManager == NULL) {
1988         return binderStatusFromStatusT(NO_INIT);
1989     }
1990     audio_utils::lock_guard _l(mMutex);
1991     AutoCallerClear acc;
1992     *_aidl_return = mAudioPolicyManager->getStreamVolumeDB(stream, index, device);
1993     return Status::ok();
1994 }
1995 
getSurroundFormats(Int * count,std::vector<AudioFormatDescription> * formats,std::vector<bool> * formatsEnabled)1996 Status AudioPolicyService::getSurroundFormats(Int* count,
1997         std::vector<AudioFormatDescription>* formats,
1998         std::vector<bool>* formatsEnabled) {
1999     unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS(
2000             convertIntegral<unsigned int>(count->value));
2001     if (numSurroundFormats > MAX_ITEMS_PER_LIST) {
2002         numSurroundFormats = MAX_ITEMS_PER_LIST;
2003     }
2004     unsigned int numSurroundFormatsReq = numSurroundFormats;
2005     std::unique_ptr<audio_format_t[]>surroundFormats(new audio_format_t[numSurroundFormats]);
2006     std::unique_ptr<bool[]>surroundFormatsEnabled(new bool[numSurroundFormats]);
2007 
2008     if (mAudioPolicyManager == NULL) {
2009         return binderStatusFromStatusT(NO_INIT);
2010     }
2011     audio_utils::lock_guard _l(mMutex);
2012     AutoCallerClear acc;
2013     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2014             mAudioPolicyManager->getSurroundFormats(&numSurroundFormats, surroundFormats.get(),
2015                                                     surroundFormatsEnabled.get())));
2016     numSurroundFormatsReq = std::min(numSurroundFormats, numSurroundFormatsReq);
2017     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2018             convertRange(surroundFormats.get(), surroundFormats.get() + numSurroundFormatsReq,
2019                          std::back_inserter(*formats),
2020                          legacy2aidl_audio_format_t_AudioFormatDescription)));
2021     formatsEnabled->insert(
2022             formatsEnabled->begin(),
2023             surroundFormatsEnabled.get(),
2024             surroundFormatsEnabled.get() + numSurroundFormatsReq);
2025     count->value = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<uint32_t>(numSurroundFormats));
2026     return Status::ok();
2027 }
2028 
getReportedSurroundFormats(Int * count,std::vector<AudioFormatDescription> * formats)2029 Status AudioPolicyService::getReportedSurroundFormats(
2030         Int* count, std::vector<AudioFormatDescription>* formats) {
2031     unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS(
2032             convertIntegral<unsigned int>(count->value));
2033     if (numSurroundFormats > MAX_ITEMS_PER_LIST) {
2034         numSurroundFormats = MAX_ITEMS_PER_LIST;
2035     }
2036     unsigned int numSurroundFormatsReq = numSurroundFormats;
2037     std::unique_ptr<audio_format_t[]>surroundFormats(new audio_format_t[numSurroundFormats]);
2038 
2039     if (mAudioPolicyManager == NULL) {
2040         return binderStatusFromStatusT(NO_INIT);
2041     }
2042     audio_utils::lock_guard _l(mMutex);
2043     AutoCallerClear acc;
2044     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2045             mAudioPolicyManager->getReportedSurroundFormats(
2046                     &numSurroundFormats, surroundFormats.get())));
2047     numSurroundFormatsReq = std::min(numSurroundFormats, numSurroundFormatsReq);
2048     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2049             convertRange(surroundFormats.get(), surroundFormats.get() + numSurroundFormatsReq,
2050                          std::back_inserter(*formats),
2051                          legacy2aidl_audio_format_t_AudioFormatDescription)));
2052     count->value = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral<uint32_t>(numSurroundFormats));
2053     return Status::ok();
2054 }
2055 
getHwOffloadFormatsSupportedForBluetoothMedia(const AudioDeviceDescription & deviceAidl,std::vector<AudioFormatDescription> * _aidl_return)2056 Status AudioPolicyService::getHwOffloadFormatsSupportedForBluetoothMedia(
2057         const AudioDeviceDescription& deviceAidl,
2058         std::vector<AudioFormatDescription>* _aidl_return) {
2059     std::vector<audio_format_t> formats;
2060 
2061     if (mAudioPolicyManager == NULL) {
2062         return binderStatusFromStatusT(NO_INIT);
2063     }
2064     audio_utils::lock_guard _l(mMutex);
2065     AutoCallerClear acc;
2066     audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS(
2067             aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl));
2068     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2069             mAudioPolicyManager->getHwOffloadFormatsSupportedForBluetoothMedia(device, &formats)));
2070     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2071             convertContainer<std::vector<AudioFormatDescription>>(
2072                     formats,
2073                     legacy2aidl_audio_format_t_AudioFormatDescription));
2074     return Status::ok();
2075 }
2076 
setSurroundFormatEnabled(const AudioFormatDescription & audioFormatAidl,bool enabled)2077 Status AudioPolicyService::setSurroundFormatEnabled(
2078         const AudioFormatDescription& audioFormatAidl, bool enabled) {
2079     audio_format_t audioFormat = VALUE_OR_RETURN_BINDER_STATUS(
2080             aidl2legacy_AudioFormatDescription_audio_format_t(audioFormatAidl));
2081     if (mAudioPolicyManager == NULL) {
2082         return binderStatusFromStatusT(NO_INIT);
2083     }
2084     audio_utils::lock_guard _l(mMutex);
2085     AutoCallerClear acc;
2086     return binderStatusFromStatusT(
2087             mAudioPolicyManager->setSurroundFormatEnabled(audioFormat, enabled));
2088 }
2089 
convertInt32VectorToUidVectorWithLimit(const std::vector<int32_t> & uidsAidl,std::vector<uid_t> & uids)2090 Status convertInt32VectorToUidVectorWithLimit(
2091         const std::vector<int32_t>& uidsAidl, std::vector<uid_t>& uids) {
2092     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2093         convertRangeWithLimit(uidsAidl.begin(),
2094             uidsAidl.end(),
2095             std::back_inserter(uids),
2096             aidl2legacy_int32_t_uid_t,
2097             MAX_ITEMS_PER_LIST)));
2098 
2099     return Status::ok();
2100 }
2101 
setAssistantServicesUids(const std::vector<int32_t> & uidsAidl)2102 Status AudioPolicyService::setAssistantServicesUids(const std::vector<int32_t>& uidsAidl)
2103 {
2104     std::vector<uid_t> uids;
2105     RETURN_IF_BINDER_ERROR(convertInt32VectorToUidVectorWithLimit(uidsAidl, uids));
2106 
2107     audio_utils::lock_guard _l(mMutex);
2108     mUidPolicy->setAssistantUids(uids);
2109     return Status::ok();
2110 }
2111 
setActiveAssistantServicesUids(const std::vector<int32_t> & activeUidsAidl)2112 Status AudioPolicyService::setActiveAssistantServicesUids(
2113         const std::vector<int32_t>& activeUidsAidl) {
2114     std::vector<uid_t> activeUids;
2115     RETURN_IF_BINDER_ERROR(convertInt32VectorToUidVectorWithLimit(activeUidsAidl, activeUids));
2116 
2117     audio_utils::lock_guard _l(mMutex);
2118     mUidPolicy->setActiveAssistantUids(activeUids);
2119     return Status::ok();
2120 }
2121 
setA11yServicesUids(const std::vector<int32_t> & uidsAidl)2122 Status AudioPolicyService::setA11yServicesUids(const std::vector<int32_t>& uidsAidl)
2123 {
2124     std::vector<uid_t> uids;
2125     RETURN_IF_BINDER_ERROR(convertInt32VectorToUidVectorWithLimit(uidsAidl, uids));
2126 
2127     audio_utils::lock_guard _l(mMutex);
2128     mUidPolicy->setA11yUids(uids);
2129     return Status::ok();
2130 }
2131 
setCurrentImeUid(int32_t uidAidl)2132 Status AudioPolicyService::setCurrentImeUid(int32_t uidAidl)
2133 {
2134     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
2135     audio_utils::lock_guard _l(mMutex);
2136     mUidPolicy->setCurrentImeUid(uid);
2137     return Status::ok();
2138 }
2139 
isHapticPlaybackSupported(bool * _aidl_return)2140 Status AudioPolicyService::isHapticPlaybackSupported(bool* _aidl_return)
2141 {
2142     if (mAudioPolicyManager == NULL) {
2143         return binderStatusFromStatusT(NO_INIT);
2144     }
2145     audio_utils::lock_guard _l(mMutex);
2146     AutoCallerClear acc;
2147     *_aidl_return = mAudioPolicyManager->isHapticPlaybackSupported();
2148     return Status::ok();
2149 }
2150 
isUltrasoundSupported(bool * _aidl_return)2151 Status AudioPolicyService::isUltrasoundSupported(bool* _aidl_return)
2152 {
2153     if (mAudioPolicyManager == NULL) {
2154         return binderStatusFromStatusT(NO_INIT);
2155     }
2156     audio_utils::lock_guard _l(mMutex);
2157     AutoCallerClear acc;
2158     *_aidl_return = mAudioPolicyManager->isUltrasoundSupported();
2159     return Status::ok();
2160 }
2161 
isHotwordStreamSupported(bool lookbackAudio,bool * _aidl_return)2162 Status AudioPolicyService::isHotwordStreamSupported(bool lookbackAudio, bool* _aidl_return)
2163 {
2164     if (mAudioPolicyManager == nullptr) {
2165         return binderStatusFromStatusT(NO_INIT);
2166     }
2167     audio_utils::lock_guard _l(mMutex);
2168     AutoCallerClear acc;
2169     *_aidl_return = mAudioPolicyManager->isHotwordStreamSupported(lookbackAudio);
2170     return Status::ok();
2171 }
2172 
listAudioProductStrategies(std::vector<media::AudioProductStrategy> * _aidl_return)2173 Status AudioPolicyService::listAudioProductStrategies(
2174         std::vector<media::AudioProductStrategy>* _aidl_return) {
2175     AudioProductStrategyVector strategies;
2176 
2177     if (mAudioPolicyManager == NULL) {
2178         return binderStatusFromStatusT(NO_INIT);
2179     }
2180     audio_utils::lock_guard _l(mMutex);
2181     RETURN_IF_BINDER_ERROR(
2182             binderStatusFromStatusT(mAudioPolicyManager->listAudioProductStrategies(strategies)));
2183     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2184             convertContainer<std::vector<media::AudioProductStrategy>>(
2185                     strategies,
2186                     legacy2aidl_AudioProductStrategy));
2187     return Status::ok();
2188 }
2189 
getProductStrategyFromAudioAttributes(const media::audio::common::AudioAttributes & aaAidl,bool fallbackOnDefault,int32_t * _aidl_return)2190 Status AudioPolicyService::getProductStrategyFromAudioAttributes(
2191         const media::audio::common::AudioAttributes& aaAidl,
2192         bool fallbackOnDefault, int32_t* _aidl_return) {
2193     audio_attributes_t aa = VALUE_OR_RETURN_BINDER_STATUS(
2194             aidl2legacy_AudioAttributes_audio_attributes_t(aaAidl));
2195     product_strategy_t productStrategy;
2196 
2197     if (mAudioPolicyManager == NULL) {
2198         return binderStatusFromStatusT(NO_INIT);
2199     }
2200     audio_utils::lock_guard _l(mMutex);
2201     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2202             mAudioPolicyManager->getProductStrategyFromAudioAttributes(
2203                     aa, productStrategy, fallbackOnDefault)));
2204     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2205             legacy2aidl_product_strategy_t_int32_t(productStrategy));
2206     return Status::ok();
2207 }
2208 
listAudioVolumeGroups(std::vector<media::AudioVolumeGroup> * _aidl_return)2209 Status AudioPolicyService::listAudioVolumeGroups(std::vector<media::AudioVolumeGroup>* _aidl_return)
2210 {
2211     AudioVolumeGroupVector groups;
2212     if (mAudioPolicyManager == NULL) {
2213         return binderStatusFromStatusT(NO_INIT);
2214     }
2215     audio_utils::lock_guard _l(mMutex);
2216     RETURN_IF_BINDER_ERROR(
2217             binderStatusFromStatusT(mAudioPolicyManager->listAudioVolumeGroups(groups)));
2218     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2219             convertContainer<std::vector<media::AudioVolumeGroup>>(groups,
2220                                                                    legacy2aidl_AudioVolumeGroup));
2221     return Status::ok();
2222 }
2223 
getVolumeGroupFromAudioAttributes(const media::audio::common::AudioAttributes & aaAidl,bool fallbackOnDefault,int32_t * _aidl_return)2224 Status AudioPolicyService::getVolumeGroupFromAudioAttributes(
2225         const media::audio::common::AudioAttributes& aaAidl,
2226         bool fallbackOnDefault, int32_t* _aidl_return) {
2227     audio_attributes_t aa = VALUE_OR_RETURN_BINDER_STATUS(
2228             aidl2legacy_AudioAttributes_audio_attributes_t(aaAidl));
2229     volume_group_t volumeGroup;
2230 
2231     if (mAudioPolicyManager == NULL) {
2232         return binderStatusFromStatusT(NO_INIT);
2233     }
2234     audio_utils::lock_guard _l(mMutex);
2235     RETURN_IF_BINDER_ERROR(
2236             binderStatusFromStatusT(
2237                     mAudioPolicyManager->getVolumeGroupFromAudioAttributes(
2238                             aa, volumeGroup, fallbackOnDefault)));
2239     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_volume_group_t_int32_t(volumeGroup));
2240     return Status::ok();
2241 }
2242 
setRttEnabled(bool enabled)2243 Status AudioPolicyService::setRttEnabled(bool enabled)
2244 {
2245     audio_utils::lock_guard _l(mMutex);
2246     mUidPolicy->setRttEnabled(enabled);
2247     return Status::ok();
2248 }
2249 
isCallScreenModeSupported(bool * _aidl_return)2250 Status AudioPolicyService::isCallScreenModeSupported(bool* _aidl_return)
2251 {
2252     if (mAudioPolicyManager == NULL) {
2253         return binderStatusFromStatusT(NO_INIT);
2254     }
2255     audio_utils::lock_guard _l(mMutex);
2256     AutoCallerClear acc;
2257     *_aidl_return = mAudioPolicyManager->isCallScreenModeSupported();
2258     return Status::ok();
2259 }
2260 
setDevicesRoleForStrategy(int32_t strategyAidl,media::DeviceRole roleAidl,const std::vector<AudioDevice> & devicesAidl)2261 Status AudioPolicyService::setDevicesRoleForStrategy(
2262         int32_t strategyAidl,
2263         media::DeviceRole roleAidl,
2264         const std::vector<AudioDevice>& devicesAidl) {
2265     product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS(
2266             aidl2legacy_int32_t_product_strategy_t(strategyAidl));
2267     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2268             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2269     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
2270             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2271                                                         aidl2legacy_AudioDeviceTypeAddress));
2272 
2273     if (mAudioPolicyManager == NULL) {
2274         return binderStatusFromStatusT(NO_INIT);
2275     }
2276     audio_utils::lock_guard _l(mMutex);
2277     status_t status = mAudioPolicyManager->setDevicesRoleForStrategy(strategy, role, devices);
2278     if (status == NO_ERROR) {
2279        onCheckSpatializer_l();
2280     }
2281     return binderStatusFromStatusT(status);
2282 }
2283 
removeDevicesRoleForStrategy(int32_t strategyAidl,media::DeviceRole roleAidl,const std::vector<AudioDevice> & devicesAidl)2284 Status AudioPolicyService::removeDevicesRoleForStrategy(
2285         int32_t strategyAidl,
2286         media::DeviceRole roleAidl,
2287         const std::vector<AudioDevice>& devicesAidl) {
2288     product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS(
2289             aidl2legacy_int32_t_product_strategy_t(strategyAidl));
2290     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2291             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2292     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
2293             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2294                                                         aidl2legacy_AudioDeviceTypeAddress));
2295 
2296     if (mAudioPolicyManager == NULL) {
2297         return binderStatusFromStatusT(NO_INIT);
2298     }
2299     audio_utils::lock_guard _l(mMutex);
2300     status_t status = mAudioPolicyManager->removeDevicesRoleForStrategy(strategy, role, devices);
2301     if (status == NO_ERROR) {
2302        onCheckSpatializer_l();
2303     }
2304     return binderStatusFromStatusT(status);
2305 }
2306 
clearDevicesRoleForStrategy(int32_t strategyAidl,media::DeviceRole roleAidl)2307 Status AudioPolicyService::clearDevicesRoleForStrategy(int32_t strategyAidl,
2308                                                            media::DeviceRole roleAidl) {
2309      product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS(
2310             aidl2legacy_int32_t_product_strategy_t(strategyAidl));
2311     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2312             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2313    if (mAudioPolicyManager == NULL) {
2314         return binderStatusFromStatusT(NO_INIT);
2315     }
2316     audio_utils::lock_guard _l(mMutex);
2317     status_t status = mAudioPolicyManager->clearDevicesRoleForStrategy(strategy, role);
2318     if (status == NO_ERROR) {
2319        onCheckSpatializer_l();
2320     }
2321     return binderStatusFromStatusT(status);
2322 }
2323 
getDevicesForRoleAndStrategy(int32_t strategyAidl,media::DeviceRole roleAidl,std::vector<AudioDevice> * _aidl_return)2324 Status AudioPolicyService::getDevicesForRoleAndStrategy(
2325         int32_t strategyAidl,
2326         media::DeviceRole roleAidl,
2327         std::vector<AudioDevice>* _aidl_return) {
2328     product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS(
2329             aidl2legacy_int32_t_product_strategy_t(strategyAidl));
2330     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2331             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2332     AudioDeviceTypeAddrVector devices;
2333 
2334     if (mAudioPolicyManager == NULL) {
2335         return binderStatusFromStatusT(NO_INIT);
2336     }
2337     audio_utils::lock_guard _l(mMutex);
2338     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2339             mAudioPolicyManager->getDevicesForRoleAndStrategy(strategy, role, devices)));
2340     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2341             convertContainer<std::vector<AudioDevice>>(devices,
2342                                                        legacy2aidl_AudioDeviceTypeAddress));
2343     return Status::ok();
2344 }
2345 
registerSoundTriggerCaptureStateListener(const sp<media::ICaptureStateListener> & listener,bool * _aidl_return)2346 Status AudioPolicyService::registerSoundTriggerCaptureStateListener(
2347         const sp<media::ICaptureStateListener>& listener, bool* _aidl_return) {
2348     *_aidl_return = mCaptureStateNotifier.RegisterListener(listener);
2349     return Status::ok();
2350 }
2351 
setDevicesRoleForCapturePreset(AudioSource audioSourceAidl,media::DeviceRole roleAidl,const std::vector<AudioDevice> & devicesAidl)2352 Status AudioPolicyService::setDevicesRoleForCapturePreset(
2353         AudioSource audioSourceAidl,
2354         media::DeviceRole roleAidl,
2355         const std::vector<AudioDevice>& devicesAidl) {
2356     audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS(
2357             aidl2legacy_AudioSource_audio_source_t(audioSourceAidl));
2358     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2359             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2360     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
2361             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2362                                                         aidl2legacy_AudioDeviceTypeAddress));
2363 
2364     if (mAudioPolicyManager == nullptr) {
2365         return binderStatusFromStatusT(NO_INIT);
2366     }
2367     audio_utils::lock_guard _l(mMutex);
2368     return binderStatusFromStatusT(
2369             mAudioPolicyManager->setDevicesRoleForCapturePreset(audioSource, role, devices));
2370 }
2371 
addDevicesRoleForCapturePreset(AudioSource audioSourceAidl,media::DeviceRole roleAidl,const std::vector<AudioDevice> & devicesAidl)2372 Status AudioPolicyService::addDevicesRoleForCapturePreset(
2373         AudioSource audioSourceAidl,
2374         media::DeviceRole roleAidl,
2375         const std::vector<AudioDevice>& devicesAidl) {
2376     audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS(
2377             aidl2legacy_AudioSource_audio_source_t(audioSourceAidl));
2378     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2379             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2380     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
2381             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2382                                                         aidl2legacy_AudioDeviceTypeAddress));
2383 
2384     if (mAudioPolicyManager == nullptr) {
2385         return binderStatusFromStatusT(NO_INIT);
2386     }
2387     audio_utils::lock_guard _l(mMutex);
2388     return binderStatusFromStatusT(
2389             mAudioPolicyManager->addDevicesRoleForCapturePreset(audioSource, role, devices));
2390 }
2391 
removeDevicesRoleForCapturePreset(AudioSource audioSourceAidl,media::DeviceRole roleAidl,const std::vector<AudioDevice> & devicesAidl)2392 Status AudioPolicyService::removeDevicesRoleForCapturePreset(
2393         AudioSource audioSourceAidl,
2394         media::DeviceRole roleAidl,
2395         const std::vector<AudioDevice>& devicesAidl) {
2396     audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS(
2397             aidl2legacy_AudioSource_audio_source_t(audioSourceAidl));
2398     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2399             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2400     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
2401             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2402                                                         aidl2legacy_AudioDeviceTypeAddress));
2403 
2404    if (mAudioPolicyManager == nullptr) {
2405         return binderStatusFromStatusT(NO_INIT);
2406     }
2407     audio_utils::lock_guard _l(mMutex);
2408     return binderStatusFromStatusT(
2409             mAudioPolicyManager->removeDevicesRoleForCapturePreset(audioSource, role, devices));
2410 }
2411 
clearDevicesRoleForCapturePreset(AudioSource audioSourceAidl,media::DeviceRole roleAidl)2412 Status AudioPolicyService::clearDevicesRoleForCapturePreset(AudioSource audioSourceAidl,
2413                                                             media::DeviceRole roleAidl) {
2414     audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS(
2415             aidl2legacy_AudioSource_audio_source_t(audioSourceAidl));
2416     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2417             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2418 
2419     if (mAudioPolicyManager == nullptr) {
2420         return binderStatusFromStatusT(NO_INIT);
2421     }
2422     audio_utils::lock_guard _l(mMutex);
2423     return binderStatusFromStatusT(
2424             mAudioPolicyManager->clearDevicesRoleForCapturePreset(audioSource, role));
2425 }
2426 
getDevicesForRoleAndCapturePreset(AudioSource audioSourceAidl,media::DeviceRole roleAidl,std::vector<AudioDevice> * _aidl_return)2427 Status AudioPolicyService::getDevicesForRoleAndCapturePreset(
2428         AudioSource audioSourceAidl,
2429         media::DeviceRole roleAidl,
2430         std::vector<AudioDevice>* _aidl_return) {
2431     audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS(
2432             aidl2legacy_AudioSource_audio_source_t(audioSourceAidl));
2433     device_role_t role = VALUE_OR_RETURN_BINDER_STATUS(
2434             aidl2legacy_DeviceRole_device_role_t(roleAidl));
2435     AudioDeviceTypeAddrVector devices;
2436 
2437     if (mAudioPolicyManager == nullptr) {
2438         return binderStatusFromStatusT(NO_INIT);
2439     }
2440     audio_utils::lock_guard _l(mMutex);
2441     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2442             mAudioPolicyManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices)));
2443     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2444             convertContainer<std::vector<AudioDevice>>(devices,
2445                                                        legacy2aidl_AudioDeviceTypeAddress));
2446     return Status::ok();
2447 }
2448 
getSpatializer(const sp<media::INativeSpatializerCallback> & callback,media::GetSpatializerResponse * _aidl_return)2449 Status AudioPolicyService::getSpatializer(
2450         const sp<media::INativeSpatializerCallback>& callback,
2451         media::GetSpatializerResponse* _aidl_return) {
2452     _aidl_return->spatializer = nullptr;
2453     if (callback == nullptr) {
2454         return binderStatusFromStatusT(BAD_VALUE);
2455     }
2456     if (mSpatializer != nullptr) {
2457         RETURN_IF_BINDER_ERROR(
2458                 binderStatusFromStatusT(mSpatializer->registerCallback(callback)));
2459         _aidl_return->spatializer = mSpatializer;
2460     }
2461     return Status::ok();
2462 }
2463 
canBeSpatialized(const std::optional<media::audio::common::AudioAttributes> & attrAidl,const std::optional<AudioConfig> & configAidl,const std::vector<AudioDevice> & devicesAidl,bool * _aidl_return)2464 Status AudioPolicyService::canBeSpatialized(
2465         const std::optional<media::audio::common::AudioAttributes>& attrAidl,
2466         const std::optional<AudioConfig>& configAidl,
2467         const std::vector<AudioDevice>& devicesAidl,
2468         bool* _aidl_return) {
2469     if (mAudioPolicyManager == nullptr) {
2470         return binderStatusFromStatusT(NO_INIT);
2471     }
2472     audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER;
2473     if (attrAidl.has_value()) {
2474         attr = VALUE_OR_RETURN_BINDER_STATUS(
2475             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl.value()));
2476     }
2477     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2478     if (configAidl.has_value()) {
2479         config = VALUE_OR_RETURN_BINDER_STATUS(
2480                                     aidl2legacy_AudioConfig_audio_config_t(configAidl.value(),
2481                                     false /*isInput*/));
2482     }
2483     AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS(
2484             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2485                                                         aidl2legacy_AudioDeviceTypeAddress));
2486 
2487     audio_utils::lock_guard _l(mMutex);
2488     *_aidl_return = mAudioPolicyManager->canBeSpatialized(&attr, &config, devices);
2489     return Status::ok();
2490 }
2491 
getDirectPlaybackSupport(const media::audio::common::AudioAttributes & attrAidl,const AudioConfig & configAidl,media::AudioDirectMode * _aidl_return)2492 Status AudioPolicyService::getDirectPlaybackSupport(
2493         const media::audio::common::AudioAttributes &attrAidl,
2494         const AudioConfig &configAidl,
2495         media::AudioDirectMode *_aidl_return) {
2496     if (mAudioPolicyManager == nullptr) {
2497         return binderStatusFromStatusT(NO_INIT);
2498     }
2499     if (_aidl_return == nullptr) {
2500         return binderStatusFromStatusT(BAD_VALUE);
2501     }
2502     audio_attributes_t attr = VALUE_OR_RETURN_BINDER_STATUS(
2503             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
2504     audio_config_t config = VALUE_OR_RETURN_BINDER_STATUS(
2505             aidl2legacy_AudioConfig_audio_config_t(configAidl, false /*isInput*/));
2506     audio_utils::lock_guard _l(mMutex);
2507     *_aidl_return = static_cast<media::AudioDirectMode>(
2508             VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_direct_mode_t_int32_t_mask(
2509                     mAudioPolicyManager->getDirectPlaybackSupport(&attr, &config))));
2510     return Status::ok();
2511 }
2512 
getDirectProfilesForAttributes(const media::audio::common::AudioAttributes & attrAidl,std::vector<media::audio::common::AudioProfile> * _aidl_return)2513 Status AudioPolicyService::getDirectProfilesForAttributes(
2514                                 const media::audio::common::AudioAttributes& attrAidl,
2515                                 std::vector<media::audio::common::AudioProfile>* _aidl_return) {
2516    if (mAudioPolicyManager == nullptr) {
2517         return binderStatusFromStatusT(NO_INIT);
2518     }
2519     audio_attributes_t attr = VALUE_OR_RETURN_BINDER_STATUS(
2520             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
2521     AudioProfileVector audioProfiles;
2522 
2523     audio_utils::lock_guard _l(mMutex);
2524     RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(
2525             mAudioPolicyManager->getDirectProfilesForAttributes(&attr, audioProfiles)));
2526     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2527             convertContainer<std::vector<media::audio::common::AudioProfile>>(
2528                 audioProfiles, legacy2aidl_AudioProfile_common, false /*isInput*/));
2529 
2530     return Status::ok();
2531 }
2532 
getSupportedMixerAttributes(int32_t portIdAidl,std::vector<media::AudioMixerAttributesInternal> * _aidl_return)2533 Status AudioPolicyService::getSupportedMixerAttributes(
2534         int32_t portIdAidl, std::vector<media::AudioMixerAttributesInternal>* _aidl_return) {
2535     if (mAudioPolicyManager == nullptr) {
2536         return binderStatusFromStatusT(NO_INIT);
2537     }
2538 
2539     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
2540             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
2541 
2542     std::vector<audio_mixer_attributes_t> mixerAttrs;
2543     audio_utils::lock_guard _l(mMutex);
2544     RETURN_IF_BINDER_ERROR(
2545             binderStatusFromStatusT(mAudioPolicyManager->getSupportedMixerAttributes(
2546                     portId, mixerAttrs)));
2547     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2548             convertContainer<std::vector<media::AudioMixerAttributesInternal>>(
2549                     mixerAttrs,
2550                     legacy2aidl_audio_mixer_attributes_t_AudioMixerAttributesInternal));
2551     return Status::ok();
2552 }
2553 
setPreferredMixerAttributes(const media::audio::common::AudioAttributes & attrAidl,int32_t portIdAidl,int32_t uidAidl,const media::AudioMixerAttributesInternal & mixerAttrAidl)2554 Status AudioPolicyService::setPreferredMixerAttributes(
2555         const media::audio::common::AudioAttributes& attrAidl,
2556         int32_t portIdAidl,
2557         int32_t uidAidl,
2558         const media::AudioMixerAttributesInternal& mixerAttrAidl) {
2559     if (mAudioPolicyManager == nullptr) {
2560         return binderStatusFromStatusT(NO_INIT);
2561     }
2562 
2563     audio_attributes_t  attr = VALUE_OR_RETURN_BINDER_STATUS(
2564             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
2565     audio_mixer_attributes_t mixerAttr = VALUE_OR_RETURN_BINDER_STATUS(
2566             aidl2legacy_AudioMixerAttributesInternal_audio_mixer_attributes_t(mixerAttrAidl));
2567     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
2568     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
2569             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
2570 
2571     audio_utils::lock_guard _l(mMutex);
2572     return binderStatusFromStatusT(
2573             mAudioPolicyManager->setPreferredMixerAttributes(&attr, portId, uid, &mixerAttr));
2574 }
2575 
getPreferredMixerAttributes(const media::audio::common::AudioAttributes & attrAidl,int32_t portIdAidl,std::optional<media::AudioMixerAttributesInternal> * _aidl_return)2576 Status AudioPolicyService::getPreferredMixerAttributes(
2577         const media::audio::common::AudioAttributes& attrAidl,
2578         int32_t portIdAidl,
2579         std::optional<media::AudioMixerAttributesInternal>* _aidl_return) {
2580     if (mAudioPolicyManager == nullptr) {
2581         return binderStatusFromStatusT(NO_INIT);
2582     }
2583 
2584     audio_attributes_t  attr = VALUE_OR_RETURN_BINDER_STATUS(
2585             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
2586     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
2587             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
2588 
2589     audio_utils::lock_guard _l(mMutex);
2590     audio_mixer_attributes_t mixerAttr = AUDIO_MIXER_ATTRIBUTES_INITIALIZER;
2591     RETURN_IF_BINDER_ERROR(
2592             binderStatusFromStatusT(mAudioPolicyManager->getPreferredMixerAttributes(
2593                     &attr, portId, &mixerAttr)));
2594     *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(
2595             legacy2aidl_audio_mixer_attributes_t_AudioMixerAttributesInternal(mixerAttr));
2596     return Status::ok();
2597 }
2598 
clearPreferredMixerAttributes(const media::audio::common::AudioAttributes & attrAidl,int32_t portIdAidl,int32_t uidAidl)2599 Status AudioPolicyService::clearPreferredMixerAttributes(
2600         const media::audio::common::AudioAttributes& attrAidl,
2601         int32_t portIdAidl,
2602         int32_t uidAidl) {
2603     if (mAudioPolicyManager == nullptr) {
2604         return binderStatusFromStatusT(NO_INIT);
2605     }
2606 
2607     audio_attributes_t  attr = VALUE_OR_RETURN_BINDER_STATUS(
2608             aidl2legacy_AudioAttributes_audio_attributes_t(attrAidl));
2609     uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl));
2610     audio_port_handle_t portId = VALUE_OR_RETURN_BINDER_STATUS(
2611             aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
2612 
2613     audio_utils::lock_guard _l(mMutex);
2614     return binderStatusFromStatusT(
2615             mAudioPolicyManager->clearPreferredMixerAttributes(&attr, portId, uid));
2616 }
2617 
getPermissionController(sp<INativePermissionController> * out)2618 Status AudioPolicyService::getPermissionController(sp<INativePermissionController>* out) {
2619     *out = mPermissionController;
2620     return Status::ok();
2621 }
2622 
2623 } // namespace android
2624