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