1 /*
2  * Copyright (C) 2006-2007 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 "AudioSystem"
18 //#define LOG_NDEBUG 0
19 
20 #include <utils/Log.h>
21 
22 #include <android/media/IAudioPolicyService.h>
23 #include <android/media/AudioMixUpdate.h>
24 #include <android/media/BnCaptureStateListener.h>
25 #include <android_media_audiopolicy.h>
26 #include <binder/IServiceManager.h>
27 #include <binder/ProcessState.h>
28 #include <binder/IPCThreadState.h>
29 #include <media/AidlConversion.h>
30 #include <media/AudioResamplerPublic.h>
31 #include <media/AudioSystem.h>
32 #include <media/IAudioFlinger.h>
33 #include <media/PolicyAidlConversion.h>
34 #include <media/TypeConverter.h>
35 #include <math.h>
36 
37 #include <system/audio.h>
38 #include <android/media/GetInputForAttrResponse.h>
39 #include <android/media/AudioMixerAttributesInternal.h>
40 
41 #define VALUE_OR_RETURN_BINDER_STATUS(x) \
42     ({ auto _tmp = (x); \
43        if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \
44        std::move(_tmp.value()); })
45 
46 // ----------------------------------------------------------------------------
47 
48 namespace audio_flags = android::media::audiopolicy;
49 
50 namespace android {
51 using aidl_utils::statusTFromBinderStatus;
52 using binder::Status;
53 using content::AttributionSourceState;
54 using media::IAudioPolicyService;
55 using media::audio::common::AudioConfig;
56 using media::audio::common::AudioConfigBase;
57 using media::audio::common::AudioDevice;
58 using media::audio::common::AudioDeviceDescription;
59 using media::audio::common::AudioFormatDescription;
60 using media::audio::common::AudioMMapPolicyInfo;
61 using media::audio::common::AudioMMapPolicyType;
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::Int;
67 
68 std::mutex AudioSystem::gMutex;
69 dynamic_policy_callback AudioSystem::gDynPolicyCallback = NULL;
70 record_config_callback AudioSystem::gRecordConfigCallback = NULL;
71 routing_callback AudioSystem::gRoutingCallback = NULL;
72 vol_range_init_req_callback AudioSystem::gVolRangeInitReqCallback = NULL;
73 
74 std::mutex AudioSystem::gApsCallbackMutex;
75 std::mutex AudioSystem::gErrorCallbacksMutex;
76 std::set<audio_error_callback> AudioSystem::gAudioErrorCallbacks;
77 
78 std::mutex AudioSystem::gSoundTriggerMutex;
79 sp<CaptureStateListenerImpl> AudioSystem::gSoundTriggerCaptureStateListener;
80 
81 // Sets the Binder for the AudioFlinger service, passed to this client process
82 // from the system server.
83 // This allows specific isolated processes to access the audio system. Currently used only for the
84 // HotwordDetectionService.
85 template <typename ServiceInterface, typename Client, typename AidlInterface,
86         typename ServiceTraits>
87 class ServiceHandler {
88 public:
getService()89     sp<ServiceInterface> getService()
90             EXCLUDES(mMutex) NO_THREAD_SAFETY_ANALYSIS {  // std::unique_ptr
91         sp<ServiceInterface> service;
92         sp<Client> client;
93 
94         bool reportNoError = false;
95         {
96             std::lock_guard _l(mMutex);
97             if (mService != nullptr) {
98                 return mService;
99             }
100         }
101 
102         std::unique_lock ul_only1thread(mSingleGetter);
103         std::unique_lock ul(mMutex);
104         if (mService != nullptr) {
105             return mService;
106         }
107         if (mClient == nullptr) {
108             mClient = sp<Client>::make();
109         } else {
110             reportNoError = true;
111         }
112         while (true) {
113             mService = mLocalService;
114             if (mService != nullptr) break;
115 
116             sp<IBinder> binder = mBinder;
117             if (binder == nullptr) {
118                 sp <IServiceManager> sm = defaultServiceManager();
119                 binder = sm->checkService(String16(ServiceTraits::SERVICE_NAME));
120                 if (binder == nullptr) {
121                     ALOGD("%s: waiting for %s", __func__, ServiceTraits::SERVICE_NAME);
122 
123                     // if the condition variable is present, setLocalService() and
124                     // setBinder() is allowed to use it to notify us.
125                     if (mCvGetter == nullptr) {
126                         mCvGetter = std::make_shared<std::condition_variable>();
127                     }
128                     mCvGetter->wait_for(ul, std::chrono::seconds(1));
129                     continue;
130                 }
131             }
132             binder->linkToDeath(mClient);
133             auto aidlInterface = interface_cast<AidlInterface>(binder);
134             LOG_ALWAYS_FATAL_IF(aidlInterface == nullptr);
135             if constexpr (std::is_same_v<ServiceInterface, AidlInterface>) {
136                 mService = std::move(aidlInterface);
137             } else /* constexpr */ {
138                 mService = ServiceTraits::createServiceAdapter(aidlInterface);
139             }
140             break;
141         }
142         if (mCvGetter) mCvGetter.reset();  // remove condition variable.
143         client = mClient;
144         service = mService;
145         // Make sure callbacks can be received by the client
146         if (mCanStartThreadPool) {
147             ProcessState::self()->startThreadPool();
148         }
149         ul.unlock();
150         ul_only1thread.unlock();
151         ServiceTraits::onServiceCreate(service, client);
152         if (reportNoError) AudioSystem::reportError(NO_ERROR);
153         return service;
154     }
155 
setLocalService(const sp<ServiceInterface> & service)156     status_t setLocalService(const sp<ServiceInterface>& service) EXCLUDES(mMutex) {
157         std::lock_guard _l(mMutex);
158         // we allow clearing once set, but not a double non-null set.
159         if (mService != nullptr && service != nullptr) return INVALID_OPERATION;
160         mLocalService = service;
161         if (mCvGetter) mCvGetter->notify_one();
162         return OK;
163     }
164 
getClient()165     sp<Client> getClient() EXCLUDES(mMutex)  {
166         const auto service = getService();
167         if (service == nullptr) return nullptr;
168         std::lock_guard _l(mMutex);
169         return mClient;
170     }
171 
setBinder(const sp<IBinder> & binder)172     void setBinder(const sp<IBinder>& binder) EXCLUDES(mMutex)  {
173         std::lock_guard _l(mMutex);
174         if (mService != nullptr) {
175             ALOGW("%s: ignoring; %s connection already established.",
176                     __func__, ServiceTraits::SERVICE_NAME);
177             return;
178         }
179         mBinder = binder;
180         if (mCvGetter) mCvGetter->notify_one();
181     }
182 
clearService()183     void clearService() EXCLUDES(mMutex)  {
184         std::lock_guard _l(mMutex);
185         mService.clear();
186         if (mClient) ServiceTraits::onClearService(mClient);
187     }
188 
disableThreadPool()189     void disableThreadPool() {
190         mCanStartThreadPool = false;
191     }
192 
193 private:
194     std::mutex mSingleGetter;
195     std::mutex mMutex;
196     std::shared_ptr<std::condition_variable> mCvGetter GUARDED_BY(mMutex);
197     sp<IBinder> mBinder GUARDED_BY(mMutex);
198     sp<ServiceInterface> mLocalService GUARDED_BY(mMutex);
199     sp<ServiceInterface> mService GUARDED_BY(mMutex);
200     sp<Client> mClient GUARDED_BY(mMutex);
201     std::atomic<bool> mCanStartThreadPool = true;
202 };
203 
204 struct AudioFlingerTraits {
onServiceCreateandroid::AudioFlingerTraits205     static void onServiceCreate(
206             const sp<IAudioFlinger>& af, const sp<AudioSystem::AudioFlingerClient>& afc) {
207         const int64_t token = IPCThreadState::self()->clearCallingIdentity();
208         af->registerClient(afc);
209         IPCThreadState::self()->restoreCallingIdentity(token);
210     }
211 
createServiceAdapterandroid::AudioFlingerTraits212     static sp<IAudioFlinger> createServiceAdapter(
213             const sp<media::IAudioFlingerService>& aidlInterface) {
214         return sp<AudioFlingerClientAdapter>::make(aidlInterface);
215     }
216 
onClearServiceandroid::AudioFlingerTraits217     static void onClearService(const sp<AudioSystem::AudioFlingerClient>& afc) {
218         afc->clearIoCache();
219     }
220 
221     static constexpr const char* SERVICE_NAME = IAudioFlinger::DEFAULT_SERVICE_NAME;
222 };
223 
224 [[clang::no_destroy]] static constinit ServiceHandler<IAudioFlinger,
225         AudioSystem::AudioFlingerClient, media::IAudioFlingerService,
226         AudioFlingerTraits> gAudioFlingerServiceHandler;
227 
get_audio_flinger()228 sp<IAudioFlinger> AudioSystem::get_audio_flinger() {
229     return gAudioFlingerServiceHandler.getService();
230 }
231 
getAudioFlingerClient()232 sp<AudioSystem::AudioFlingerClient> AudioSystem::getAudioFlingerClient() {
233     return gAudioFlingerServiceHandler.getClient();
234 }
235 
setAudioFlingerBinder(const sp<IBinder> & audioFlinger)236 void AudioSystem::setAudioFlingerBinder(const sp<IBinder>& audioFlinger) {
237     if (audioFlinger->getInterfaceDescriptor() != media::IAudioFlingerService::descriptor) {
238         ALOGE("%s: received a binder of type %s",
239                 __func__, String8(audioFlinger->getInterfaceDescriptor()).c_str());
240         return;
241     }
242     gAudioFlingerServiceHandler.setBinder(audioFlinger);
243 }
244 
setLocalAudioFlinger(const sp<IAudioFlinger> & af)245 status_t AudioSystem::setLocalAudioFlinger(const sp<IAudioFlinger>& af) {
246     return gAudioFlingerServiceHandler.setLocalService(af);
247 }
248 
getIoDescriptor(audio_io_handle_t ioHandle)249 sp<AudioIoDescriptor> AudioSystem::getIoDescriptor(audio_io_handle_t ioHandle) {
250     sp<AudioIoDescriptor> desc;
251     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
252     if (afc != 0) {
253         desc = afc->getIoDescriptor(ioHandle);
254     }
255     return desc;
256 }
257 
checkAudioFlinger()258 /* static */ status_t AudioSystem::checkAudioFlinger() {
259     if (defaultServiceManager()->checkService(String16("media.audio_flinger")) != 0) {
260         return NO_ERROR;
261     }
262     return DEAD_OBJECT;
263 }
264 
265 // FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp
266 
muteMicrophone(bool state)267 status_t AudioSystem::muteMicrophone(bool state) {
268     const sp<IAudioFlinger> af = get_audio_flinger();
269     if (af == 0) return PERMISSION_DENIED;
270     return af->setMicMute(state);
271 }
272 
isMicrophoneMuted(bool * state)273 status_t AudioSystem::isMicrophoneMuted(bool* state) {
274     const sp<IAudioFlinger> af = get_audio_flinger();
275     if (af == 0) return PERMISSION_DENIED;
276     *state = af->getMicMute();
277     return NO_ERROR;
278 }
279 
setMasterVolume(float value)280 status_t AudioSystem::setMasterVolume(float value) {
281     const sp<IAudioFlinger> af = get_audio_flinger();
282     if (af == 0) return PERMISSION_DENIED;
283     af->setMasterVolume(value);
284     return NO_ERROR;
285 }
286 
setMasterMute(bool mute)287 status_t AudioSystem::setMasterMute(bool mute) {
288     const sp<IAudioFlinger> af = get_audio_flinger();
289     if (af == 0) return PERMISSION_DENIED;
290     af->setMasterMute(mute);
291     return NO_ERROR;
292 }
293 
getMasterVolume(float * volume)294 status_t AudioSystem::getMasterVolume(float* volume) {
295     const sp<IAudioFlinger> af = get_audio_flinger();
296     if (af == 0) return PERMISSION_DENIED;
297     *volume = af->masterVolume();
298     return NO_ERROR;
299 }
300 
getMasterMute(bool * mute)301 status_t AudioSystem::getMasterMute(bool* mute) {
302     const sp<IAudioFlinger> af = get_audio_flinger();
303     if (af == 0) return PERMISSION_DENIED;
304     *mute = af->masterMute();
305     return NO_ERROR;
306 }
307 
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)308 status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
309                                       audio_io_handle_t output) {
310     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
311     const sp<IAudioFlinger> af = get_audio_flinger();
312     if (af == 0) return PERMISSION_DENIED;
313     af->setStreamVolume(stream, value, output);
314     return NO_ERROR;
315 }
316 
setStreamMute(audio_stream_type_t stream,bool mute)317 status_t AudioSystem::setStreamMute(audio_stream_type_t stream, bool mute) {
318     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
319     const sp<IAudioFlinger> af = get_audio_flinger();
320     if (af == 0) return PERMISSION_DENIED;
321     af->setStreamMute(stream, mute);
322     return NO_ERROR;
323 }
324 
getStreamVolume(audio_stream_type_t stream,float * volume,audio_io_handle_t output)325 status_t AudioSystem::getStreamVolume(audio_stream_type_t stream, float* volume,
326                                       audio_io_handle_t output) {
327     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
328     const sp<IAudioFlinger> af = get_audio_flinger();
329     if (af == 0) return PERMISSION_DENIED;
330     *volume = af->streamVolume(stream, output);
331     return NO_ERROR;
332 }
333 
getStreamMute(audio_stream_type_t stream,bool * mute)334 status_t AudioSystem::getStreamMute(audio_stream_type_t stream, bool* mute) {
335     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
336     const sp<IAudioFlinger> af = get_audio_flinger();
337     if (af == 0) return PERMISSION_DENIED;
338     *mute = af->streamMute(stream);
339     return NO_ERROR;
340 }
341 
setMode(audio_mode_t mode)342 status_t AudioSystem::setMode(audio_mode_t mode) {
343     if (uint32_t(mode) >= AUDIO_MODE_CNT) return BAD_VALUE;
344     const sp<IAudioFlinger> af = get_audio_flinger();
345     if (af == 0) return PERMISSION_DENIED;
346     return af->setMode(mode);
347 }
348 
setSimulateDeviceConnections(bool enabled)349 status_t AudioSystem::setSimulateDeviceConnections(bool enabled) {
350     const sp<IAudioFlinger> af = get_audio_flinger();
351     if (af == 0) return PERMISSION_DENIED;
352     return af->setSimulateDeviceConnections(enabled);
353 }
354 
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)355 status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) {
356     const sp<IAudioFlinger> af = get_audio_flinger();
357     if (af == 0) return PERMISSION_DENIED;
358     return af->setParameters(ioHandle, keyValuePairs);
359 }
360 
getParameters(audio_io_handle_t ioHandle,const String8 & keys)361 String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys) {
362     const sp<IAudioFlinger> af = get_audio_flinger();
363     String8 result = String8("");
364     if (af == 0) return result;
365 
366     result = af->getParameters(ioHandle, keys);
367     return result;
368 }
369 
setParameters(const String8 & keyValuePairs)370 status_t AudioSystem::setParameters(const String8& keyValuePairs) {
371     return setParameters(AUDIO_IO_HANDLE_NONE, keyValuePairs);
372 }
373 
getParameters(const String8 & keys)374 String8 AudioSystem::getParameters(const String8& keys) {
375     return getParameters(AUDIO_IO_HANDLE_NONE, keys);
376 }
377 
378 // convert volume steps to natural log scale
379 
380 // change this value to change volume scaling
381 constexpr float kdbPerStep = 0.5f;
382 // shouldn't need to touch these
383 constexpr float kdBConvert = -kdbPerStep * 2.302585093f / 20.0f;
384 constexpr float kdBConvertInverse = 1.0f / kdBConvert;
385 
linearToLog(int volume)386 float AudioSystem::linearToLog(int volume) {
387     // float v = volume ? exp(float(100 - volume) * kdBConvert) : 0;
388     // ALOGD("linearToLog(%d)=%f", volume, v);
389     // return v;
390     return volume ? exp(float(100 - volume) * kdBConvert) : 0;
391 }
392 
logToLinear(float volume)393 int AudioSystem::logToLinear(float volume) {
394     // int v = volume ? 100 - int(kdBConvertInverse * log(volume) + 0.5) : 0;
395     // ALOGD("logTolinear(%d)=%f", v, volume);
396     // return v;
397     return volume ? 100 - int(kdBConvertInverse * log(volume) + 0.5) : 0;
398 }
399 
calculateMinFrameCount(uint32_t afLatencyMs,uint32_t afFrameCount,uint32_t afSampleRate,uint32_t sampleRate,float speed)400 /* static */ size_t AudioSystem::calculateMinFrameCount(
401         uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
402         uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/) {
403     // Ensure that buffer depth covers at least audio hardware latency
404     uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
405     if (minBufCount < 2) {
406         minBufCount = 2;
407     }
408 #if 0
409         // The notificationsPerBufferReq parameter is not yet used for non-fast tracks,
410         // but keeping the code here to make it easier to add later.
411         if (minBufCount < notificationsPerBufferReq) {
412             minBufCount = notificationsPerBufferReq;
413         }
414 #endif
415     ALOGV("calculateMinFrameCount afLatency %u  afFrameCount %u  afSampleRate %u  "
416           "sampleRate %u  speed %f  minBufCount: %u" /*"  notificationsPerBufferReq %u"*/,
417           afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount
418     /*, notificationsPerBufferReq*/);
419     return minBufCount * sourceFramesNeededWithTimestretch(
420             sampleRate, afFrameCount, afSampleRate, speed);
421 }
422 
423 
424 status_t
getOutputSamplingRate(uint32_t * samplingRate,audio_stream_type_t streamType)425 AudioSystem::getOutputSamplingRate(uint32_t* samplingRate, audio_stream_type_t streamType) {
426     audio_io_handle_t output;
427 
428     if (streamType == AUDIO_STREAM_DEFAULT) {
429         streamType = AUDIO_STREAM_MUSIC;
430     }
431 
432     output = getOutput(streamType);
433     if (output == 0) {
434         return PERMISSION_DENIED;
435     }
436 
437     return getSamplingRate(output, samplingRate);
438 }
439 
getSamplingRate(audio_io_handle_t ioHandle,uint32_t * samplingRate)440 status_t AudioSystem::getSamplingRate(audio_io_handle_t ioHandle,
441                                       uint32_t* samplingRate) {
442     const sp<IAudioFlinger> af = get_audio_flinger();
443     if (af == 0) return PERMISSION_DENIED;
444     sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
445     if (desc == 0) {
446         *samplingRate = af->sampleRate(ioHandle);
447     } else {
448         *samplingRate = desc->getSamplingRate();
449     }
450     if (*samplingRate == 0) {
451         ALOGE("AudioSystem::getSamplingRate failed for ioHandle %d", ioHandle);
452         return BAD_VALUE;
453     }
454 
455     ALOGV("getSamplingRate() ioHandle %d, sampling rate %u", ioHandle, *samplingRate);
456 
457     return NO_ERROR;
458 }
459 
getOutputFrameCount(size_t * frameCount,audio_stream_type_t streamType)460 status_t AudioSystem::getOutputFrameCount(size_t* frameCount, audio_stream_type_t streamType) {
461     audio_io_handle_t output;
462 
463     if (streamType == AUDIO_STREAM_DEFAULT) {
464         streamType = AUDIO_STREAM_MUSIC;
465     }
466 
467     output = getOutput(streamType);
468     if (output == AUDIO_IO_HANDLE_NONE) {
469         return PERMISSION_DENIED;
470     }
471 
472     return getFrameCount(output, frameCount);
473 }
474 
getFrameCount(audio_io_handle_t ioHandle,size_t * frameCount)475 status_t AudioSystem::getFrameCount(audio_io_handle_t ioHandle,
476                                     size_t* frameCount) {
477     const sp<IAudioFlinger> af = get_audio_flinger();
478     if (af == 0) return PERMISSION_DENIED;
479     sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
480     if (desc == 0) {
481         *frameCount = af->frameCount(ioHandle);
482     } else {
483         *frameCount = desc->getFrameCount();
484     }
485     if (*frameCount == 0) {
486         ALOGE("AudioSystem::getFrameCount failed for ioHandle %d", ioHandle);
487         return BAD_VALUE;
488     }
489 
490     ALOGV("getFrameCount() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
491 
492     return NO_ERROR;
493 }
494 
getOutputLatency(uint32_t * latency,audio_stream_type_t streamType)495 status_t AudioSystem::getOutputLatency(uint32_t* latency, audio_stream_type_t streamType) {
496     audio_io_handle_t output;
497 
498     if (streamType == AUDIO_STREAM_DEFAULT) {
499         streamType = AUDIO_STREAM_MUSIC;
500     }
501 
502     output = getOutput(streamType);
503     if (output == AUDIO_IO_HANDLE_NONE) {
504         return PERMISSION_DENIED;
505     }
506 
507     return getLatency(output, latency);
508 }
509 
getLatency(audio_io_handle_t output,uint32_t * latency)510 status_t AudioSystem::getLatency(audio_io_handle_t output,
511                                  uint32_t* latency) {
512     const sp<IAudioFlinger> af = get_audio_flinger();
513     if (af == 0) return PERMISSION_DENIED;
514     sp<AudioIoDescriptor> outputDesc = getIoDescriptor(output);
515     if (outputDesc == 0) {
516         *latency = af->latency(output);
517     } else {
518         *latency = outputDesc->getLatency();
519     }
520 
521     ALOGV("getLatency() output %d, latency %d", output, *latency);
522 
523     return NO_ERROR;
524 }
525 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * buffSize)526 status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
527                                          audio_channel_mask_t channelMask, size_t* buffSize) {
528     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
529     if (afc == 0) {
530         return NO_INIT;
531     }
532     return afc->getInputBufferSize(sampleRate, format, channelMask, buffSize);
533 }
534 
setVoiceVolume(float value)535 status_t AudioSystem::setVoiceVolume(float value) {
536     const sp<IAudioFlinger> af = get_audio_flinger();
537     if (af == 0) return PERMISSION_DENIED;
538     return af->setVoiceVolume(value);
539 }
540 
getRenderPosition(audio_io_handle_t output,uint32_t * halFrames,uint32_t * dspFrames)541 status_t AudioSystem::getRenderPosition(audio_io_handle_t output, uint32_t* halFrames,
542                                         uint32_t* dspFrames) {
543     const sp<IAudioFlinger> af = get_audio_flinger();
544     if (af == 0) return PERMISSION_DENIED;
545 
546     return af->getRenderPosition(halFrames, dspFrames, output);
547 }
548 
getInputFramesLost(audio_io_handle_t ioHandle)549 uint32_t AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle) {
550     const sp<IAudioFlinger> af = get_audio_flinger();
551     uint32_t result = 0;
552     if (af == 0) return result;
553     if (ioHandle == AUDIO_IO_HANDLE_NONE) return result;
554 
555     result = af->getInputFramesLost(ioHandle);
556     return result;
557 }
558 
newAudioUniqueId(audio_unique_id_use_t use)559 audio_unique_id_t AudioSystem::newAudioUniqueId(audio_unique_id_use_t use) {
560     // Must not use AF as IDs will re-roll on audioserver restart, b/130369529.
561     const sp<IAudioFlinger> af = get_audio_flinger();
562     if (af == 0) return AUDIO_UNIQUE_ID_ALLOCATE;
563     return af->newAudioUniqueId(use);
564 }
565 
acquireAudioSessionId(audio_session_t audioSession,pid_t pid,uid_t uid)566 void AudioSystem::acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid) {
567     const sp<IAudioFlinger> af = get_audio_flinger();
568     if (af != 0) {
569         af->acquireAudioSessionId(audioSession, pid, uid);
570     }
571 }
572 
releaseAudioSessionId(audio_session_t audioSession,pid_t pid)573 void AudioSystem::releaseAudioSessionId(audio_session_t audioSession, pid_t pid) {
574     const sp<IAudioFlinger> af = get_audio_flinger();
575     if (af != 0) {
576         af->releaseAudioSessionId(audioSession, pid);
577     }
578 }
579 
getAudioHwSyncForSession(audio_session_t sessionId)580 audio_hw_sync_t AudioSystem::getAudioHwSyncForSession(audio_session_t sessionId) {
581     const sp<IAudioFlinger> af = get_audio_flinger();
582     if (af == 0) return AUDIO_HW_SYNC_INVALID;
583     return af->getAudioHwSyncForSession(sessionId);
584 }
585 
systemReady()586 status_t AudioSystem::systemReady() {
587     const sp<IAudioFlinger> af = get_audio_flinger();
588     if (af == 0) return NO_INIT;
589     return af->systemReady();
590 }
591 
audioPolicyReady()592 status_t AudioSystem::audioPolicyReady() {
593     const sp<IAudioFlinger> af = get_audio_flinger();
594     if (af == 0) return NO_INIT;
595     return af->audioPolicyReady();
596 }
597 
getFrameCountHAL(audio_io_handle_t ioHandle,size_t * frameCount)598 status_t AudioSystem::getFrameCountHAL(audio_io_handle_t ioHandle,
599                                        size_t* frameCount) {
600     const sp<IAudioFlinger> af = get_audio_flinger();
601     if (af == 0) return PERMISSION_DENIED;
602     sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
603     if (desc == 0) {
604         *frameCount = af->frameCountHAL(ioHandle);
605     } else {
606         *frameCount = desc->getFrameCountHAL();
607     }
608     if (*frameCount == 0) {
609         ALOGE("AudioSystem::getFrameCountHAL failed for ioHandle %d", ioHandle);
610         return BAD_VALUE;
611     }
612 
613     ALOGV("getFrameCountHAL() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
614 
615     return NO_ERROR;
616 }
617 
618 // ---------------------------------------------------------------------------
619 
620 
clearIoCache()621 void AudioSystem::AudioFlingerClient::clearIoCache() {
622     std::lock_guard _l(mMutex);
623     mIoDescriptors.clear();
624     mInBuffSize = 0;
625     mInSamplingRate = 0;
626     mInFormat = AUDIO_FORMAT_DEFAULT;
627     mInChannelMask = AUDIO_CHANNEL_NONE;
628 }
629 
binderDied(const wp<IBinder> & who __unused)630 void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who __unused) {
631     gAudioFlingerServiceHandler.clearService();
632     reportError(DEAD_OBJECT);
633 
634     ALOGW("AudioFlinger server died!");
635 }
636 
ioConfigChanged(media::AudioIoConfigEvent _event,const media::AudioIoDescriptor & _ioDesc)637 Status AudioSystem::AudioFlingerClient::ioConfigChanged(
638         media::AudioIoConfigEvent _event,
639         const media::AudioIoDescriptor& _ioDesc) {
640     audio_io_config_event_t event = VALUE_OR_RETURN_BINDER_STATUS(
641             aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t(_event));
642     sp<AudioIoDescriptor> ioDesc(
643             VALUE_OR_RETURN_BINDER_STATUS(
644                     aidl2legacy_AudioIoDescriptor_AudioIoDescriptor(_ioDesc)));
645 
646     ALOGV("ioConfigChanged() event %d", event);
647 
648     if (ioDesc->getIoHandle() == AUDIO_IO_HANDLE_NONE) return Status::ok();
649 
650     audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
651     std::vector<sp<AudioDeviceCallback>> callbacksToCall;
652     {
653         std::lock_guard _l(mMutex);
654         auto callbacks = std::map<audio_port_handle_t, wp<AudioDeviceCallback>>();
655 
656         switch (event) {
657             case AUDIO_OUTPUT_OPENED:
658             case AUDIO_OUTPUT_REGISTERED:
659             case AUDIO_INPUT_OPENED:
660             case AUDIO_INPUT_REGISTERED: {
661                 if (sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->getIoHandle())) {
662                     deviceId = oldDesc->getDeviceId();
663                 }
664                 mIoDescriptors[ioDesc->getIoHandle()] = ioDesc;
665 
666                 if (ioDesc->getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
667                     deviceId = ioDesc->getDeviceId();
668                     if (event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED) {
669                         auto it = mAudioDeviceCallbacks.find(ioDesc->getIoHandle());
670                         if (it != mAudioDeviceCallbacks.end()) {
671                             callbacks = it->second;
672                         }
673                     }
674                 }
675                 ALOGV("ioConfigChanged() new %s %s %s",
676                       event == AUDIO_OUTPUT_OPENED || event == AUDIO_OUTPUT_REGISTERED ?
677                       "output" : "input",
678                       event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED ?
679                       "opened" : "registered",
680                       ioDesc->toDebugString().c_str());
681             }
682                 break;
683             case AUDIO_OUTPUT_CLOSED:
684             case AUDIO_INPUT_CLOSED: {
685                 if (getIoDescriptor_l(ioDesc->getIoHandle()) == 0) {
686                     ALOGW("ioConfigChanged() closing unknown %s %d",
687                           event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->getIoHandle());
688                     break;
689                 }
690                 ALOGV("ioConfigChanged() %s %d closed",
691                       event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->getIoHandle());
692 
693                 mIoDescriptors.erase(ioDesc->getIoHandle());
694                 mAudioDeviceCallbacks.erase(ioDesc->getIoHandle());
695             }
696                 break;
697 
698             case AUDIO_OUTPUT_CONFIG_CHANGED:
699             case AUDIO_INPUT_CONFIG_CHANGED: {
700                 sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->getIoHandle());
701                 if (oldDesc == 0) {
702                     ALOGW("ioConfigChanged() modifying unknown %s! %d",
703                           event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input",
704                           ioDesc->getIoHandle());
705                     break;
706                 }
707 
708                 deviceId = oldDesc->getDeviceId();
709                 mIoDescriptors[ioDesc->getIoHandle()] = ioDesc;
710 
711                 if (deviceId != ioDesc->getDeviceId()) {
712                     deviceId = ioDesc->getDeviceId();
713                     auto it = mAudioDeviceCallbacks.find(ioDesc->getIoHandle());
714                     if (it != mAudioDeviceCallbacks.end()) {
715                         callbacks = it->second;
716                     }
717                 }
718                 ALOGV("ioConfigChanged() new config for %s %s",
719                       event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input",
720                       ioDesc->toDebugString().c_str());
721 
722             }
723                 break;
724             case AUDIO_CLIENT_STARTED: {
725                 sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->getIoHandle());
726                 if (oldDesc == 0) {
727                     ALOGW("ioConfigChanged() start client on unknown io! %d",
728                             ioDesc->getIoHandle());
729                     break;
730                 }
731                 ALOGV("ioConfigChanged() AUDIO_CLIENT_STARTED  io %d port %d num callbacks %zu",
732                       ioDesc->getIoHandle(), ioDesc->getPortId(), mAudioDeviceCallbacks.size());
733                 oldDesc->setPatch(ioDesc->getPatch());
734                 auto it = mAudioDeviceCallbacks.find(ioDesc->getIoHandle());
735                 if (it != mAudioDeviceCallbacks.end()) {
736                     auto cbks = it->second;
737                     auto it2 = cbks.find(ioDesc->getPortId());
738                     if (it2 != cbks.end()) {
739                         callbacks.emplace(ioDesc->getPortId(), it2->second);
740                         deviceId = oldDesc->getDeviceId();
741                     }
742                 }
743             }
744                 break;
745         }
746 
747         for (auto wpCbk : callbacks) {
748             sp<AudioDeviceCallback> spCbk = wpCbk.second.promote();
749             if (spCbk != nullptr) {
750                 callbacksToCall.push_back(spCbk);
751             }
752         }
753     }
754 
755     // Callbacks must be called without mMutex held. May lead to dead lock if calling for
756     // example getRoutedDevice that updates the device and tries to acquire mMutex.
757     for (auto cb  : callbacksToCall) {
758         // If callbacksToCall is not empty, it implies ioDesc->getIoHandle() and deviceId are valid
759         cb->onAudioDeviceUpdate(ioDesc->getIoHandle(), deviceId);
760     }
761 
762     return Status::ok();
763 }
764 
onSupportedLatencyModesChanged(int output,const std::vector<media::audio::common::AudioLatencyMode> & latencyModes)765 Status AudioSystem::AudioFlingerClient::onSupportedLatencyModesChanged(
766         int output, const std::vector<media::audio::common::AudioLatencyMode>& latencyModes) {
767     audio_io_handle_t outputLegacy = VALUE_OR_RETURN_BINDER_STATUS(
768             aidl2legacy_int32_t_audio_io_handle_t(output));
769     std::vector<audio_latency_mode_t> modesLegacy = VALUE_OR_RETURN_BINDER_STATUS(
770             convertContainer<std::vector<audio_latency_mode_t>>(
771                     latencyModes, aidl2legacy_AudioLatencyMode_audio_latency_mode_t));
772 
773     std::vector<sp<SupportedLatencyModesCallback>> callbacks;
774     {
775         std::lock_guard _l(mMutex);
776         for (auto callback : mSupportedLatencyModesCallbacks) {
777             if (auto ref = callback.promote(); ref != nullptr) {
778                 callbacks.push_back(ref);
779             }
780         }
781     }
782     for (const auto& callback : callbacks) {
783         callback->onSupportedLatencyModesChanged(outputLegacy, modesLegacy);
784     }
785 
786     return Status::ok();
787 }
788 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * buffSize)789 status_t AudioSystem::AudioFlingerClient::getInputBufferSize(
790         uint32_t sampleRate, audio_format_t format,
791         audio_channel_mask_t channelMask, size_t* buffSize) {
792     const sp<IAudioFlinger> af = get_audio_flinger();
793     if (af == 0) {
794         return PERMISSION_DENIED;
795     }
796     std::lock_guard _l(mMutex);
797     // Do we have a stale mInBuffSize or are we requesting the input buffer size for new values
798     if ((mInBuffSize == 0) || (sampleRate != mInSamplingRate) || (format != mInFormat)
799         || (channelMask != mInChannelMask)) {
800         size_t inBuffSize = af->getInputBufferSize(sampleRate, format, channelMask);
801         if (inBuffSize == 0) {
802             ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %#x channelMask %#x",
803                   sampleRate, format, channelMask);
804             return BAD_VALUE;
805         }
806         // A benign race is possible here: we could overwrite a fresher cache entry
807         // save the request params
808         mInSamplingRate = sampleRate;
809         mInFormat = format;
810         mInChannelMask = channelMask;
811 
812         mInBuffSize = inBuffSize;
813     }
814 
815     *buffSize = mInBuffSize;
816 
817     return NO_ERROR;
818 }
819 
820 sp<AudioIoDescriptor>
getIoDescriptor_l(audio_io_handle_t ioHandle)821 AudioSystem::AudioFlingerClient::getIoDescriptor_l(audio_io_handle_t ioHandle) {
822     if (const auto it = mIoDescriptors.find(ioHandle);
823         it != mIoDescriptors.end()) {
824         return it->second;
825     }
826     return {};
827 }
828 
getIoDescriptor(audio_io_handle_t ioHandle)829 sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor(audio_io_handle_t ioHandle) {
830     std::lock_guard _l(mMutex);
831     return getIoDescriptor_l(ioHandle);
832 }
833 
addAudioDeviceCallback(const wp<AudioDeviceCallback> & callback,audio_io_handle_t audioIo,audio_port_handle_t portId)834 status_t AudioSystem::AudioFlingerClient::addAudioDeviceCallback(
835         const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo,
836         audio_port_handle_t portId) {
837     ALOGV("%s audioIo %d portId %d", __func__, audioIo, portId);
838     std::lock_guard _l(mMutex);
839     auto& callbacks = mAudioDeviceCallbacks.emplace(
840             audioIo,
841             std::map<audio_port_handle_t, wp<AudioDeviceCallback>>()).first->second;
842     auto result = callbacks.try_emplace(portId, callback);
843     if (!result.second) {
844         return INVALID_OPERATION;
845     }
846     return NO_ERROR;
847 }
848 
removeAudioDeviceCallback(const wp<AudioDeviceCallback> & callback __unused,audio_io_handle_t audioIo,audio_port_handle_t portId)849 status_t AudioSystem::AudioFlingerClient::removeAudioDeviceCallback(
850         const wp<AudioDeviceCallback>& callback __unused, audio_io_handle_t audioIo,
851         audio_port_handle_t portId) {
852     ALOGV("%s audioIo %d portId %d", __func__, audioIo, portId);
853     std::lock_guard _l(mMutex);
854     auto it = mAudioDeviceCallbacks.find(audioIo);
855     if (it == mAudioDeviceCallbacks.end()) {
856         return INVALID_OPERATION;
857     }
858     if (it->second.erase(portId) == 0) {
859         return INVALID_OPERATION;
860     }
861     if (it->second.size() == 0) {
862         mAudioDeviceCallbacks.erase(audioIo);
863     }
864     return NO_ERROR;
865 }
866 
addSupportedLatencyModesCallback(const sp<SupportedLatencyModesCallback> & callback)867 status_t AudioSystem::AudioFlingerClient::addSupportedLatencyModesCallback(
868         const sp<SupportedLatencyModesCallback>& callback) {
869     std::lock_guard _l(mMutex);
870     if (std::find(mSupportedLatencyModesCallbacks.begin(),
871                   mSupportedLatencyModesCallbacks.end(),
872                   callback) != mSupportedLatencyModesCallbacks.end()) {
873         return INVALID_OPERATION;
874     }
875     mSupportedLatencyModesCallbacks.push_back(callback);
876     return NO_ERROR;
877 }
878 
removeSupportedLatencyModesCallback(const sp<SupportedLatencyModesCallback> & callback)879 status_t AudioSystem::AudioFlingerClient::removeSupportedLatencyModesCallback(
880         const sp<SupportedLatencyModesCallback>& callback) {
881     std::lock_guard _l(mMutex);
882     auto it = std::find(mSupportedLatencyModesCallbacks.begin(),
883                                  mSupportedLatencyModesCallbacks.end(),
884                                  callback);
885     if (it == mSupportedLatencyModesCallbacks.end()) {
886         return INVALID_OPERATION;
887     }
888     mSupportedLatencyModesCallbacks.erase(it);
889     return NO_ERROR;
890 }
891 
addErrorCallback(audio_error_callback cb)892 /* static */ uintptr_t AudioSystem::addErrorCallback(audio_error_callback cb) {
893     std::lock_guard _l(gErrorCallbacksMutex);
894     gAudioErrorCallbacks.insert(cb);
895     return reinterpret_cast<uintptr_t>(cb);
896 }
897 
removeErrorCallback(uintptr_t cb)898 /* static */ void AudioSystem::removeErrorCallback(uintptr_t cb) {
899     std::lock_guard _l(gErrorCallbacksMutex);
900     gAudioErrorCallbacks.erase(reinterpret_cast<audio_error_callback>(cb));
901 }
902 
reportError(status_t err)903 /* static */ void AudioSystem::reportError(status_t err) {
904     std::lock_guard _l(gErrorCallbacksMutex);
905     for (auto callback : gAudioErrorCallbacks) {
906         callback(err);
907     }
908 }
909 
setDynPolicyCallback(dynamic_policy_callback cb)910 /*static*/ void AudioSystem::setDynPolicyCallback(dynamic_policy_callback cb) {
911     std::lock_guard _l(gMutex);
912     gDynPolicyCallback = cb;
913 }
914 
setRecordConfigCallback(record_config_callback cb)915 /*static*/ void AudioSystem::setRecordConfigCallback(record_config_callback cb) {
916     std::lock_guard _l(gMutex);
917     gRecordConfigCallback = cb;
918 }
919 
setRoutingCallback(routing_callback cb)920 /*static*/ void AudioSystem::setRoutingCallback(routing_callback cb) {
921     std::lock_guard _l(gMutex);
922     gRoutingCallback = cb;
923 }
924 
setVolInitReqCallback(vol_range_init_req_callback cb)925 /*static*/ void AudioSystem::setVolInitReqCallback(vol_range_init_req_callback cb) {
926     std::lock_guard _l(gMutex);
927     gVolRangeInitReqCallback = cb;
928 }
929 
930 struct AudioPolicyTraits {
onServiceCreateandroid::AudioPolicyTraits931     static void onServiceCreate(const sp<IAudioPolicyService>& ap,
932             const sp<AudioSystem::AudioPolicyServiceClient>& apc) {
933         const int64_t token = IPCThreadState::self()->clearCallingIdentity();
934         ap->registerClient(apc);
935         ap->setAudioPortCallbacksEnabled(apc->isAudioPortCbEnabled());
936         ap->setAudioVolumeGroupCallbacksEnabled(apc->isAudioVolumeGroupCbEnabled());
937         IPCThreadState::self()->restoreCallingIdentity(token);
938     }
939 
onClearServiceandroid::AudioPolicyTraits940     static void onClearService(const sp<AudioSystem::AudioPolicyServiceClient>&) {}
941 
942     static constexpr const char *SERVICE_NAME = "media.audio_policy";
943 };
944 
945 [[clang::no_destroy]] static constinit ServiceHandler<IAudioPolicyService,
946         AudioSystem::AudioPolicyServiceClient, IAudioPolicyService,
947         AudioPolicyTraits> gAudioPolicyServiceHandler;
948 
setLocalAudioPolicyService(const sp<IAudioPolicyService> & aps)949 status_t AudioSystem::setLocalAudioPolicyService(const sp<IAudioPolicyService>& aps) {
950     return gAudioPolicyServiceHandler.setLocalService(aps);
951 }
952 
get_audio_policy_service()953 sp<IAudioPolicyService> AudioSystem::get_audio_policy_service() {
954     return gAudioPolicyServiceHandler.getService();
955 }
956 
clearAudioPolicyService()957 void AudioSystem::clearAudioPolicyService() {
958     gAudioPolicyServiceHandler.clearService();
959 }
960 
disableThreadPool()961 void AudioSystem::disableThreadPool() {
962     gAudioFlingerServiceHandler.disableThreadPool();
963     gAudioPolicyServiceHandler.disableThreadPool();
964 }
965 
966 // ---------------------------------------------------------------------------
967 
onNewAudioModulesAvailable()968 void AudioSystem::onNewAudioModulesAvailable() {
969     const sp<IAudioPolicyService> aps = get_audio_policy_service();
970     if (aps == 0) return;
971     aps->onNewAudioModulesAvailable();
972 }
973 
setDeviceConnectionState(audio_policy_dev_state_t state,const android::media::audio::common::AudioPort & port,audio_format_t encodedFormat)974 status_t AudioSystem::setDeviceConnectionState(audio_policy_dev_state_t state,
975                                                const android::media::audio::common::AudioPort& port,
976                                                audio_format_t encodedFormat) {
977     const sp<IAudioPolicyService> aps = get_audio_policy_service();
978 
979     if (aps == 0) return PERMISSION_DENIED;
980 
981     return statusTFromBinderStatus(
982             aps->setDeviceConnectionState(
983                     VALUE_OR_RETURN_STATUS(
984                             legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState(state)),
985                     port,
986                     VALUE_OR_RETURN_STATUS(
987                             legacy2aidl_audio_format_t_AudioFormatDescription(encodedFormat))));
988 }
989 
getDeviceConnectionState(audio_devices_t device,const char * device_address)990 audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t device,
991                                                                const char* device_address) {
992     const sp<IAudioPolicyService> aps = get_audio_policy_service();
993     if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
994 
995     auto result = [&]() -> ConversionResult<audio_policy_dev_state_t> {
996         AudioDevice deviceAidl = VALUE_OR_RETURN(
997                 legacy2aidl_audio_device_AudioDevice(device, device_address));
998 
999         media::AudioPolicyDeviceState result;
1000         RETURN_IF_ERROR(statusTFromBinderStatus(
1001                 aps->getDeviceConnectionState(deviceAidl, &result)));
1002 
1003         return aidl2legacy_AudioPolicyDeviceState_audio_policy_dev_state_t(result);
1004     }();
1005     return result.value_or(AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
1006 }
1007 
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name,audio_format_t encodedFormat)1008 status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device,
1009                                                const char* device_address,
1010                                                const char* device_name,
1011                                                audio_format_t encodedFormat) {
1012     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1013     const char* address = "";
1014     const char* name = "";
1015 
1016     if (aps == 0) return PERMISSION_DENIED;
1017 
1018     if (device_address != NULL) {
1019         address = device_address;
1020     }
1021     if (device_name != NULL) {
1022         name = device_name;
1023     }
1024 
1025     AudioDevice deviceAidl = VALUE_OR_RETURN_STATUS(
1026             legacy2aidl_audio_device_AudioDevice(device, address));
1027 
1028     return statusTFromBinderStatus(
1029             aps->handleDeviceConfigChange(deviceAidl, name, VALUE_OR_RETURN_STATUS(
1030                     legacy2aidl_audio_format_t_AudioFormatDescription(encodedFormat))));
1031 }
1032 
setPhoneState(audio_mode_t state,uid_t uid)1033 status_t AudioSystem::setPhoneState(audio_mode_t state, uid_t uid) {
1034     if (uint32_t(state) >= AUDIO_MODE_CNT) return BAD_VALUE;
1035     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1036     if (aps == 0) return PERMISSION_DENIED;
1037 
1038     return statusTFromBinderStatus(aps->setPhoneState(
1039             VALUE_OR_RETURN_STATUS(legacy2aidl_audio_mode_t_AudioMode(state)),
1040             VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid))));
1041 }
1042 
1043 status_t
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)1044 AudioSystem::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config) {
1045     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1046     if (aps == 0) return PERMISSION_DENIED;
1047 
1048     return statusTFromBinderStatus(
1049             aps->setForceUse(
1050                     VALUE_OR_RETURN_STATUS(
1051                             legacy2aidl_audio_policy_force_use_t_AudioPolicyForceUse(usage)),
1052                     VALUE_OR_RETURN_STATUS(
1053                             legacy2aidl_audio_policy_forced_cfg_t_AudioPolicyForcedConfig(
1054                                     config))));
1055 }
1056 
getForceUse(audio_policy_force_use_t usage)1057 audio_policy_forced_cfg_t AudioSystem::getForceUse(audio_policy_force_use_t usage) {
1058     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1059     if (aps == 0) return AUDIO_POLICY_FORCE_NONE;
1060 
1061     auto result = [&]() -> ConversionResult<audio_policy_forced_cfg_t> {
1062         media::AudioPolicyForceUse usageAidl = VALUE_OR_RETURN(
1063                 legacy2aidl_audio_policy_force_use_t_AudioPolicyForceUse(usage));
1064         media::AudioPolicyForcedConfig configAidl;
1065         RETURN_IF_ERROR(statusTFromBinderStatus(
1066                 aps->getForceUse(usageAidl, &configAidl)));
1067         return aidl2legacy_AudioPolicyForcedConfig_audio_policy_forced_cfg_t(configAidl);
1068     }();
1069 
1070     return result.value_or(AUDIO_POLICY_FORCE_NONE);
1071 }
1072 
1073 
getOutput(audio_stream_type_t stream)1074 audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream) {
1075     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1076     if (aps == 0) return AUDIO_IO_HANDLE_NONE;
1077 
1078     auto result = [&]() -> ConversionResult<audio_io_handle_t> {
1079         AudioStreamType streamAidl = VALUE_OR_RETURN(
1080                 legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1081         int32_t outputAidl;
1082         RETURN_IF_ERROR(
1083                 statusTFromBinderStatus(aps->getOutput(streamAidl, &outputAidl)));
1084         return aidl2legacy_int32_t_audio_io_handle_t(outputAidl);
1085     }();
1086 
1087     return result.value_or(AUDIO_IO_HANDLE_NONE);
1088 }
1089 
getOutputForAttr(audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,const AttributionSourceState & attributionSource,audio_config_t * config,audio_output_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId,std::vector<audio_io_handle_t> * secondaryOutputs,bool * isSpatialized,bool * isBitPerfect)1090 status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr,
1091                                        audio_io_handle_t* output,
1092                                        audio_session_t session,
1093                                        audio_stream_type_t* stream,
1094                                        const AttributionSourceState& attributionSource,
1095                                        audio_config_t* config,
1096                                        audio_output_flags_t flags,
1097                                        audio_port_handle_t* selectedDeviceId,
1098                                        audio_port_handle_t* portId,
1099                                        std::vector<audio_io_handle_t>* secondaryOutputs,
1100                                        bool *isSpatialized,
1101                                        bool *isBitPerfect) {
1102     if (attr == nullptr) {
1103         ALOGE("%s NULL audio attributes", __func__);
1104         return BAD_VALUE;
1105     }
1106     if (output == nullptr) {
1107         ALOGE("%s NULL output - shouldn't happen", __func__);
1108         return BAD_VALUE;
1109     }
1110     if (selectedDeviceId == nullptr) {
1111         ALOGE("%s NULL selectedDeviceId - shouldn't happen", __func__);
1112         return BAD_VALUE;
1113     }
1114     if (portId == nullptr) {
1115         ALOGE("%s NULL portId - shouldn't happen", __func__);
1116         return BAD_VALUE;
1117     }
1118     if (secondaryOutputs == nullptr) {
1119         ALOGE("%s NULL secondaryOutputs - shouldn't happen", __func__);
1120         return BAD_VALUE;
1121     }
1122 
1123     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1124     if (aps == 0) return NO_INIT;
1125 
1126     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
1127             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
1128     int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session));
1129     AudioConfig configAidl = VALUE_OR_RETURN_STATUS(
1130             legacy2aidl_audio_config_t_AudioConfig(*config, false /*isInput*/));
1131     int32_t flagsAidl = VALUE_OR_RETURN_STATUS(
1132             legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
1133     int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS(
1134             legacy2aidl_audio_port_handle_t_int32_t(*selectedDeviceId));
1135 
1136     media::GetOutputForAttrResponse responseAidl;
1137 
1138     status_t status = statusTFromBinderStatus(
1139             aps->getOutputForAttr(attrAidl, sessionAidl, attributionSource, configAidl, flagsAidl,
1140                                   selectedDeviceIdAidl, &responseAidl));
1141     if (status != NO_ERROR) {
1142         config->format = VALUE_OR_RETURN_STATUS(
1143             aidl2legacy_AudioFormatDescription_audio_format_t(responseAidl.configBase.format));
1144         config->channel_mask = VALUE_OR_RETURN_STATUS(
1145             aidl2legacy_AudioChannelLayout_audio_channel_mask_t(
1146                     responseAidl.configBase.channelMask, false /*isInput*/));
1147         config->sample_rate = responseAidl.configBase.sampleRate;
1148         return status;
1149     }
1150 
1151     *output = VALUE_OR_RETURN_STATUS(
1152             aidl2legacy_int32_t_audio_io_handle_t(responseAidl.output));
1153 
1154     if (stream != nullptr) {
1155         *stream = VALUE_OR_RETURN_STATUS(
1156                 aidl2legacy_AudioStreamType_audio_stream_type_t(responseAidl.stream));
1157     }
1158     *selectedDeviceId = VALUE_OR_RETURN_STATUS(
1159             aidl2legacy_int32_t_audio_port_handle_t(responseAidl.selectedDeviceId));
1160     *portId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(responseAidl.portId));
1161     *secondaryOutputs = VALUE_OR_RETURN_STATUS(convertContainer<std::vector<audio_io_handle_t>>(
1162             responseAidl.secondaryOutputs, aidl2legacy_int32_t_audio_io_handle_t));
1163     *isSpatialized = responseAidl.isSpatialized;
1164     *isBitPerfect = responseAidl.isBitPerfect;
1165     *attr = VALUE_OR_RETURN_STATUS(
1166             aidl2legacy_AudioAttributes_audio_attributes_t(responseAidl.attr));
1167 
1168     return OK;
1169 }
1170 
startOutput(audio_port_handle_t portId)1171 status_t AudioSystem::startOutput(audio_port_handle_t portId) {
1172     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1173     if (aps == 0) return PERMISSION_DENIED;
1174 
1175     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
1176     return statusTFromBinderStatus(aps->startOutput(portIdAidl));
1177 }
1178 
stopOutput(audio_port_handle_t portId)1179 status_t AudioSystem::stopOutput(audio_port_handle_t portId) {
1180     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1181     if (aps == 0) return PERMISSION_DENIED;
1182 
1183     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
1184     return statusTFromBinderStatus(aps->stopOutput(portIdAidl));
1185 }
1186 
releaseOutput(audio_port_handle_t portId)1187 void AudioSystem::releaseOutput(audio_port_handle_t portId) {
1188     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1189     if (aps == 0) return;
1190 
1191     auto status = [&]() -> status_t {
1192         int32_t portIdAidl = VALUE_OR_RETURN_STATUS(
1193                 legacy2aidl_audio_port_handle_t_int32_t(portId));
1194         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(aps->releaseOutput(portIdAidl)));
1195         return OK;
1196     }();
1197 
1198     // Ignore status.
1199     (void) status;
1200 }
1201 
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_unique_id_t riid,audio_session_t session,const AttributionSourceState & attributionSource,audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId)1202 status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr,
1203                                       audio_io_handle_t* input,
1204                                       audio_unique_id_t riid,
1205                                       audio_session_t session,
1206                                       const AttributionSourceState &attributionSource,
1207                                       audio_config_base_t* config,
1208                                       audio_input_flags_t flags,
1209                                       audio_port_handle_t* selectedDeviceId,
1210                                       audio_port_handle_t* portId) {
1211     if (attr == NULL) {
1212         ALOGE("getInputForAttr NULL attr - shouldn't happen");
1213         return BAD_VALUE;
1214     }
1215     if (input == NULL) {
1216         ALOGE("getInputForAttr NULL input - shouldn't happen");
1217         return BAD_VALUE;
1218     }
1219     if (selectedDeviceId == NULL) {
1220         ALOGE("getInputForAttr NULL selectedDeviceId - shouldn't happen");
1221         return BAD_VALUE;
1222     }
1223     if (portId == NULL) {
1224         ALOGE("getInputForAttr NULL portId - shouldn't happen");
1225         return BAD_VALUE;
1226     }
1227 
1228     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1229     if (aps == 0) return NO_INIT;
1230 
1231     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
1232             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
1233     int32_t inputAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(*input));
1234     int32_t riidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_unique_id_t_int32_t(riid));
1235     int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session));
1236     AudioConfigBase configAidl = VALUE_OR_RETURN_STATUS(
1237             legacy2aidl_audio_config_base_t_AudioConfigBase(*config, true /*isInput*/));
1238     int32_t flagsAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags));
1239     int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS(
1240             legacy2aidl_audio_port_handle_t_int32_t(*selectedDeviceId));
1241 
1242     media::GetInputForAttrResponse response;
1243 
1244     status_t status = statusTFromBinderStatus(
1245             aps->getInputForAttr(attrAidl, inputAidl, riidAidl, sessionAidl, attributionSource,
1246                 configAidl, flagsAidl, selectedDeviceIdAidl, &response));
1247     if (status != NO_ERROR) {
1248         *config = VALUE_OR_RETURN_STATUS(
1249                 aidl2legacy_AudioConfigBase_audio_config_base_t(response.config, true /*isInput*/));
1250         return status;
1251     }
1252 
1253     *input = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(response.input));
1254     *selectedDeviceId = VALUE_OR_RETURN_STATUS(
1255             aidl2legacy_int32_t_audio_port_handle_t(response.selectedDeviceId));
1256     *portId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(response.portId));
1257 
1258     return OK;
1259 }
1260 
startInput(audio_port_handle_t portId)1261 status_t AudioSystem::startInput(audio_port_handle_t portId) {
1262     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1263     if (aps == 0) return PERMISSION_DENIED;
1264 
1265     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
1266     return statusTFromBinderStatus(aps->startInput(portIdAidl));
1267 }
1268 
stopInput(audio_port_handle_t portId)1269 status_t AudioSystem::stopInput(audio_port_handle_t portId) {
1270     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1271     if (aps == 0) return PERMISSION_DENIED;
1272 
1273     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
1274     return statusTFromBinderStatus(aps->stopInput(portIdAidl));
1275 }
1276 
releaseInput(audio_port_handle_t portId)1277 void AudioSystem::releaseInput(audio_port_handle_t portId) {
1278     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1279     if (aps == 0) return;
1280 
1281     auto status = [&]() -> status_t {
1282         int32_t portIdAidl = VALUE_OR_RETURN_STATUS(
1283                 legacy2aidl_audio_port_handle_t_int32_t(portId));
1284         RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(aps->releaseInput(portIdAidl)));
1285         return OK;
1286     }();
1287 
1288     // Ignore status.
1289     (void) status;
1290 }
1291 
setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,const char * address,bool enabled,audio_stream_type_t streamToDriveAbs)1292 status_t AudioSystem::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
1293                                                      const char *address,
1294                                                      bool enabled,
1295                                                      audio_stream_type_t streamToDriveAbs) {
1296     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1297     if (aps == nullptr) return PERMISSION_DENIED;
1298 
1299     AudioDevice deviceAidl = VALUE_OR_RETURN_STATUS(
1300             legacy2aidl_audio_device_AudioDevice(deviceType, address));
1301     AudioStreamType streamToDriveAbsAidl = VALUE_OR_RETURN_STATUS(
1302             legacy2aidl_audio_stream_type_t_AudioStreamType(streamToDriveAbs));
1303     return statusTFromBinderStatus(
1304             aps->setDeviceAbsoluteVolumeEnabled(deviceAidl, enabled, streamToDriveAbsAidl));
1305 }
1306 
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)1307 status_t AudioSystem::initStreamVolume(audio_stream_type_t stream,
1308                                        int indexMin,
1309                                        int indexMax) {
1310     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1311     if (aps == 0) return PERMISSION_DENIED;
1312 
1313     AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS(
1314             legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1315     int32_t indexMinAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(indexMin));
1316     int32_t indexMaxAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(indexMax));
1317     status_t status = statusTFromBinderStatus(
1318             aps->initStreamVolume(streamAidl, indexMinAidl, indexMaxAidl));
1319     if (status == DEAD_OBJECT) {
1320         // This is a critical operation since w/o proper stream volumes no audio
1321         // will be heard. Make sure we recover from a failure in any case.
1322         ALOGE("Received DEAD_OBJECT from APS, clearing the client");
1323         clearAudioPolicyService();
1324     }
1325     return status;
1326 }
1327 
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)1328 status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
1329                                            int index,
1330                                            audio_devices_t device) {
1331     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1332     if (aps == 0) return PERMISSION_DENIED;
1333 
1334     AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS(
1335             legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1336     int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(index));
1337     AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS(
1338             legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
1339     return statusTFromBinderStatus(
1340             aps->setStreamVolumeIndex(streamAidl, deviceAidl, indexAidl));
1341 }
1342 
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)1343 status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
1344                                            int* index,
1345                                            audio_devices_t device) {
1346     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1347     if (aps == 0) return PERMISSION_DENIED;
1348 
1349     AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS(
1350             legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1351     AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS(
1352             legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
1353     int32_t indexAidl;
1354     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1355             aps->getStreamVolumeIndex(streamAidl, deviceAidl, &indexAidl)));
1356     if (index != nullptr) {
1357         *index = VALUE_OR_RETURN_STATUS(convertIntegral<int>(indexAidl));
1358     }
1359     return OK;
1360 }
1361 
setVolumeIndexForAttributes(const audio_attributes_t & attr,int index,audio_devices_t device)1362 status_t AudioSystem::setVolumeIndexForAttributes(const audio_attributes_t& attr,
1363                                                   int index,
1364                                                   audio_devices_t device) {
1365     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1366     if (aps == 0) return PERMISSION_DENIED;
1367 
1368     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
1369             legacy2aidl_audio_attributes_t_AudioAttributes(attr));
1370     int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(index));
1371     AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS(
1372             legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
1373     return statusTFromBinderStatus(
1374             aps->setVolumeIndexForAttributes(attrAidl, deviceAidl, indexAidl));
1375 }
1376 
getVolumeIndexForAttributes(const audio_attributes_t & attr,int & index,audio_devices_t device)1377 status_t AudioSystem::getVolumeIndexForAttributes(const audio_attributes_t& attr,
1378                                                   int& index,
1379                                                   audio_devices_t device) {
1380     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1381     if (aps == 0) return PERMISSION_DENIED;
1382 
1383     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
1384             legacy2aidl_audio_attributes_t_AudioAttributes(attr));
1385     AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS(
1386             legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
1387     int32_t indexAidl;
1388     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1389             aps->getVolumeIndexForAttributes(attrAidl, deviceAidl, &indexAidl)));
1390     index = VALUE_OR_RETURN_STATUS(convertIntegral<int>(indexAidl));
1391     return OK;
1392 }
1393 
getMaxVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)1394 status_t AudioSystem::getMaxVolumeIndexForAttributes(const audio_attributes_t& attr, int& index) {
1395     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1396     if (aps == 0) return PERMISSION_DENIED;
1397 
1398     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
1399             legacy2aidl_audio_attributes_t_AudioAttributes(attr));
1400     int32_t indexAidl;
1401     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1402             aps->getMaxVolumeIndexForAttributes(attrAidl, &indexAidl)));
1403     index = VALUE_OR_RETURN_STATUS(convertIntegral<int>(indexAidl));
1404     return OK;
1405 }
1406 
getMinVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)1407 status_t AudioSystem::getMinVolumeIndexForAttributes(const audio_attributes_t& attr, int& index) {
1408     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1409     if (aps == 0) return PERMISSION_DENIED;
1410 
1411     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
1412             legacy2aidl_audio_attributes_t_AudioAttributes(attr));
1413     int32_t indexAidl;
1414     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1415             aps->getMinVolumeIndexForAttributes(attrAidl, &indexAidl)));
1416     index = VALUE_OR_RETURN_STATUS(convertIntegral<int>(indexAidl));
1417     return OK;
1418 }
1419 
getStrategyForStream(audio_stream_type_t stream)1420 product_strategy_t AudioSystem::getStrategyForStream(audio_stream_type_t stream) {
1421     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1422     if (aps == 0) return PRODUCT_STRATEGY_NONE;
1423 
1424     auto result = [&]() -> ConversionResult<product_strategy_t> {
1425         AudioStreamType streamAidl = VALUE_OR_RETURN(
1426                 legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1427         int32_t resultAidl;
1428         RETURN_IF_ERROR(statusTFromBinderStatus(
1429                 aps->getStrategyForStream(streamAidl, &resultAidl)));
1430         return aidl2legacy_int32_t_product_strategy_t(resultAidl);
1431     }();
1432     return result.value_or(PRODUCT_STRATEGY_NONE);
1433 }
1434 
getDevicesForAttributes(const audio_attributes_t & aa,AudioDeviceTypeAddrVector * devices,bool forVolume)1435 status_t AudioSystem::getDevicesForAttributes(const audio_attributes_t& aa,
1436                                               AudioDeviceTypeAddrVector* devices,
1437                                               bool forVolume) {
1438     if (devices == nullptr) {
1439         return BAD_VALUE;
1440     }
1441     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1442     if (aps == 0) return PERMISSION_DENIED;
1443 
1444     media::audio::common::AudioAttributes aaAidl = VALUE_OR_RETURN_STATUS(
1445              legacy2aidl_audio_attributes_t_AudioAttributes(aa));
1446     std::vector<AudioDevice> retAidl;
1447     RETURN_STATUS_IF_ERROR(
1448             statusTFromBinderStatus(aps->getDevicesForAttributes(aaAidl, forVolume, &retAidl)));
1449     *devices = VALUE_OR_RETURN_STATUS(
1450             convertContainer<AudioDeviceTypeAddrVector>(
1451                     retAidl,
1452                     aidl2legacy_AudioDeviceTypeAddress));
1453     return OK;
1454 }
1455 
getOutputForEffect(const effect_descriptor_t * desc)1456 audio_io_handle_t AudioSystem::getOutputForEffect(const effect_descriptor_t* desc) {
1457     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1458     // FIXME change return type to status_t, and return PERMISSION_DENIED here
1459     if (aps == 0) return AUDIO_IO_HANDLE_NONE;
1460 
1461     auto result = [&]() -> ConversionResult<audio_io_handle_t> {
1462         media::EffectDescriptor descAidl = VALUE_OR_RETURN(
1463                 legacy2aidl_effect_descriptor_t_EffectDescriptor(*desc));
1464         int32_t retAidl;
1465         RETURN_IF_ERROR(
1466                 statusTFromBinderStatus(aps->getOutputForEffect(descAidl, &retAidl)));
1467         return aidl2legacy_int32_t_audio_io_handle_t(retAidl);
1468     }();
1469 
1470     return result.value_or(AUDIO_IO_HANDLE_NONE);
1471 }
1472 
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,product_strategy_t strategy,audio_session_t session,int id)1473 status_t AudioSystem::registerEffect(const effect_descriptor_t* desc,
1474                                      audio_io_handle_t io,
1475                                      product_strategy_t strategy,
1476                                      audio_session_t session,
1477                                      int id) {
1478     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1479     if (aps == 0) return PERMISSION_DENIED;
1480 
1481     media::EffectDescriptor descAidl = VALUE_OR_RETURN_STATUS(
1482             legacy2aidl_effect_descriptor_t_EffectDescriptor(*desc));
1483     int32_t ioAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(io));
1484     int32_t strategyAidl = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_product_strategy_t(strategy));
1485     int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session));
1486     int32_t idAidl = VALUE_OR_RETURN_STATUS(convertReinterpret<int32_t>(id));
1487     return statusTFromBinderStatus(
1488             aps->registerEffect(descAidl, ioAidl, strategyAidl, sessionAidl, idAidl));
1489 }
1490 
unregisterEffect(int id)1491 status_t AudioSystem::unregisterEffect(int id) {
1492     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1493     if (aps == 0) return PERMISSION_DENIED;
1494 
1495     int32_t idAidl = VALUE_OR_RETURN_STATUS(convertReinterpret<int32_t>(id));
1496     return statusTFromBinderStatus(
1497             aps->unregisterEffect(idAidl));
1498 }
1499 
setEffectEnabled(int id,bool enabled)1500 status_t AudioSystem::setEffectEnabled(int id, bool enabled) {
1501     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1502     if (aps == 0) return PERMISSION_DENIED;
1503 
1504     int32_t idAidl = VALUE_OR_RETURN_STATUS(convertReinterpret<int32_t>(id));
1505     return statusTFromBinderStatus(
1506             aps->setEffectEnabled(idAidl, enabled));
1507 }
1508 
moveEffectsToIo(const std::vector<int> & ids,audio_io_handle_t io)1509 status_t AudioSystem::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io) {
1510     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1511     if (aps == 0) return PERMISSION_DENIED;
1512 
1513     std::vector<int32_t> idsAidl = VALUE_OR_RETURN_STATUS(
1514             convertContainer<std::vector<int32_t>>(ids, convertReinterpret<int32_t, int>));
1515     int32_t ioAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(io));
1516     return statusTFromBinderStatus(aps->moveEffectsToIo(idsAidl, ioAidl));
1517 }
1518 
isStreamActive(audio_stream_type_t stream,bool * state,uint32_t inPastMs)1519 status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs) {
1520     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1521     if (aps == 0) return PERMISSION_DENIED;
1522     if (state == NULL) return BAD_VALUE;
1523 
1524     AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS(
1525             legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1526     int32_t inPastMsAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(inPastMs));
1527     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1528             aps->isStreamActive(streamAidl, inPastMsAidl, state)));
1529     return OK;
1530 }
1531 
isStreamActiveRemotely(audio_stream_type_t stream,bool * state,uint32_t inPastMs)1532 status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* state,
1533                                              uint32_t inPastMs) {
1534     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1535     if (aps == 0) return PERMISSION_DENIED;
1536     if (state == NULL) return BAD_VALUE;
1537 
1538     AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS(
1539             legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
1540     int32_t inPastMsAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(inPastMs));
1541     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1542             aps->isStreamActiveRemotely(streamAidl, inPastMsAidl, state)));
1543     return OK;
1544 }
1545 
isSourceActive(audio_source_t stream,bool * state)1546 status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state) {
1547     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1548     if (aps == 0) return PERMISSION_DENIED;
1549     if (state == NULL) return BAD_VALUE;
1550 
1551     AudioSource streamAidl = VALUE_OR_RETURN_STATUS(
1552             legacy2aidl_audio_source_t_AudioSource(stream));
1553     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1554             aps->isSourceActive(streamAidl, state)));
1555     return OK;
1556 }
1557 
getPrimaryOutputSamplingRate()1558 uint32_t AudioSystem::getPrimaryOutputSamplingRate() {
1559     const sp<IAudioFlinger> af = get_audio_flinger();
1560     if (af == 0) return 0;
1561     return af->getPrimaryOutputSamplingRate();
1562 }
1563 
getPrimaryOutputFrameCount()1564 size_t AudioSystem::getPrimaryOutputFrameCount() {
1565     const sp<IAudioFlinger> af = get_audio_flinger();
1566     if (af == 0) return 0;
1567     return af->getPrimaryOutputFrameCount();
1568 }
1569 
setLowRamDevice(bool isLowRamDevice,int64_t totalMemory)1570 status_t AudioSystem::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory) {
1571     const sp<IAudioFlinger> af = get_audio_flinger();
1572     if (af == 0) return PERMISSION_DENIED;
1573     return af->setLowRamDevice(isLowRamDevice, totalMemory);
1574 }
1575 
clearAudioConfigCache()1576 void AudioSystem::clearAudioConfigCache() {
1577     // called by restoreTrack_l(), which needs new IAudioFlinger and IAudioPolicyService instances
1578     ALOGV("clearAudioConfigCache()");
1579     gAudioFlingerServiceHandler.clearService();
1580     clearAudioPolicyService();
1581 }
1582 
setSupportedSystemUsages(const std::vector<audio_usage_t> & systemUsages)1583 status_t AudioSystem::setSupportedSystemUsages(const std::vector<audio_usage_t>& systemUsages) {
1584     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1585     if (aps == nullptr) return PERMISSION_DENIED;
1586 
1587     std::vector<AudioUsage> systemUsagesAidl = VALUE_OR_RETURN_STATUS(
1588             convertContainer<std::vector<AudioUsage>>(systemUsages,
1589                                                       legacy2aidl_audio_usage_t_AudioUsage));
1590     return statusTFromBinderStatus(aps->setSupportedSystemUsages(systemUsagesAidl));
1591 }
1592 
setAllowedCapturePolicy(uid_t uid,audio_flags_mask_t capturePolicy)1593 status_t AudioSystem::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy) {
1594     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1595     if (aps == nullptr) return PERMISSION_DENIED;
1596 
1597     int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid));
1598     int32_t capturePolicyAidl = VALUE_OR_RETURN_STATUS(
1599             legacy2aidl_audio_flags_mask_t_int32_t_mask(capturePolicy));
1600     return statusTFromBinderStatus(aps->setAllowedCapturePolicy(uidAidl, capturePolicyAidl));
1601 }
1602 
getOffloadSupport(const audio_offload_info_t & info)1603 audio_offload_mode_t AudioSystem::getOffloadSupport(const audio_offload_info_t& info) {
1604     ALOGV("%s", __func__);
1605     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1606     if (aps == 0) return AUDIO_OFFLOAD_NOT_SUPPORTED;
1607 
1608     auto result = [&]() -> ConversionResult<audio_offload_mode_t> {
1609         AudioOffloadInfo infoAidl = VALUE_OR_RETURN(
1610                 legacy2aidl_audio_offload_info_t_AudioOffloadInfo(info));
1611         media::AudioOffloadMode retAidl;
1612         RETURN_IF_ERROR(
1613                 statusTFromBinderStatus(aps->getOffloadSupport(infoAidl, &retAidl)));
1614         return aidl2legacy_AudioOffloadMode_audio_offload_mode_t(retAidl);
1615     }();
1616 
1617     return result.value_or(static_cast<audio_offload_mode_t>(0));
1618 }
1619 
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port_v7 * ports,unsigned int * generation)1620 status_t AudioSystem::listAudioPorts(audio_port_role_t role,
1621                                      audio_port_type_t type,
1622                                      unsigned int* num_ports,
1623                                      struct audio_port_v7* ports,
1624                                      unsigned int* generation) {
1625     if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
1626         generation == nullptr) {
1627         return BAD_VALUE;
1628     }
1629 
1630     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1631     if (aps == 0) return PERMISSION_DENIED;
1632 
1633     media::AudioPortRole roleAidl = VALUE_OR_RETURN_STATUS(
1634             legacy2aidl_audio_port_role_t_AudioPortRole(role));
1635     media::AudioPortType typeAidl = VALUE_OR_RETURN_STATUS(
1636             legacy2aidl_audio_port_type_t_AudioPortType(type));
1637     Int numPortsAidl;
1638     numPortsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(*num_ports));
1639     std::vector<media::AudioPortFw> portsAidl;
1640     int32_t generationAidl;
1641 
1642     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1643             aps->listAudioPorts(roleAidl, typeAidl, &numPortsAidl, &portsAidl, &generationAidl)));
1644     *num_ports = VALUE_OR_RETURN_STATUS(convertIntegral<unsigned int>(numPortsAidl.value));
1645     *generation = VALUE_OR_RETURN_STATUS(convertIntegral<unsigned int>(generationAidl));
1646     RETURN_STATUS_IF_ERROR(convertRange(portsAidl.begin(), portsAidl.end(), ports,
1647                                         aidl2legacy_AudioPortFw_audio_port_v7));
1648     return OK;
1649 }
1650 
listDeclaredDevicePorts(media::AudioPortRole role,std::vector<media::AudioPortFw> * result)1651 status_t AudioSystem::listDeclaredDevicePorts(media::AudioPortRole role,
1652                                               std::vector<media::AudioPortFw>* result) {
1653     if (result == nullptr) return BAD_VALUE;
1654     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1655     if (aps == 0) return PERMISSION_DENIED;
1656     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(aps->listDeclaredDevicePorts(role, result)));
1657     return OK;
1658 }
1659 
getAudioPort(struct audio_port_v7 * port)1660 status_t AudioSystem::getAudioPort(struct audio_port_v7* port) {
1661     if (port == nullptr) {
1662         return BAD_VALUE;
1663     }
1664     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1665     if (aps == 0) return PERMISSION_DENIED;
1666 
1667     media::AudioPortFw portAidl;
1668     RETURN_STATUS_IF_ERROR(
1669             statusTFromBinderStatus(aps->getAudioPort(port->id, &portAidl)));
1670     *port = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortFw_audio_port_v7(portAidl));
1671     return OK;
1672 }
1673 
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)1674 status_t AudioSystem::createAudioPatch(const struct audio_patch* patch,
1675                                        audio_patch_handle_t* handle) {
1676     if (patch == nullptr || handle == nullptr) {
1677         return BAD_VALUE;
1678     }
1679 
1680     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1681     if (aps == 0) return PERMISSION_DENIED;
1682 
1683     media::AudioPatchFw patchAidl = VALUE_OR_RETURN_STATUS(
1684             legacy2aidl_audio_patch_AudioPatchFw(*patch));
1685     int32_t handleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_patch_handle_t_int32_t(*handle));
1686     RETURN_STATUS_IF_ERROR(
1687             statusTFromBinderStatus(aps->createAudioPatch(patchAidl, handleAidl, &handleAidl)));
1688     *handle = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_patch_handle_t(handleAidl));
1689     return OK;
1690 }
1691 
releaseAudioPatch(audio_patch_handle_t handle)1692 status_t AudioSystem::releaseAudioPatch(audio_patch_handle_t handle) {
1693     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1694     if (aps == 0) return PERMISSION_DENIED;
1695 
1696     int32_t handleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_patch_handle_t_int32_t(handle));
1697     return statusTFromBinderStatus(aps->releaseAudioPatch(handleAidl));
1698 }
1699 
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)1700 status_t AudioSystem::listAudioPatches(unsigned int* num_patches,
1701                                        struct audio_patch* patches,
1702                                        unsigned int* generation) {
1703     if (num_patches == nullptr || (*num_patches != 0 && patches == nullptr) ||
1704         generation == nullptr) {
1705         return BAD_VALUE;
1706     }
1707 
1708     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1709     if (aps == 0) return PERMISSION_DENIED;
1710 
1711 
1712     Int numPatchesAidl;
1713     numPatchesAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(*num_patches));
1714     std::vector<media::AudioPatchFw> patchesAidl;
1715     int32_t generationAidl;
1716 
1717     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1718             aps->listAudioPatches(&numPatchesAidl, &patchesAidl, &generationAidl)));
1719     *num_patches = VALUE_OR_RETURN_STATUS(convertIntegral<unsigned int>(numPatchesAidl.value));
1720     *generation = VALUE_OR_RETURN_STATUS(convertIntegral<unsigned int>(generationAidl));
1721     RETURN_STATUS_IF_ERROR(convertRange(patchesAidl.begin(), patchesAidl.end(), patches,
1722                                         aidl2legacy_AudioPatchFw_audio_patch));
1723     return OK;
1724 }
1725 
setAudioPortConfig(const struct audio_port_config * config)1726 status_t AudioSystem::setAudioPortConfig(const struct audio_port_config* config) {
1727     if (config == nullptr) {
1728         return BAD_VALUE;
1729     }
1730 
1731     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1732     if (aps == 0) return PERMISSION_DENIED;
1733 
1734     media::AudioPortConfigFw configAidl = VALUE_OR_RETURN_STATUS(
1735             legacy2aidl_audio_port_config_AudioPortConfigFw(*config));
1736     return statusTFromBinderStatus(aps->setAudioPortConfig(configAidl));
1737 }
1738 
addAudioPortCallback(const sp<AudioPortCallback> & callback)1739 status_t AudioSystem::addAudioPortCallback(const sp<AudioPortCallback>& callback) {
1740     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1741     if (aps == 0) return PERMISSION_DENIED;
1742     const auto apc = gAudioPolicyServiceHandler.getClient();
1743     if (apc == nullptr) return NO_INIT;
1744 
1745     std::lock_guard _l(gApsCallbackMutex);
1746     const int ret = apc->addAudioPortCallback(callback);
1747     if (ret == 1) {
1748         aps->setAudioPortCallbacksEnabled(true);
1749     }
1750     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1751 }
1752 
1753 /*static*/
removeAudioPortCallback(const sp<AudioPortCallback> & callback)1754 status_t AudioSystem::removeAudioPortCallback(const sp<AudioPortCallback>& callback) {
1755     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1756     if (aps == 0) return PERMISSION_DENIED;
1757     const auto apc = gAudioPolicyServiceHandler.getClient();
1758     if (apc == nullptr) return NO_INIT;
1759 
1760     std::lock_guard _l(gApsCallbackMutex);
1761     const int ret = apc->removeAudioPortCallback(callback);
1762     if (ret == 0) {
1763         aps->setAudioPortCallbacksEnabled(false);
1764     }
1765     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1766 }
1767 
addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)1768 status_t AudioSystem::addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback) {
1769     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1770     if (aps == 0) return PERMISSION_DENIED;
1771     const auto apc = gAudioPolicyServiceHandler.getClient();
1772     if (apc == nullptr) return NO_INIT;
1773 
1774     std::lock_guard _l(gApsCallbackMutex);
1775     const int ret = apc->addAudioVolumeGroupCallback(callback);
1776     if (ret == 1) {
1777         aps->setAudioVolumeGroupCallbacksEnabled(true);
1778     }
1779     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1780 }
1781 
removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)1782 status_t AudioSystem::removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback) {
1783     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1784     if (aps == 0) return PERMISSION_DENIED;
1785     const auto apc = gAudioPolicyServiceHandler.getClient();
1786     if (apc == nullptr) return NO_INIT;
1787 
1788     std::lock_guard _l(gApsCallbackMutex);
1789     const int ret = apc->removeAudioVolumeGroupCallback(callback);
1790     if (ret == 0) {
1791         aps->setAudioVolumeGroupCallbacksEnabled(false);
1792     }
1793     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1794 }
1795 
addAudioDeviceCallback(const wp<AudioDeviceCallback> & callback,audio_io_handle_t audioIo,audio_port_handle_t portId)1796 status_t AudioSystem::addAudioDeviceCallback(
1797         const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo,
1798         audio_port_handle_t portId) {
1799     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1800     if (afc == 0) {
1801         return NO_INIT;
1802     }
1803     status_t status = afc->addAudioDeviceCallback(callback, audioIo, portId);
1804     if (status == NO_ERROR) {
1805         const sp<IAudioFlinger> af = get_audio_flinger();
1806         if (af != 0) {
1807             af->registerClient(afc);
1808         }
1809     }
1810     return status;
1811 }
1812 
removeAudioDeviceCallback(const wp<AudioDeviceCallback> & callback,audio_io_handle_t audioIo,audio_port_handle_t portId)1813 status_t AudioSystem::removeAudioDeviceCallback(
1814         const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo,
1815         audio_port_handle_t portId) {
1816     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1817     if (afc == 0) {
1818         return NO_INIT;
1819     }
1820     return afc->removeAudioDeviceCallback(callback, audioIo, portId);
1821 }
1822 
addSupportedLatencyModesCallback(const sp<SupportedLatencyModesCallback> & callback)1823 status_t AudioSystem::addSupportedLatencyModesCallback(
1824         const sp<SupportedLatencyModesCallback>& callback) {
1825     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1826     if (afc == 0) {
1827         return NO_INIT;
1828     }
1829     return afc->addSupportedLatencyModesCallback(callback);
1830 }
1831 
removeSupportedLatencyModesCallback(const sp<SupportedLatencyModesCallback> & callback)1832 status_t AudioSystem::removeSupportedLatencyModesCallback(
1833         const sp<SupportedLatencyModesCallback>& callback) {
1834     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1835     if (afc == 0) {
1836         return NO_INIT;
1837     }
1838     return afc->removeSupportedLatencyModesCallback(callback);
1839 }
1840 
getDeviceIdForIo(audio_io_handle_t audioIo)1841 audio_port_handle_t AudioSystem::getDeviceIdForIo(audio_io_handle_t audioIo) {
1842     const sp<IAudioFlinger> af = get_audio_flinger();
1843     if (af == 0) return PERMISSION_DENIED;
1844     const sp<AudioIoDescriptor> desc = getIoDescriptor(audioIo);
1845     if (desc == 0) {
1846         return AUDIO_PORT_HANDLE_NONE;
1847     }
1848     return desc->getDeviceId();
1849 }
1850 
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)1851 status_t AudioSystem::acquireSoundTriggerSession(audio_session_t* session,
1852                                                  audio_io_handle_t* ioHandle,
1853                                                  audio_devices_t* device) {
1854     if (session == nullptr || ioHandle == nullptr || device == nullptr) {
1855         return BAD_VALUE;
1856     }
1857     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1858     if (aps == 0) return PERMISSION_DENIED;
1859 
1860     media::SoundTriggerSession retAidl;
1861     RETURN_STATUS_IF_ERROR(
1862             statusTFromBinderStatus(aps->acquireSoundTriggerSession(&retAidl)));
1863     *session = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_session_t(retAidl.session));
1864     *ioHandle = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(retAidl.ioHandle));
1865     *device = VALUE_OR_RETURN_STATUS(
1866             aidl2legacy_AudioDeviceDescription_audio_devices_t(retAidl.device));
1867     return OK;
1868 }
1869 
releaseSoundTriggerSession(audio_session_t session)1870 status_t AudioSystem::releaseSoundTriggerSession(audio_session_t session) {
1871     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1872     if (aps == 0) return PERMISSION_DENIED;
1873 
1874     int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session));
1875     return statusTFromBinderStatus(aps->releaseSoundTriggerSession(sessionAidl));
1876 }
1877 
getPhoneState()1878 audio_mode_t AudioSystem::getPhoneState() {
1879     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1880     if (aps == 0) return AUDIO_MODE_INVALID;
1881 
1882     auto result = [&]() -> ConversionResult<audio_mode_t> {
1883         media::audio::common::AudioMode retAidl;
1884         RETURN_IF_ERROR(statusTFromBinderStatus(aps->getPhoneState(&retAidl)));
1885         return aidl2legacy_AudioMode_audio_mode_t(retAidl);
1886     }();
1887 
1888     return result.value_or(AUDIO_MODE_INVALID);
1889 }
1890 
registerPolicyMixes(const Vector<AudioMix> & mixes,bool registration)1891 status_t AudioSystem::registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration) {
1892     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1893     if (aps == 0) return PERMISSION_DENIED;
1894 
1895     size_t mixesSize = std::min(mixes.size(), size_t{MAX_MIXES_PER_POLICY});
1896     std::vector<media::AudioMix> mixesAidl;
1897     RETURN_STATUS_IF_ERROR(
1898             convertRange(mixes.begin(), mixes.begin() + mixesSize, std::back_inserter(mixesAidl),
1899                          legacy2aidl_AudioMix));
1900     return statusTFromBinderStatus(aps->registerPolicyMixes(mixesAidl, registration));
1901 }
1902 
getRegisteredPolicyMixes(std::vector<AudioMix> & mixes)1903 status_t AudioSystem::getRegisteredPolicyMixes(std::vector<AudioMix>& mixes) {
1904     if (!audio_flags::audio_mix_test_api()) {
1905         return INVALID_OPERATION;
1906     }
1907 
1908     const sp<IAudioPolicyService> aps = AudioSystem::get_audio_policy_service();
1909     if (aps == nullptr) return PERMISSION_DENIED;
1910 
1911     std::vector<::android::media::AudioMix> aidlMixes;
1912     Status status = aps->getRegisteredPolicyMixes(&aidlMixes);
1913 
1914     for (const auto& aidlMix : aidlMixes) {
1915         AudioMix mix = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioMix(aidlMix));
1916         mixes.push_back(mix);
1917     }
1918 
1919     return statusTFromBinderStatus(status);
1920 }
1921 
updatePolicyMixes(const std::vector<std::pair<AudioMix,std::vector<AudioMixMatchCriterion>>> & mixesWithUpdates)1922 status_t AudioSystem::updatePolicyMixes(
1923         const std::vector<std::pair<AudioMix, std::vector<AudioMixMatchCriterion>>>&
1924                 mixesWithUpdates) {
1925     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1926     if (aps == 0) return PERMISSION_DENIED;
1927 
1928     std::vector<media::AudioMixUpdate> updatesAidl;
1929     updatesAidl.reserve(mixesWithUpdates.size());
1930 
1931     for (const auto& update : mixesWithUpdates) {
1932         media::AudioMixUpdate updateAidl;
1933         updateAidl.audioMix = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioMix(update.first));
1934         RETURN_STATUS_IF_ERROR(convertRange(update.second.begin(), update.second.end(),
1935                                             std::back_inserter(updateAidl.newCriteria),
1936                                             legacy2aidl_AudioMixMatchCriterion));
1937         updatesAidl.emplace_back(updateAidl);
1938     }
1939 
1940     return statusTFromBinderStatus(aps->updatePolicyMixes(updatesAidl));
1941 }
1942 
setUidDeviceAffinities(uid_t uid,const AudioDeviceTypeAddrVector & devices)1943 status_t AudioSystem::setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices) {
1944     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1945     if (aps == 0) return PERMISSION_DENIED;
1946 
1947     int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid));
1948     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
1949             convertContainer<std::vector<AudioDevice>>(devices,
1950                                                               legacy2aidl_AudioDeviceTypeAddress));
1951     return statusTFromBinderStatus(aps->setUidDeviceAffinities(uidAidl, devicesAidl));
1952 }
1953 
removeUidDeviceAffinities(uid_t uid)1954 status_t AudioSystem::removeUidDeviceAffinities(uid_t uid) {
1955     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1956     if (aps == 0) return PERMISSION_DENIED;
1957 
1958     int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid));
1959     return statusTFromBinderStatus(aps->removeUidDeviceAffinities(uidAidl));
1960 }
1961 
setUserIdDeviceAffinities(int userId,const AudioDeviceTypeAddrVector & devices)1962 status_t AudioSystem::setUserIdDeviceAffinities(int userId,
1963                                                 const AudioDeviceTypeAddrVector& devices) {
1964     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1965     if (aps == 0) return PERMISSION_DENIED;
1966 
1967     int32_t userIdAidl = VALUE_OR_RETURN_STATUS(convertReinterpret<int32_t>(userId));
1968     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
1969             convertContainer<std::vector<AudioDevice>>(devices,
1970                                                        legacy2aidl_AudioDeviceTypeAddress));
1971     return statusTFromBinderStatus(
1972             aps->setUserIdDeviceAffinities(userIdAidl, devicesAidl));
1973 }
1974 
removeUserIdDeviceAffinities(int userId)1975 status_t AudioSystem::removeUserIdDeviceAffinities(int userId) {
1976     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1977     if (aps == 0) return PERMISSION_DENIED;
1978     int32_t userIdAidl = VALUE_OR_RETURN_STATUS(convertReinterpret<int32_t>(userId));
1979     return statusTFromBinderStatus(aps->removeUserIdDeviceAffinities(userIdAidl));
1980 }
1981 
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId)1982 status_t AudioSystem::startAudioSource(const struct audio_port_config* source,
1983                                        const audio_attributes_t* attributes,
1984                                        audio_port_handle_t* portId) {
1985     if (source == nullptr || attributes == nullptr || portId == nullptr) {
1986         return BAD_VALUE;
1987     }
1988     const sp<IAudioPolicyService> aps = get_audio_policy_service();
1989     if (aps == 0) return PERMISSION_DENIED;
1990 
1991     media::AudioPortConfigFw sourceAidl = VALUE_OR_RETURN_STATUS(
1992             legacy2aidl_audio_port_config_AudioPortConfigFw(*source));
1993     media::audio::common::AudioAttributes attributesAidl = VALUE_OR_RETURN_STATUS(
1994             legacy2aidl_audio_attributes_t_AudioAttributes(*attributes));
1995     int32_t portIdAidl;
1996     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
1997             aps->startAudioSource(sourceAidl, attributesAidl, &portIdAidl)));
1998     *portId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(portIdAidl));
1999     return OK;
2000 }
2001 
stopAudioSource(audio_port_handle_t portId)2002 status_t AudioSystem::stopAudioSource(audio_port_handle_t portId) {
2003     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2004     if (aps == 0) return PERMISSION_DENIED;
2005 
2006     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
2007     return statusTFromBinderStatus(aps->stopAudioSource(portIdAidl));
2008 }
2009 
setMasterMono(bool mono)2010 status_t AudioSystem::setMasterMono(bool mono) {
2011     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2012     if (aps == 0) return PERMISSION_DENIED;
2013     return statusTFromBinderStatus(aps->setMasterMono(mono));
2014 }
2015 
getMasterMono(bool * mono)2016 status_t AudioSystem::getMasterMono(bool* mono) {
2017     if (mono == nullptr) {
2018         return BAD_VALUE;
2019     }
2020     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2021     if (aps == 0) return PERMISSION_DENIED;
2022     return statusTFromBinderStatus(aps->getMasterMono(mono));
2023 }
2024 
setMasterBalance(float balance)2025 status_t AudioSystem::setMasterBalance(float balance) {
2026     const sp<IAudioFlinger> af = get_audio_flinger();
2027     if (af == 0) return PERMISSION_DENIED;
2028     return af->setMasterBalance(balance);
2029 }
2030 
getMasterBalance(float * balance)2031 status_t AudioSystem::getMasterBalance(float* balance) {
2032     const sp<IAudioFlinger> af = get_audio_flinger();
2033     if (af == 0) return PERMISSION_DENIED;
2034     return af->getMasterBalance(balance);
2035 }
2036 
2037 float
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)2038 AudioSystem::getStreamVolumeDB(audio_stream_type_t stream, int index, audio_devices_t device) {
2039     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2040     if (aps == 0) return NAN;
2041 
2042     auto result = [&]() -> ConversionResult<float> {
2043         AudioStreamType streamAidl = VALUE_OR_RETURN(
2044                 legacy2aidl_audio_stream_type_t_AudioStreamType(stream));
2045         int32_t indexAidl = VALUE_OR_RETURN(convertIntegral<int32_t>(index));
2046         AudioDeviceDescription deviceAidl = VALUE_OR_RETURN(
2047                 legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
2048         float retAidl;
2049         RETURN_IF_ERROR(statusTFromBinderStatus(
2050                 aps->getStreamVolumeDB(streamAidl, indexAidl, deviceAidl, &retAidl)));
2051         return retAidl;
2052     }();
2053     return result.value_or(NAN);
2054 }
2055 
getMicrophones(std::vector<media::MicrophoneInfoFw> * microphones)2056 status_t AudioSystem::getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) {
2057     const sp<IAudioFlinger> af = get_audio_flinger();
2058     if (af == 0) return PERMISSION_DENIED;
2059     return af->getMicrophones(microphones);
2060 }
2061 
setAudioHalPids(const std::vector<pid_t> & pids)2062 status_t AudioSystem::setAudioHalPids(const std::vector<pid_t>& pids) {
2063     const sp<IAudioFlinger> af = get_audio_flinger();
2064     if (af == nullptr) return PERMISSION_DENIED;
2065     return af->setAudioHalPids(pids);
2066 }
2067 
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled)2068 status_t AudioSystem::getSurroundFormats(unsigned int* numSurroundFormats,
2069                                          audio_format_t* surroundFormats,
2070                                          bool* surroundFormatsEnabled) {
2071     if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
2072                                           (surroundFormats == nullptr ||
2073                                            surroundFormatsEnabled == nullptr))) {
2074         return BAD_VALUE;
2075     }
2076 
2077     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2078     if (aps == 0) return PERMISSION_DENIED;
2079     Int numSurroundFormatsAidl;
2080     numSurroundFormatsAidl.value =
2081             VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(*numSurroundFormats));
2082     std::vector<AudioFormatDescription> surroundFormatsAidl;
2083     std::vector<bool> surroundFormatsEnabledAidl;
2084     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2085             aps->getSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl,
2086                                     &surroundFormatsEnabledAidl)));
2087 
2088     *numSurroundFormats = VALUE_OR_RETURN_STATUS(
2089             convertIntegral<unsigned int>(numSurroundFormatsAidl.value));
2090     RETURN_STATUS_IF_ERROR(
2091             convertRange(surroundFormatsAidl.begin(), surroundFormatsAidl.end(), surroundFormats,
2092                          aidl2legacy_AudioFormatDescription_audio_format_t));
2093     std::copy(surroundFormatsEnabledAidl.begin(), surroundFormatsEnabledAidl.end(),
2094             surroundFormatsEnabled);
2095     return OK;
2096 }
2097 
getReportedSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats)2098 status_t AudioSystem::getReportedSurroundFormats(unsigned int* numSurroundFormats,
2099                                                  audio_format_t* surroundFormats) {
2100     if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
2101         return BAD_VALUE;
2102     }
2103 
2104     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2105     if (aps == 0) return PERMISSION_DENIED;
2106     Int numSurroundFormatsAidl;
2107     numSurroundFormatsAidl.value =
2108             VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(*numSurroundFormats));
2109     std::vector<AudioFormatDescription> surroundFormatsAidl;
2110     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2111             aps->getReportedSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl)));
2112 
2113     *numSurroundFormats = VALUE_OR_RETURN_STATUS(
2114             convertIntegral<unsigned int>(numSurroundFormatsAidl.value));
2115     RETURN_STATUS_IF_ERROR(
2116             convertRange(surroundFormatsAidl.begin(), surroundFormatsAidl.end(), surroundFormats,
2117                          aidl2legacy_AudioFormatDescription_audio_format_t));
2118     return OK;
2119 }
2120 
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)2121 status_t AudioSystem::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled) {
2122     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2123     if (aps == 0) return PERMISSION_DENIED;
2124 
2125     AudioFormatDescription audioFormatAidl = VALUE_OR_RETURN_STATUS(
2126             legacy2aidl_audio_format_t_AudioFormatDescription(audioFormat));
2127     return statusTFromBinderStatus(
2128             aps->setSurroundFormatEnabled(audioFormatAidl, enabled));
2129 }
2130 
setAssistantServicesUids(const std::vector<uid_t> & uids)2131 status_t AudioSystem::setAssistantServicesUids(const std::vector<uid_t>& uids) {
2132     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2133     if (aps == 0) return PERMISSION_DENIED;
2134 
2135     std::vector<int32_t> uidsAidl = VALUE_OR_RETURN_STATUS(
2136                 convertContainer<std::vector<int32_t>>(uids, legacy2aidl_uid_t_int32_t));
2137     return statusTFromBinderStatus(aps->setAssistantServicesUids(uidsAidl));
2138 }
2139 
setActiveAssistantServicesUids(const std::vector<uid_t> & activeUids)2140 status_t AudioSystem::setActiveAssistantServicesUids(const std::vector<uid_t>& activeUids) {
2141     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2142     if (aps == 0) return PERMISSION_DENIED;
2143 
2144     std::vector<int32_t> activeUidsAidl = VALUE_OR_RETURN_STATUS(
2145                 convertContainer<std::vector<int32_t>>(activeUids, legacy2aidl_uid_t_int32_t));
2146     return statusTFromBinderStatus(aps->setActiveAssistantServicesUids(activeUidsAidl));
2147 }
2148 
setA11yServicesUids(const std::vector<uid_t> & uids)2149 status_t AudioSystem::setA11yServicesUids(const std::vector<uid_t>& uids) {
2150     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2151     if (aps == 0) return PERMISSION_DENIED;
2152 
2153     std::vector<int32_t> uidsAidl = VALUE_OR_RETURN_STATUS(
2154             convertContainer<std::vector<int32_t>>(uids, legacy2aidl_uid_t_int32_t));
2155     return statusTFromBinderStatus(aps->setA11yServicesUids(uidsAidl));
2156 }
2157 
setCurrentImeUid(uid_t uid)2158 status_t AudioSystem::setCurrentImeUid(uid_t uid) {
2159     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2160     if (aps == 0) return PERMISSION_DENIED;
2161 
2162     int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid));
2163     return statusTFromBinderStatus(aps->setCurrentImeUid(uidAidl));
2164 }
2165 
isHapticPlaybackSupported()2166 bool AudioSystem::isHapticPlaybackSupported() {
2167     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2168     if (aps == 0) return false;
2169 
2170     auto result = [&]() -> ConversionResult<bool> {
2171         bool retVal;
2172         RETURN_IF_ERROR(
2173                 statusTFromBinderStatus(aps->isHapticPlaybackSupported(&retVal)));
2174         return retVal;
2175     }();
2176     return result.value_or(false);
2177 }
2178 
isUltrasoundSupported()2179 bool AudioSystem::isUltrasoundSupported() {
2180     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2181     if (aps == 0) return false;
2182 
2183     auto result = [&]() -> ConversionResult<bool> {
2184         bool retVal;
2185         RETURN_IF_ERROR(
2186                 statusTFromBinderStatus(aps->isUltrasoundSupported(&retVal)));
2187         return retVal;
2188     }();
2189     return result.value_or(false);
2190 }
2191 
getHwOffloadFormatsSupportedForBluetoothMedia(audio_devices_t device,std::vector<audio_format_t> * formats)2192 status_t AudioSystem::getHwOffloadFormatsSupportedForBluetoothMedia(
2193         audio_devices_t device, std::vector<audio_format_t>* formats) {
2194     if (formats == nullptr) {
2195         return BAD_VALUE;
2196     }
2197 
2198     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2199     if (aps == 0) return PERMISSION_DENIED;
2200 
2201     std::vector<AudioFormatDescription> formatsAidl;
2202     AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS(
2203             legacy2aidl_audio_devices_t_AudioDeviceDescription(device));
2204     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2205             aps->getHwOffloadFormatsSupportedForBluetoothMedia(deviceAidl, &formatsAidl)));
2206     *formats = VALUE_OR_RETURN_STATUS(
2207             convertContainer<std::vector<audio_format_t>>(
2208                     formatsAidl,
2209                     aidl2legacy_AudioFormatDescription_audio_format_t));
2210     return OK;
2211 }
2212 
listAudioProductStrategies(AudioProductStrategyVector & strategies)2213 status_t AudioSystem::listAudioProductStrategies(AudioProductStrategyVector& strategies) {
2214     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2215     if (aps == 0) return PERMISSION_DENIED;
2216 
2217     std::vector<media::AudioProductStrategy> strategiesAidl;
2218     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2219             aps->listAudioProductStrategies(&strategiesAidl)));
2220     strategies = VALUE_OR_RETURN_STATUS(
2221             convertContainer<AudioProductStrategyVector>(strategiesAidl,
2222                                                          aidl2legacy_AudioProductStrategy));
2223     return OK;
2224 }
2225 
streamTypeToAttributes(audio_stream_type_t stream)2226 audio_attributes_t AudioSystem::streamTypeToAttributes(audio_stream_type_t stream) {
2227     AudioProductStrategyVector strategies;
2228     listAudioProductStrategies(strategies);
2229     for (const auto& strategy : strategies) {
2230         auto attrVect = strategy.getVolumeGroupAttributes();
2231         auto iter = std::find_if(begin(attrVect), end(attrVect), [&stream](const auto& attributes) {
2232             return attributes.getStreamType() == stream;
2233         });
2234         if (iter != end(attrVect)) {
2235             return iter->getAttributes();
2236         }
2237     }
2238     ALOGE("invalid stream type %s when converting to attributes", toString(stream).c_str());
2239     return AUDIO_ATTRIBUTES_INITIALIZER;
2240 }
2241 
attributesToStreamType(const audio_attributes_t & attr)2242 audio_stream_type_t AudioSystem::attributesToStreamType(const audio_attributes_t& attr) {
2243     product_strategy_t psId;
2244     status_t ret = AudioSystem::getProductStrategyFromAudioAttributes(attr, psId);
2245     if (ret != NO_ERROR) {
2246         ALOGE("no strategy found for attributes %s", toString(attr).c_str());
2247         return AUDIO_STREAM_MUSIC;
2248     }
2249     AudioProductStrategyVector strategies;
2250     listAudioProductStrategies(strategies);
2251     for (const auto& strategy : strategies) {
2252         if (strategy.getId() == psId) {
2253             auto attrVect = strategy.getVolumeGroupAttributes();
2254             auto iter = std::find_if(begin(attrVect), end(attrVect), [&attr](const auto& refAttr) {
2255                 return refAttr.matchesScore(attr) > 0;
2256             });
2257             if (iter != end(attrVect)) {
2258                 return iter->getStreamType();
2259             }
2260         }
2261     }
2262     switch (attr.usage) {
2263         case AUDIO_USAGE_VIRTUAL_SOURCE:
2264             // virtual source is not expected to have an associated product strategy
2265             break;
2266         default:
2267             ALOGE("invalid attributes %s when converting to stream", toString(attr).c_str());
2268             break;
2269     }
2270     return AUDIO_STREAM_MUSIC;
2271 }
2272 
getProductStrategyFromAudioAttributes(const audio_attributes_t & aa,product_strategy_t & productStrategy,bool fallbackOnDefault)2273 status_t AudioSystem::getProductStrategyFromAudioAttributes(const audio_attributes_t& aa,
2274                                                             product_strategy_t& productStrategy,
2275                                                             bool fallbackOnDefault) {
2276     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2277     if (aps == 0) return PERMISSION_DENIED;
2278 
2279     media::audio::common::AudioAttributes aaAidl = VALUE_OR_RETURN_STATUS(
2280             legacy2aidl_audio_attributes_t_AudioAttributes(aa));
2281     int32_t productStrategyAidl;
2282 
2283     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2284             aps->getProductStrategyFromAudioAttributes(aaAidl, fallbackOnDefault,
2285             &productStrategyAidl)));
2286     productStrategy = VALUE_OR_RETURN_STATUS(
2287             aidl2legacy_int32_t_product_strategy_t(productStrategyAidl));
2288     return OK;
2289 }
2290 
listAudioVolumeGroups(AudioVolumeGroupVector & groups)2291 status_t AudioSystem::listAudioVolumeGroups(AudioVolumeGroupVector& groups) {
2292     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2293     if (aps == 0) return PERMISSION_DENIED;
2294 
2295     std::vector<media::AudioVolumeGroup> groupsAidl;
2296     RETURN_STATUS_IF_ERROR(
2297             statusTFromBinderStatus(aps->listAudioVolumeGroups(&groupsAidl)));
2298     groups = VALUE_OR_RETURN_STATUS(
2299             convertContainer<AudioVolumeGroupVector>(groupsAidl, aidl2legacy_AudioVolumeGroup));
2300     return OK;
2301 }
2302 
getVolumeGroupFromAudioAttributes(const audio_attributes_t & aa,volume_group_t & volumeGroup,bool fallbackOnDefault)2303 status_t AudioSystem::getVolumeGroupFromAudioAttributes(const audio_attributes_t &aa,
2304                                                         volume_group_t& volumeGroup,
2305                                                         bool fallbackOnDefault) {
2306     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2307     if (aps == 0) return PERMISSION_DENIED;
2308 
2309     media::audio::common::AudioAttributes aaAidl = VALUE_OR_RETURN_STATUS(
2310             legacy2aidl_audio_attributes_t_AudioAttributes(aa));
2311     int32_t volumeGroupAidl;
2312     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2313             aps->getVolumeGroupFromAudioAttributes(aaAidl, fallbackOnDefault, &volumeGroupAidl)));
2314     volumeGroup = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_volume_group_t(volumeGroupAidl));
2315     return OK;
2316 }
2317 
setRttEnabled(bool enabled)2318 status_t AudioSystem::setRttEnabled(bool enabled) {
2319     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2320     if (aps == 0) return PERMISSION_DENIED;
2321     return statusTFromBinderStatus(aps->setRttEnabled(enabled));
2322 }
2323 
isCallScreenModeSupported()2324 bool AudioSystem::isCallScreenModeSupported() {
2325     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2326     if (aps == 0) return false;
2327 
2328     auto result = [&]() -> ConversionResult<bool> {
2329         bool retAidl;
2330         RETURN_IF_ERROR(
2331                 statusTFromBinderStatus(aps->isCallScreenModeSupported(&retAidl)));
2332         return retAidl;
2333     }();
2334     return result.value_or(false);
2335 }
2336 
setDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role,const AudioDeviceTypeAddrVector & devices)2337 status_t AudioSystem::setDevicesRoleForStrategy(product_strategy_t strategy,
2338                                                 device_role_t role,
2339                                                 const AudioDeviceTypeAddrVector& devices) {
2340     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2341     if (aps == 0) {
2342         return PERMISSION_DENIED;
2343     }
2344 
2345     int32_t strategyAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_product_strategy_t_int32_t(strategy));
2346     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2347     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
2348             convertContainer<std::vector<AudioDevice>>(devices,
2349                                                        legacy2aidl_AudioDeviceTypeAddress));
2350     return statusTFromBinderStatus(
2351             aps->setDevicesRoleForStrategy(strategyAidl, roleAidl, devicesAidl));
2352 }
2353 
removeDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role,const AudioDeviceTypeAddrVector & devices)2354 status_t AudioSystem::removeDevicesRoleForStrategy(product_strategy_t strategy,
2355                                                    device_role_t role,
2356                                                    const AudioDeviceTypeAddrVector& devices) {
2357     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2358     if (aps == 0) {
2359         return PERMISSION_DENIED;
2360     }
2361 
2362     int32_t strategyAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_product_strategy_t_int32_t(strategy));
2363     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2364     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
2365             convertContainer<std::vector<AudioDevice>>(devices,
2366                                                        legacy2aidl_AudioDeviceTypeAddress));
2367     return statusTFromBinderStatus(
2368             aps->removeDevicesRoleForStrategy(strategyAidl, roleAidl, devicesAidl));
2369 }
2370 
2371 status_t
clearDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role)2372 AudioSystem::clearDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role) {
2373     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2374     if (aps == 0) {
2375         return PERMISSION_DENIED;
2376     }
2377     int32_t strategyAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_product_strategy_t_int32_t(strategy));
2378     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2379     return statusTFromBinderStatus(
2380             aps->clearDevicesRoleForStrategy(strategyAidl, roleAidl));
2381 }
2382 
getDevicesForRoleAndStrategy(product_strategy_t strategy,device_role_t role,AudioDeviceTypeAddrVector & devices)2383 status_t AudioSystem::getDevicesForRoleAndStrategy(product_strategy_t strategy,
2384                                                    device_role_t role,
2385                                                    AudioDeviceTypeAddrVector& devices) {
2386     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2387     if (aps == 0) {
2388         return PERMISSION_DENIED;
2389     }
2390     int32_t strategyAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_product_strategy_t_int32_t(strategy));
2391     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2392     std::vector<AudioDevice> devicesAidl;
2393     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2394             aps->getDevicesForRoleAndStrategy(strategyAidl, roleAidl, &devicesAidl)));
2395     devices = VALUE_OR_RETURN_STATUS(
2396             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2397                                                         aidl2legacy_AudioDeviceTypeAddress));
2398     return OK;
2399 }
2400 
setDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)2401 status_t AudioSystem::setDevicesRoleForCapturePreset(audio_source_t audioSource,
2402                                                      device_role_t role,
2403                                                      const AudioDeviceTypeAddrVector& devices) {
2404     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2405     if (aps == 0) {
2406         return PERMISSION_DENIED;
2407     }
2408 
2409     AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS(
2410             legacy2aidl_audio_source_t_AudioSource(audioSource));
2411     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2412     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
2413             convertContainer<std::vector<AudioDevice>>(devices,
2414                                                        legacy2aidl_AudioDeviceTypeAddress));
2415     return statusTFromBinderStatus(
2416             aps->setDevicesRoleForCapturePreset(audioSourceAidl, roleAidl, devicesAidl));
2417 }
2418 
addDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)2419 status_t AudioSystem::addDevicesRoleForCapturePreset(audio_source_t audioSource,
2420                                                      device_role_t role,
2421                                                      const AudioDeviceTypeAddrVector& devices) {
2422     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2423     if (aps == 0) {
2424         return PERMISSION_DENIED;
2425     }
2426     AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS(
2427             legacy2aidl_audio_source_t_AudioSource(audioSource));
2428     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2429     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
2430             convertContainer<std::vector<AudioDevice>>(devices,
2431                                                        legacy2aidl_AudioDeviceTypeAddress));
2432     return statusTFromBinderStatus(
2433             aps->addDevicesRoleForCapturePreset(audioSourceAidl, roleAidl, devicesAidl));
2434 }
2435 
removeDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)2436 status_t AudioSystem::removeDevicesRoleForCapturePreset(
2437         audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices) {
2438     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2439     if (aps == 0) {
2440         return PERMISSION_DENIED;
2441     }
2442     AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS(
2443             legacy2aidl_audio_source_t_AudioSource(audioSource));
2444     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2445     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
2446             convertContainer<std::vector<AudioDevice>>(devices,
2447                                                        legacy2aidl_AudioDeviceTypeAddress));
2448     return statusTFromBinderStatus(
2449             aps->removeDevicesRoleForCapturePreset(audioSourceAidl, roleAidl, devicesAidl));
2450 }
2451 
clearDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role)2452 status_t AudioSystem::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
2453                                                        device_role_t role) {
2454     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2455     if (aps == 0) {
2456         return PERMISSION_DENIED;
2457     }
2458     AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS(
2459             legacy2aidl_audio_source_t_AudioSource(audioSource));
2460     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2461     return statusTFromBinderStatus(
2462             aps->clearDevicesRoleForCapturePreset(audioSourceAidl, roleAidl));
2463 }
2464 
getDevicesForRoleAndCapturePreset(audio_source_t audioSource,device_role_t role,AudioDeviceTypeAddrVector & devices)2465 status_t AudioSystem::getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
2466                                                         device_role_t role,
2467                                                         AudioDeviceTypeAddrVector& devices) {
2468     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2469     if (aps == 0) {
2470         return PERMISSION_DENIED;
2471     }
2472     AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS(
2473             legacy2aidl_audio_source_t_AudioSource(audioSource));
2474     media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role));
2475     std::vector<AudioDevice> devicesAidl;
2476     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2477             aps->getDevicesForRoleAndCapturePreset(audioSourceAidl, roleAidl, &devicesAidl)));
2478     devices = VALUE_OR_RETURN_STATUS(
2479             convertContainer<AudioDeviceTypeAddrVector>(devicesAidl,
2480                                                         aidl2legacy_AudioDeviceTypeAddress));
2481     return OK;
2482 }
2483 
getSpatializer(const sp<media::INativeSpatializerCallback> & callback,sp<media::ISpatializer> * spatializer)2484 status_t AudioSystem::getSpatializer(const sp<media::INativeSpatializerCallback>& callback,
2485                                           sp<media::ISpatializer>* spatializer) {
2486     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2487     if (spatializer == nullptr) {
2488         return BAD_VALUE;
2489     }
2490     if (aps == 0) {
2491         return PERMISSION_DENIED;
2492     }
2493     media::GetSpatializerResponse response;
2494     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2495             aps->getSpatializer(callback, &response)));
2496 
2497     *spatializer = response.spatializer;
2498     return OK;
2499 }
2500 
canBeSpatialized(const audio_attributes_t * attr,const audio_config_t * config,const AudioDeviceTypeAddrVector & devices,bool * canBeSpatialized)2501 status_t AudioSystem::canBeSpatialized(const audio_attributes_t *attr,
2502                                     const audio_config_t *config,
2503                                     const AudioDeviceTypeAddrVector &devices,
2504                                     bool *canBeSpatialized) {
2505     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2506     if (canBeSpatialized == nullptr) {
2507         return BAD_VALUE;
2508     }
2509     if (aps == 0) {
2510         return PERMISSION_DENIED;
2511     }
2512     audio_attributes_t attributes = attr != nullptr ? *attr : AUDIO_ATTRIBUTES_INITIALIZER;
2513     audio_config_t configuration = config != nullptr ? *config : AUDIO_CONFIG_INITIALIZER;
2514 
2515     std::optional<media::audio::common::AudioAttributes> attrAidl = VALUE_OR_RETURN_STATUS(
2516             legacy2aidl_audio_attributes_t_AudioAttributes(attributes));
2517     std::optional<AudioConfig> configAidl = VALUE_OR_RETURN_STATUS(
2518             legacy2aidl_audio_config_t_AudioConfig(configuration, false /*isInput*/));
2519     std::vector<AudioDevice> devicesAidl = VALUE_OR_RETURN_STATUS(
2520             convertContainer<std::vector<AudioDevice>>(devices,
2521                                                        legacy2aidl_AudioDeviceTypeAddress));
2522     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2523             aps->canBeSpatialized(attrAidl, configAidl, devicesAidl, canBeSpatialized)));
2524     return OK;
2525 }
2526 
getSoundDoseInterface(const sp<media::ISoundDoseCallback> & callback,sp<media::ISoundDose> * soundDose)2527 status_t AudioSystem::getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback,
2528                                             sp<media::ISoundDose>* soundDose) {
2529     const sp<IAudioFlinger> af = get_audio_flinger();
2530     if (af == nullptr) {
2531         return PERMISSION_DENIED;
2532     }
2533     if (soundDose == nullptr) {
2534         return BAD_VALUE;
2535     }
2536 
2537     RETURN_STATUS_IF_ERROR(af->getSoundDoseInterface(callback, soundDose));
2538     return OK;
2539 }
2540 
getDirectPlaybackSupport(const audio_attributes_t * attr,const audio_config_t * config,audio_direct_mode_t * directMode)2541 status_t AudioSystem::getDirectPlaybackSupport(const audio_attributes_t *attr,
2542                                                const audio_config_t *config,
2543                                                audio_direct_mode_t* directMode) {
2544     if (attr == nullptr || config == nullptr || directMode == nullptr) {
2545         return BAD_VALUE;
2546     }
2547 
2548     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2549     if (aps == 0) {
2550         return PERMISSION_DENIED;
2551     }
2552 
2553     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
2554             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
2555     AudioConfig configAidl = VALUE_OR_RETURN_STATUS(
2556             legacy2aidl_audio_config_t_AudioConfig(*config, false /*isInput*/));
2557 
2558     media::AudioDirectMode retAidl;
2559     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2560             aps->getDirectPlaybackSupport(attrAidl, configAidl, &retAidl)));
2561     *directMode = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_direct_mode_t_mask(
2562             static_cast<int32_t>(retAidl)));
2563     return NO_ERROR;
2564 }
2565 
getDirectProfilesForAttributes(const audio_attributes_t * attr,std::vector<audio_profile> * audioProfiles)2566 status_t AudioSystem::getDirectProfilesForAttributes(const audio_attributes_t* attr,
2567                                                 std::vector<audio_profile>* audioProfiles) {
2568     if (attr == nullptr || audioProfiles == nullptr) {
2569         return BAD_VALUE;
2570     }
2571 
2572     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2573     if (aps == 0) {
2574         return PERMISSION_DENIED;
2575     }
2576 
2577     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
2578             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
2579 
2580     std::vector<media::audio::common::AudioProfile> audioProfilesAidl;
2581     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2582             aps->getDirectProfilesForAttributes(attrAidl, &audioProfilesAidl)));
2583     *audioProfiles = VALUE_OR_RETURN_STATUS(convertContainer<std::vector<audio_profile>>(
2584                     audioProfilesAidl, aidl2legacy_AudioProfile_audio_profile, false /*isInput*/));
2585 
2586     return NO_ERROR;
2587 }
2588 
setRequestedLatencyMode(audio_io_handle_t output,audio_latency_mode_t mode)2589 status_t AudioSystem::setRequestedLatencyMode(
2590             audio_io_handle_t output, audio_latency_mode_t mode) {
2591     const sp<IAudioFlinger> af = get_audio_flinger();
2592     if (af == nullptr) {
2593         return PERMISSION_DENIED;
2594     }
2595     return af->setRequestedLatencyMode(output, mode);
2596 }
2597 
getSupportedLatencyModes(audio_io_handle_t output,std::vector<audio_latency_mode_t> * modes)2598 status_t AudioSystem::getSupportedLatencyModes(audio_io_handle_t output,
2599         std::vector<audio_latency_mode_t>* modes) {
2600     const sp<IAudioFlinger> af = get_audio_flinger();
2601     if (af == nullptr) {
2602         return PERMISSION_DENIED;
2603     }
2604     return af->getSupportedLatencyModes(output, modes);
2605 }
2606 
setBluetoothVariableLatencyEnabled(bool enabled)2607 status_t AudioSystem::setBluetoothVariableLatencyEnabled(bool enabled) {
2608     const sp<IAudioFlinger> af = get_audio_flinger();
2609     if (af == nullptr) {
2610         return PERMISSION_DENIED;
2611     }
2612     return af->setBluetoothVariableLatencyEnabled(enabled);
2613 }
2614 
isBluetoothVariableLatencyEnabled(bool * enabled)2615 status_t AudioSystem::isBluetoothVariableLatencyEnabled(
2616         bool *enabled) {
2617     const sp<IAudioFlinger> af = get_audio_flinger();
2618     if (af == nullptr) {
2619         return PERMISSION_DENIED;
2620     }
2621     return af->isBluetoothVariableLatencyEnabled(enabled);
2622 }
2623 
supportsBluetoothVariableLatency(bool * support)2624 status_t AudioSystem::supportsBluetoothVariableLatency(
2625         bool *support) {
2626     const sp<IAudioFlinger> af = get_audio_flinger();
2627     if (af == nullptr) {
2628         return PERMISSION_DENIED;
2629     }
2630     return af->supportsBluetoothVariableLatency(support);
2631 }
2632 
getAudioPolicyConfig(media::AudioPolicyConfig * config)2633 status_t AudioSystem::getAudioPolicyConfig(media::AudioPolicyConfig *config) {
2634     const sp<IAudioFlinger> af = get_audio_flinger();
2635     if (af == nullptr) {
2636         return PERMISSION_DENIED;
2637     }
2638     return af->getAudioPolicyConfig(config);
2639 }
2640 
2641 class CaptureStateListenerImpl : public media::BnCaptureStateListener,
2642                                  public IBinder::DeathRecipient {
2643 public:
CaptureStateListenerImpl(const sp<IAudioPolicyService> & aps,const sp<AudioSystem::CaptureStateListener> & listener)2644     CaptureStateListenerImpl(
2645             const sp<IAudioPolicyService>& aps,
2646             const sp<AudioSystem::CaptureStateListener>& listener)
2647             : mAps(aps), mListener(listener) {}
2648 
init()2649     void init() {
2650         bool active;
2651         status_t status = statusTFromBinderStatus(
2652                 mAps->registerSoundTriggerCaptureStateListener(this, &active));
2653         if (status != NO_ERROR) {
2654             mListener->onServiceDied();
2655             return;
2656         }
2657         mListener->onStateChanged(active);
2658         IInterface::asBinder(mAps)->linkToDeath(this);
2659     }
2660 
setCaptureState(bool active)2661     binder::Status setCaptureState(bool active) override {
2662         std::lock_guard _l(AudioSystem::gSoundTriggerMutex);
2663         mListener->onStateChanged(active);
2664         return binder::Status::ok();
2665     }
2666 
binderDied(const wp<IBinder> &)2667     void binderDied(const wp<IBinder>&) override {
2668         std::lock_guard _l(AudioSystem::gSoundTriggerMutex);
2669         mListener->onServiceDied();
2670         AudioSystem::gSoundTriggerCaptureStateListener = nullptr;
2671     }
2672 
2673 private:
2674     // Need this in order to keep the death receipent alive.
2675     sp<IAudioPolicyService> mAps;
2676     sp<AudioSystem::CaptureStateListener> mListener;
2677 };
2678 
registerSoundTriggerCaptureStateListener(const sp<CaptureStateListener> & listener)2679 status_t AudioSystem::registerSoundTriggerCaptureStateListener(
2680         const sp<CaptureStateListener>& listener) {
2681     LOG_ALWAYS_FATAL_IF(listener == nullptr);
2682 
2683     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2684     if (aps == 0) {
2685         return PERMISSION_DENIED;
2686     }
2687 
2688     std::lock_guard _l(AudioSystem::gSoundTriggerMutex);
2689     gSoundTriggerCaptureStateListener = new CaptureStateListenerImpl(aps, listener);
2690     gSoundTriggerCaptureStateListener->init();
2691 
2692     return NO_ERROR;
2693 }
2694 
setVibratorInfos(const std::vector<media::AudioVibratorInfo> & vibratorInfos)2695 status_t AudioSystem::setVibratorInfos(
2696         const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
2697     const sp<IAudioFlinger> af = get_audio_flinger();
2698     if (af == nullptr) {
2699         return PERMISSION_DENIED;
2700     }
2701     return af->setVibratorInfos(vibratorInfos);
2702 }
2703 
getMmapPolicyInfo(AudioMMapPolicyType policyType,std::vector<AudioMMapPolicyInfo> * policyInfos)2704 status_t AudioSystem::getMmapPolicyInfo(
2705         AudioMMapPolicyType policyType, std::vector<AudioMMapPolicyInfo> *policyInfos) {
2706     const sp<IAudioFlinger> af = get_audio_flinger();
2707     if (af == nullptr) {
2708         return PERMISSION_DENIED;
2709     }
2710     return af->getMmapPolicyInfos(policyType, policyInfos);
2711 }
2712 
getAAudioMixerBurstCount()2713 int32_t AudioSystem::getAAudioMixerBurstCount() {
2714     const sp<IAudioFlinger> af = get_audio_flinger();
2715     if (af == nullptr) {
2716         return PERMISSION_DENIED;
2717     }
2718     return af->getAAudioMixerBurstCount();
2719 }
2720 
getAAudioHardwareBurstMinUsec()2721 int32_t AudioSystem::getAAudioHardwareBurstMinUsec() {
2722     const sp<IAudioFlinger> af = get_audio_flinger();
2723     if (af == nullptr) {
2724         return PERMISSION_DENIED;
2725     }
2726     return af->getAAudioHardwareBurstMinUsec();
2727 }
2728 
getSupportedMixerAttributes(audio_port_handle_t portId,std::vector<audio_mixer_attributes_t> * mixerAttrs)2729 status_t AudioSystem::getSupportedMixerAttributes(
2730         audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> *mixerAttrs) {
2731     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2732     if (aps == nullptr) {
2733         return PERMISSION_DENIED;
2734     }
2735 
2736     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
2737     std::vector<media::AudioMixerAttributesInternal> _aidlReturn;
2738     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2739             aps->getSupportedMixerAttributes(portIdAidl, &_aidlReturn)));
2740     *mixerAttrs = VALUE_OR_RETURN_STATUS(
2741             convertContainer<std::vector<audio_mixer_attributes_t>>(
2742                     _aidlReturn,
2743                     aidl2legacy_AudioMixerAttributesInternal_audio_mixer_attributes_t));
2744     return OK;
2745 }
2746 
setPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,uid_t uid,const audio_mixer_attributes_t * mixerAttr)2747 status_t AudioSystem::setPreferredMixerAttributes(const audio_attributes_t *attr,
2748                                                   audio_port_handle_t portId,
2749                                                   uid_t uid,
2750                                                   const audio_mixer_attributes_t *mixerAttr) {
2751     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2752     if (aps == nullptr) {
2753         return PERMISSION_DENIED;
2754     }
2755 
2756     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
2757             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
2758     media::AudioMixerAttributesInternal mixerAttrAidl = VALUE_OR_RETURN_STATUS(
2759             legacy2aidl_audio_mixer_attributes_t_AudioMixerAttributesInternal(*mixerAttr));
2760     int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid));
2761     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
2762 
2763     return statusTFromBinderStatus(
2764             aps->setPreferredMixerAttributes(attrAidl, portIdAidl, uidAidl, mixerAttrAidl));
2765 }
2766 
getPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,std::optional<audio_mixer_attributes_t> * mixerAttr)2767 status_t AudioSystem::getPreferredMixerAttributes(
2768         const audio_attributes_t *attr,
2769         audio_port_handle_t portId,
2770         std::optional<audio_mixer_attributes_t> *mixerAttr) {
2771     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2772     if (aps == nullptr) {
2773         return PERMISSION_DENIED;
2774     }
2775 
2776     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
2777             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
2778     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
2779     std::optional<media::AudioMixerAttributesInternal> _aidlReturn;
2780     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
2781             aps->getPreferredMixerAttributes(attrAidl, portIdAidl, &_aidlReturn)));
2782 
2783     if (_aidlReturn.has_value()) {
2784          *mixerAttr = VALUE_OR_RETURN_STATUS(
2785                  aidl2legacy_AudioMixerAttributesInternal_audio_mixer_attributes_t(
2786                          _aidlReturn.value()));
2787     }
2788     return NO_ERROR;
2789 }
2790 
clearPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,uid_t uid)2791 status_t AudioSystem::clearPreferredMixerAttributes(const audio_attributes_t *attr,
2792                                                     audio_port_handle_t portId,
2793                                                     uid_t uid) {
2794     const sp<IAudioPolicyService> aps = get_audio_policy_service();
2795     if (aps == nullptr) {
2796         return PERMISSION_DENIED;
2797     }
2798 
2799     media::audio::common::AudioAttributes attrAidl = VALUE_OR_RETURN_STATUS(
2800             legacy2aidl_audio_attributes_t_AudioAttributes(*attr));
2801     int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid));
2802     int32_t portIdAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(portId));
2803     return statusTFromBinderStatus(
2804             aps->clearPreferredMixerAttributes(attrAidl, portIdAidl, uidAidl));
2805 }
2806 
2807 // ---------------------------------------------------------------------------
2808 
addAudioPortCallback(const sp<AudioPortCallback> & callback)2809 int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback(
2810         const sp<AudioPortCallback>& callback) {
2811     std::lock_guard _l(mMutex);
2812     return mAudioPortCallbacks.insert(callback).second ? mAudioPortCallbacks.size() : -1;
2813 }
2814 
removeAudioPortCallback(const sp<AudioPortCallback> & callback)2815 int AudioSystem::AudioPolicyServiceClient::removeAudioPortCallback(
2816         const sp<AudioPortCallback>& callback) {
2817     std::lock_guard _l(mMutex);
2818     return mAudioPortCallbacks.erase(callback) > 0 ? mAudioPortCallbacks.size() : -1;
2819 }
2820 
onAudioPortListUpdate()2821 Status AudioSystem::AudioPolicyServiceClient::onAudioPortListUpdate() {
2822     std::lock_guard _l(mMutex);
2823     for (const auto& callback : mAudioPortCallbacks) {
2824         callback->onAudioPortListUpdate();
2825     }
2826     return Status::ok();
2827 }
2828 
onAudioPatchListUpdate()2829 Status AudioSystem::AudioPolicyServiceClient::onAudioPatchListUpdate() {
2830     std::lock_guard _l(mMutex);
2831     for (const auto& callback : mAudioPortCallbacks) {
2832         callback->onAudioPatchListUpdate();
2833     }
2834     return Status::ok();
2835 }
2836 
2837 // ----------------------------------------------------------------------------
addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)2838 int AudioSystem::AudioPolicyServiceClient::addAudioVolumeGroupCallback(
2839         const sp<AudioVolumeGroupCallback>& callback) {
2840     std::lock_guard _l(mMutex);
2841     return mAudioVolumeGroupCallbacks.insert(callback).second
2842             ? mAudioVolumeGroupCallbacks.size() : -1;
2843 }
2844 
removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)2845 int AudioSystem::AudioPolicyServiceClient::removeAudioVolumeGroupCallback(
2846         const sp<AudioVolumeGroupCallback>& callback) {
2847     std::lock_guard _l(mMutex);
2848     return mAudioVolumeGroupCallbacks.erase(callback) > 0
2849             ? mAudioVolumeGroupCallbacks.size() : -1;
2850 }
2851 
onAudioVolumeGroupChanged(int32_t group,int32_t flags)2852 Status AudioSystem::AudioPolicyServiceClient::onAudioVolumeGroupChanged(int32_t group,
2853                                                                         int32_t flags) {
2854     volume_group_t groupLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2855             aidl2legacy_int32_t_volume_group_t(group));
2856     int flagsLegacy = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(flags));
2857 
2858     std::lock_guard _l(mMutex);
2859     for (const auto& callback : mAudioVolumeGroupCallbacks) {
2860         callback->onAudioVolumeGroupChanged(groupLegacy, flagsLegacy);
2861     }
2862     return Status::ok();
2863 }
2864 // ----------------------------------------------------------------------------
2865 
onDynamicPolicyMixStateUpdate(const::std::string & regId,int32_t state)2866 Status AudioSystem::AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(
2867         const ::std::string& regId, int32_t state) {
2868     ALOGV("AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(%s, %d)", regId.c_str(), state);
2869 
2870     String8 regIdLegacy = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_string_view_String8(regId));
2871     int stateLegacy = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(state));
2872     dynamic_policy_callback cb = NULL;
2873     {
2874         std::lock_guard _l(AudioSystem::gMutex);
2875         cb = gDynPolicyCallback;
2876     }
2877 
2878     if (cb != NULL) {
2879         cb(DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE, regIdLegacy, stateLegacy);
2880     }
2881     return Status::ok();
2882 }
2883 
onRecordingConfigurationUpdate(int32_t event,const media::RecordClientInfo & clientInfo,const AudioConfigBase & clientConfig,const std::vector<media::EffectDescriptor> & clientEffects,const AudioConfigBase & deviceConfig,const std::vector<media::EffectDescriptor> & effects,int32_t patchHandle,AudioSource source)2884 Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate(
2885         int32_t event,
2886         const media::RecordClientInfo& clientInfo,
2887         const AudioConfigBase& clientConfig,
2888         const std::vector<media::EffectDescriptor>& clientEffects,
2889         const AudioConfigBase& deviceConfig,
2890         const std::vector<media::EffectDescriptor>& effects,
2891         int32_t patchHandle,
2892         AudioSource source) {
2893     record_config_callback cb = NULL;
2894     {
2895         std::lock_guard _l(AudioSystem::gMutex);
2896         cb = gRecordConfigCallback;
2897     }
2898 
2899     if (cb != NULL) {
2900         int eventLegacy = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret<int>(event));
2901         record_client_info_t clientInfoLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2902                 aidl2legacy_RecordClientInfo_record_client_info_t(clientInfo));
2903         audio_config_base_t clientConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2904                 aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig, true /*isInput*/));
2905         std::vector<effect_descriptor_t> clientEffectsLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2906                 convertContainer<std::vector<effect_descriptor_t>>(
2907                         clientEffects,
2908                         aidl2legacy_EffectDescriptor_effect_descriptor_t));
2909         audio_config_base_t deviceConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2910                 aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig, true /*isInput*/));
2911         std::vector<effect_descriptor_t> effectsLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2912                 convertContainer<std::vector<effect_descriptor_t>>(
2913                         effects,
2914                         aidl2legacy_EffectDescriptor_effect_descriptor_t));
2915         audio_patch_handle_t patchHandleLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2916                 aidl2legacy_int32_t_audio_patch_handle_t(patchHandle));
2917         audio_source_t sourceLegacy = VALUE_OR_RETURN_BINDER_STATUS(
2918                 aidl2legacy_AudioSource_audio_source_t(source));
2919         cb(eventLegacy, &clientInfoLegacy, &clientConfigLegacy, clientEffectsLegacy,
2920            &deviceConfigLegacy, effectsLegacy, patchHandleLegacy, sourceLegacy);
2921     }
2922     return Status::ok();
2923 }
2924 
onRoutingUpdated()2925 Status AudioSystem::AudioPolicyServiceClient::onRoutingUpdated() {
2926     routing_callback cb = NULL;
2927     {
2928         std::lock_guard _l(AudioSystem::gMutex);
2929         cb = gRoutingCallback;
2930     }
2931 
2932     if (cb != NULL) {
2933         cb();
2934     }
2935     return Status::ok();
2936 }
2937 
onVolumeRangeInitRequest()2938 Status AudioSystem::AudioPolicyServiceClient::onVolumeRangeInitRequest() {
2939     vol_range_init_req_callback cb = NULL;
2940     {
2941         std::lock_guard _l(AudioSystem::gMutex);
2942         cb = gVolRangeInitReqCallback;
2943     }
2944 
2945     if (cb != NULL) {
2946         cb();
2947     }
2948     return Status::ok();
2949 }
2950 
binderDied(const wp<IBinder> & who __unused)2951 void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who __unused) {
2952     {
2953         std::lock_guard _l(mMutex);
2954         for (const auto& callback : mAudioPortCallbacks) {
2955             callback->onServiceDied();
2956         }
2957         for (const auto& callback : mAudioVolumeGroupCallbacks) {
2958             callback->onServiceDied();
2959         }
2960     }
2961     AudioSystem::clearAudioPolicyService();
2962 
2963     ALOGW("AudioPolicyService server died!");
2964 }
2965 
2966 ConversionResult<record_client_info_t>
aidl2legacy_RecordClientInfo_record_client_info_t(const media::RecordClientInfo & aidl)2967 aidl2legacy_RecordClientInfo_record_client_info_t(const media::RecordClientInfo& aidl) {
2968     record_client_info_t legacy;
2969     legacy.riid = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_unique_id_t(aidl.riid));
2970     legacy.uid = VALUE_OR_RETURN(aidl2legacy_int32_t_uid_t(aidl.uid));
2971     legacy.session = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_session_t(aidl.session));
2972     legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSource_audio_source_t(aidl.source));
2973     legacy.port_id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.portId));
2974     legacy.silenced = aidl.silenced;
2975     return legacy;
2976 }
2977 
2978 ConversionResult<media::RecordClientInfo>
legacy2aidl_record_client_info_t_RecordClientInfo(const record_client_info_t & legacy)2979 legacy2aidl_record_client_info_t_RecordClientInfo(const record_client_info_t& legacy) {
2980     media::RecordClientInfo aidl;
2981     aidl.riid = VALUE_OR_RETURN(legacy2aidl_audio_unique_id_t_int32_t(legacy.riid));
2982     aidl.uid = VALUE_OR_RETURN(legacy2aidl_uid_t_int32_t(legacy.uid));
2983     aidl.session = VALUE_OR_RETURN(legacy2aidl_audio_session_t_int32_t(legacy.session));
2984     aidl.source = VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSource(legacy.source));
2985     aidl.portId = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.port_id));
2986     aidl.silenced = legacy.silenced;
2987     return aidl;
2988 }
2989 
2990 } // namespace android
2991