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/BnCaptureStateListener.h>
23 #include <binder/IServiceManager.h>
24 #include <binder/ProcessState.h>
25 #include <binder/IPCThreadState.h>
26 #include <media/AudioResamplerPublic.h>
27 #include <media/AudioSystem.h>
28 #include <media/IAudioFlinger.h>
29 #include <media/IAudioPolicyService.h>
30 #include <media/TypeConverter.h>
31 #include <math.h>
32 
33 #include <system/audio.h>
34 
35 // ----------------------------------------------------------------------------
36 
37 namespace android {
38 
39 // client singleton for AudioFlinger binder interface
40 Mutex AudioSystem::gLock;
41 Mutex AudioSystem::gLockErrorCallbacks;
42 Mutex AudioSystem::gLockAPS;
43 sp<IAudioFlinger> AudioSystem::gAudioFlinger;
44 sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
45 std::set<audio_error_callback> AudioSystem::gAudioErrorCallbacks;
46 dynamic_policy_callback AudioSystem::gDynPolicyCallback = NULL;
47 record_config_callback AudioSystem::gRecordConfigCallback = NULL;
48 
49 // Required to be held while calling into gSoundTriggerCaptureStateListener.
50 Mutex gSoundTriggerCaptureStateListenerLock;
51 sp<AudioSystem::CaptureStateListener> gSoundTriggerCaptureStateListener = nullptr;
52 
53 // establish binder interface to AudioFlinger service
get_audio_flinger()54 const sp<IAudioFlinger> AudioSystem::get_audio_flinger()
55 {
56     sp<IAudioFlinger> af;
57     sp<AudioFlingerClient> afc;
58     bool reportNoError = false;
59     {
60         Mutex::Autolock _l(gLock);
61         if (gAudioFlinger == 0) {
62             sp<IServiceManager> sm = defaultServiceManager();
63             sp<IBinder> binder;
64             do {
65                 binder = sm->getService(String16("media.audio_flinger"));
66                 if (binder != 0)
67                     break;
68                 ALOGW("AudioFlinger not published, waiting...");
69                 usleep(500000); // 0.5 s
70             } while (true);
71             if (gAudioFlingerClient == NULL) {
72                 gAudioFlingerClient = new AudioFlingerClient();
73             } else {
74                 reportNoError = true;
75             }
76             binder->linkToDeath(gAudioFlingerClient);
77             gAudioFlinger = interface_cast<IAudioFlinger>(binder);
78             LOG_ALWAYS_FATAL_IF(gAudioFlinger == 0);
79             afc = gAudioFlingerClient;
80             // Make sure callbacks can be received by gAudioFlingerClient
81             ProcessState::self()->startThreadPool();
82         }
83         af = gAudioFlinger;
84     }
85     if (afc != 0) {
86         int64_t token = IPCThreadState::self()->clearCallingIdentity();
87         af->registerClient(afc);
88         IPCThreadState::self()->restoreCallingIdentity(token);
89     }
90     if (reportNoError) reportError(NO_ERROR);
91     return af;
92 }
93 
getAudioFlingerClient()94 const sp<AudioSystem::AudioFlingerClient> AudioSystem::getAudioFlingerClient()
95 {
96     // calling get_audio_flinger() will initialize gAudioFlingerClient if needed
97     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
98     if (af == 0) return 0;
99     Mutex::Autolock _l(gLock);
100     return gAudioFlingerClient;
101 }
102 
getIoDescriptor(audio_io_handle_t ioHandle)103 sp<AudioIoDescriptor> AudioSystem::getIoDescriptor(audio_io_handle_t ioHandle)
104 {
105     sp<AudioIoDescriptor> desc;
106     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
107     if (afc != 0) {
108         desc = afc->getIoDescriptor(ioHandle);
109     }
110     return desc;
111 }
112 
checkAudioFlinger()113 /* static */ status_t AudioSystem::checkAudioFlinger()
114 {
115     if (defaultServiceManager()->checkService(String16("media.audio_flinger")) != 0) {
116         return NO_ERROR;
117     }
118     return DEAD_OBJECT;
119 }
120 
121 // FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp
122 
muteMicrophone(bool state)123 status_t AudioSystem::muteMicrophone(bool state)
124 {
125     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
126     if (af == 0) return PERMISSION_DENIED;
127     return af->setMicMute(state);
128 }
129 
isMicrophoneMuted(bool * state)130 status_t AudioSystem::isMicrophoneMuted(bool* state)
131 {
132     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
133     if (af == 0) return PERMISSION_DENIED;
134     *state = af->getMicMute();
135     return NO_ERROR;
136 }
137 
setMasterVolume(float value)138 status_t AudioSystem::setMasterVolume(float value)
139 {
140     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
141     if (af == 0) return PERMISSION_DENIED;
142     af->setMasterVolume(value);
143     return NO_ERROR;
144 }
145 
setMasterMute(bool mute)146 status_t AudioSystem::setMasterMute(bool mute)
147 {
148     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
149     if (af == 0) return PERMISSION_DENIED;
150     af->setMasterMute(mute);
151     return NO_ERROR;
152 }
153 
getMasterVolume(float * volume)154 status_t AudioSystem::getMasterVolume(float* volume)
155 {
156     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
157     if (af == 0) return PERMISSION_DENIED;
158     *volume = af->masterVolume();
159     return NO_ERROR;
160 }
161 
getMasterMute(bool * mute)162 status_t AudioSystem::getMasterMute(bool* mute)
163 {
164     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
165     if (af == 0) return PERMISSION_DENIED;
166     *mute = af->masterMute();
167     return NO_ERROR;
168 }
169 
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)170 status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
171         audio_io_handle_t output)
172 {
173     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
174     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
175     if (af == 0) return PERMISSION_DENIED;
176     af->setStreamVolume(stream, value, output);
177     return NO_ERROR;
178 }
179 
setStreamMute(audio_stream_type_t stream,bool mute)180 status_t AudioSystem::setStreamMute(audio_stream_type_t stream, bool mute)
181 {
182     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
183     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
184     if (af == 0) return PERMISSION_DENIED;
185     af->setStreamMute(stream, mute);
186     return NO_ERROR;
187 }
188 
getStreamVolume(audio_stream_type_t stream,float * volume,audio_io_handle_t output)189 status_t AudioSystem::getStreamVolume(audio_stream_type_t stream, float* volume,
190         audio_io_handle_t output)
191 {
192     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
193     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
194     if (af == 0) return PERMISSION_DENIED;
195     *volume = af->streamVolume(stream, output);
196     return NO_ERROR;
197 }
198 
getStreamMute(audio_stream_type_t stream,bool * mute)199 status_t AudioSystem::getStreamMute(audio_stream_type_t stream, bool* mute)
200 {
201     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
202     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
203     if (af == 0) return PERMISSION_DENIED;
204     *mute = af->streamMute(stream);
205     return NO_ERROR;
206 }
207 
setMode(audio_mode_t mode)208 status_t AudioSystem::setMode(audio_mode_t mode)
209 {
210     if (uint32_t(mode) >= AUDIO_MODE_CNT) return BAD_VALUE;
211     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
212     if (af == 0) return PERMISSION_DENIED;
213     return af->setMode(mode);
214 }
215 
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)216 status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
217 {
218     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
219     if (af == 0) return PERMISSION_DENIED;
220     return af->setParameters(ioHandle, keyValuePairs);
221 }
222 
getParameters(audio_io_handle_t ioHandle,const String8 & keys)223 String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys)
224 {
225     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
226     String8 result = String8("");
227     if (af == 0) return result;
228 
229     result = af->getParameters(ioHandle, keys);
230     return result;
231 }
232 
setParameters(const String8 & keyValuePairs)233 status_t AudioSystem::setParameters(const String8& keyValuePairs)
234 {
235     return setParameters(AUDIO_IO_HANDLE_NONE, keyValuePairs);
236 }
237 
getParameters(const String8 & keys)238 String8 AudioSystem::getParameters(const String8& keys)
239 {
240     return getParameters(AUDIO_IO_HANDLE_NONE, keys);
241 }
242 
243 // convert volume steps to natural log scale
244 
245 // change this value to change volume scaling
246 static const float dBPerStep = 0.5f;
247 // shouldn't need to touch these
248 static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
249 static const float dBConvertInverse = 1.0f / dBConvert;
250 
linearToLog(int volume)251 float AudioSystem::linearToLog(int volume)
252 {
253     // float v = volume ? exp(float(100 - volume) * dBConvert) : 0;
254     // ALOGD("linearToLog(%d)=%f", volume, v);
255     // return v;
256     return volume ? exp(float(100 - volume) * dBConvert) : 0;
257 }
258 
logToLinear(float volume)259 int AudioSystem::logToLinear(float volume)
260 {
261     // int v = volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
262     // ALOGD("logTolinear(%d)=%f", v, volume);
263     // return v;
264     return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
265 }
266 
calculateMinFrameCount(uint32_t afLatencyMs,uint32_t afFrameCount,uint32_t afSampleRate,uint32_t sampleRate,float speed)267 /* static */ size_t AudioSystem::calculateMinFrameCount(
268         uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
269         uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/)
270 {
271     // Ensure that buffer depth covers at least audio hardware latency
272     uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
273     if (minBufCount < 2) {
274         minBufCount = 2;
275     }
276 #if 0
277     // The notificationsPerBufferReq parameter is not yet used for non-fast tracks,
278     // but keeping the code here to make it easier to add later.
279     if (minBufCount < notificationsPerBufferReq) {
280         minBufCount = notificationsPerBufferReq;
281     }
282 #endif
283     ALOGV("calculateMinFrameCount afLatency %u  afFrameCount %u  afSampleRate %u  "
284             "sampleRate %u  speed %f  minBufCount: %u" /*"  notificationsPerBufferReq %u"*/,
285             afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount
286             /*, notificationsPerBufferReq*/);
287     return minBufCount * sourceFramesNeededWithTimestretch(
288             sampleRate, afFrameCount, afSampleRate, speed);
289 }
290 
291 
getOutputSamplingRate(uint32_t * samplingRate,audio_stream_type_t streamType)292 status_t AudioSystem::getOutputSamplingRate(uint32_t* samplingRate, audio_stream_type_t streamType)
293 {
294     audio_io_handle_t output;
295 
296     if (streamType == AUDIO_STREAM_DEFAULT) {
297         streamType = AUDIO_STREAM_MUSIC;
298     }
299 
300     output = getOutput(streamType);
301     if (output == 0) {
302         return PERMISSION_DENIED;
303     }
304 
305     return getSamplingRate(output, samplingRate);
306 }
307 
getSamplingRate(audio_io_handle_t ioHandle,uint32_t * samplingRate)308 status_t AudioSystem::getSamplingRate(audio_io_handle_t ioHandle,
309                                       uint32_t* samplingRate)
310 {
311     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
312     if (af == 0) return PERMISSION_DENIED;
313     sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
314     if (desc == 0) {
315         *samplingRate = af->sampleRate(ioHandle);
316     } else {
317         *samplingRate = desc->mSamplingRate;
318     }
319     if (*samplingRate == 0) {
320         ALOGE("AudioSystem::getSamplingRate failed for ioHandle %d", ioHandle);
321         return BAD_VALUE;
322     }
323 
324     ALOGV("getSamplingRate() ioHandle %d, sampling rate %u", ioHandle, *samplingRate);
325 
326     return NO_ERROR;
327 }
328 
getOutputFrameCount(size_t * frameCount,audio_stream_type_t streamType)329 status_t AudioSystem::getOutputFrameCount(size_t* frameCount, audio_stream_type_t streamType)
330 {
331     audio_io_handle_t output;
332 
333     if (streamType == AUDIO_STREAM_DEFAULT) {
334         streamType = AUDIO_STREAM_MUSIC;
335     }
336 
337     output = getOutput(streamType);
338     if (output == AUDIO_IO_HANDLE_NONE) {
339         return PERMISSION_DENIED;
340     }
341 
342     return getFrameCount(output, frameCount);
343 }
344 
getFrameCount(audio_io_handle_t ioHandle,size_t * frameCount)345 status_t AudioSystem::getFrameCount(audio_io_handle_t ioHandle,
346                                     size_t* frameCount)
347 {
348     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
349     if (af == 0) return PERMISSION_DENIED;
350     sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
351     if (desc == 0) {
352         *frameCount = af->frameCount(ioHandle);
353     } else {
354         *frameCount = desc->mFrameCount;
355     }
356     if (*frameCount == 0) {
357         ALOGE("AudioSystem::getFrameCount failed for ioHandle %d", ioHandle);
358         return BAD_VALUE;
359     }
360 
361     ALOGV("getFrameCount() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
362 
363     return NO_ERROR;
364 }
365 
getOutputLatency(uint32_t * latency,audio_stream_type_t streamType)366 status_t AudioSystem::getOutputLatency(uint32_t* latency, audio_stream_type_t streamType)
367 {
368     audio_io_handle_t output;
369 
370     if (streamType == AUDIO_STREAM_DEFAULT) {
371         streamType = AUDIO_STREAM_MUSIC;
372     }
373 
374     output = getOutput(streamType);
375     if (output == AUDIO_IO_HANDLE_NONE) {
376         return PERMISSION_DENIED;
377     }
378 
379     return getLatency(output, latency);
380 }
381 
getLatency(audio_io_handle_t output,uint32_t * latency)382 status_t AudioSystem::getLatency(audio_io_handle_t output,
383                                  uint32_t* latency)
384 {
385     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
386     if (af == 0) return PERMISSION_DENIED;
387     sp<AudioIoDescriptor> outputDesc = getIoDescriptor(output);
388     if (outputDesc == 0) {
389         *latency = af->latency(output);
390     } else {
391         *latency = outputDesc->mLatency;
392     }
393 
394     ALOGV("getLatency() output %d, latency %d", output, *latency);
395 
396     return NO_ERROR;
397 }
398 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * buffSize)399 status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
400         audio_channel_mask_t channelMask, size_t* buffSize)
401 {
402     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
403     if (afc == 0) {
404         return NO_INIT;
405     }
406     return afc->getInputBufferSize(sampleRate, format, channelMask, buffSize);
407 }
408 
setVoiceVolume(float value)409 status_t AudioSystem::setVoiceVolume(float value)
410 {
411     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
412     if (af == 0) return PERMISSION_DENIED;
413     return af->setVoiceVolume(value);
414 }
415 
getRenderPosition(audio_io_handle_t output,uint32_t * halFrames,uint32_t * dspFrames)416 status_t AudioSystem::getRenderPosition(audio_io_handle_t output, uint32_t *halFrames,
417                                         uint32_t *dspFrames)
418 {
419     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
420     if (af == 0) return PERMISSION_DENIED;
421 
422     return af->getRenderPosition(halFrames, dspFrames, output);
423 }
424 
getInputFramesLost(audio_io_handle_t ioHandle)425 uint32_t AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle)
426 {
427     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
428     uint32_t result = 0;
429     if (af == 0) return result;
430     if (ioHandle == AUDIO_IO_HANDLE_NONE) return result;
431 
432     result = af->getInputFramesLost(ioHandle);
433     return result;
434 }
435 
newAudioUniqueId(audio_unique_id_use_t use)436 audio_unique_id_t AudioSystem::newAudioUniqueId(audio_unique_id_use_t use)
437 {
438     // Must not use AF as IDs will re-roll on audioserver restart, b/130369529.
439     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
440     if (af == 0) return AUDIO_UNIQUE_ID_ALLOCATE;
441     return af->newAudioUniqueId(use);
442 }
443 
acquireAudioSessionId(audio_session_t audioSession,pid_t pid,uid_t uid)444 void AudioSystem::acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid)
445 {
446     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
447     if (af != 0) {
448         af->acquireAudioSessionId(audioSession, pid, uid);
449     }
450 }
451 
releaseAudioSessionId(audio_session_t audioSession,pid_t pid)452 void AudioSystem::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
453 {
454     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
455     if (af != 0) {
456         af->releaseAudioSessionId(audioSession, pid);
457     }
458 }
459 
getAudioHwSyncForSession(audio_session_t sessionId)460 audio_hw_sync_t AudioSystem::getAudioHwSyncForSession(audio_session_t sessionId)
461 {
462     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
463     if (af == 0) return AUDIO_HW_SYNC_INVALID;
464     return af->getAudioHwSyncForSession(sessionId);
465 }
466 
systemReady()467 status_t AudioSystem::systemReady()
468 {
469     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
470     if (af == 0) return NO_INIT;
471     return af->systemReady();
472 }
473 
getFrameCountHAL(audio_io_handle_t ioHandle,size_t * frameCount)474 status_t AudioSystem::getFrameCountHAL(audio_io_handle_t ioHandle,
475                                        size_t* frameCount)
476 {
477     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
478     if (af == 0) return PERMISSION_DENIED;
479     sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
480     if (desc == 0) {
481         *frameCount = af->frameCountHAL(ioHandle);
482     } else {
483         *frameCount = desc->mFrameCountHAL;
484     }
485     if (*frameCount == 0) {
486         ALOGE("AudioSystem::getFrameCountHAL failed for ioHandle %d", ioHandle);
487         return BAD_VALUE;
488     }
489 
490     ALOGV("getFrameCountHAL() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
491 
492     return NO_ERROR;
493 }
494 
495 // ---------------------------------------------------------------------------
496 
497 
clearIoCache()498 void AudioSystem::AudioFlingerClient::clearIoCache()
499 {
500     Mutex::Autolock _l(mLock);
501     mIoDescriptors.clear();
502     mInBuffSize = 0;
503     mInSamplingRate = 0;
504     mInFormat = AUDIO_FORMAT_DEFAULT;
505     mInChannelMask = AUDIO_CHANNEL_NONE;
506 }
507 
binderDied(const wp<IBinder> & who __unused)508 void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who __unused)
509 {
510     {
511         Mutex::Autolock _l(AudioSystem::gLock);
512         AudioSystem::gAudioFlinger.clear();
513     }
514 
515     // clear output handles and stream to output map caches
516     clearIoCache();
517 
518     reportError(DEAD_OBJECT);
519 
520     ALOGW("AudioFlinger server died!");
521 }
522 
ioConfigChanged(audio_io_config_event event,const sp<AudioIoDescriptor> & ioDesc)523 void AudioSystem::AudioFlingerClient::ioConfigChanged(audio_io_config_event event,
524                                                       const sp<AudioIoDescriptor>& ioDesc) {
525     ALOGV("ioConfigChanged() event %d", event);
526 
527     if (ioDesc == 0 || ioDesc->mIoHandle == AUDIO_IO_HANDLE_NONE) return;
528 
529     audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
530     std::vector<sp<AudioDeviceCallback>> callbacksToCall;
531     {
532         Mutex::Autolock _l(mLock);
533         auto callbacks = std::map<audio_port_handle_t, wp<AudioDeviceCallback>>();
534 
535         switch (event) {
536         case AUDIO_OUTPUT_OPENED:
537         case AUDIO_OUTPUT_REGISTERED:
538         case AUDIO_INPUT_OPENED:
539         case AUDIO_INPUT_REGISTERED: {
540             sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
541             if (oldDesc == 0) {
542                 mIoDescriptors.add(ioDesc->mIoHandle, ioDesc);
543             } else {
544                 deviceId = oldDesc->getDeviceId();
545                 mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc);
546             }
547 
548             if (ioDesc->getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
549                 deviceId = ioDesc->getDeviceId();
550                 if (event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED) {
551                     auto it = mAudioDeviceCallbacks.find(ioDesc->mIoHandle);
552                     if (it != mAudioDeviceCallbacks.end()) {
553                         callbacks = it->second;
554                     }
555                 }
556             }
557             ALOGV("ioConfigChanged() new %s %s %d samplingRate %u, format %#x channel mask %#x "
558                     "frameCount %zu deviceId %d",
559                     event == AUDIO_OUTPUT_OPENED || event == AUDIO_OUTPUT_REGISTERED ?
560                             "output" : "input",
561                             event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED ?
562                             "opened" : "registered",
563                     ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat, ioDesc->mChannelMask,
564                     ioDesc->mFrameCount, ioDesc->getDeviceId());
565             } break;
566         case AUDIO_OUTPUT_CLOSED:
567         case AUDIO_INPUT_CLOSED: {
568             if (getIoDescriptor_l(ioDesc->mIoHandle) == 0) {
569                 ALOGW("ioConfigChanged() closing unknown %s %d",
570                       event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
571                 break;
572             }
573             ALOGV("ioConfigChanged() %s %d closed",
574                   event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
575 
576             mIoDescriptors.removeItem(ioDesc->mIoHandle);
577             mAudioDeviceCallbacks.erase(ioDesc->mIoHandle);
578             } break;
579 
580         case AUDIO_OUTPUT_CONFIG_CHANGED:
581         case AUDIO_INPUT_CONFIG_CHANGED: {
582             sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
583             if (oldDesc == 0) {
584                 ALOGW("ioConfigChanged() modifying unknown output! %d", ioDesc->mIoHandle);
585                 break;
586             }
587 
588             deviceId = oldDesc->getDeviceId();
589             mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc);
590 
591             if (deviceId != ioDesc->getDeviceId()) {
592                 deviceId = ioDesc->getDeviceId();
593                 auto it = mAudioDeviceCallbacks.find(ioDesc->mIoHandle);
594                 if (it != mAudioDeviceCallbacks.end()) {
595                     callbacks = it->second;
596                 }
597             }
598             ALOGV("ioConfigChanged() new config for %s %d samplingRate %u, format %#x "
599                     "channel mask %#x frameCount %zu frameCountHAL %zu deviceId %d",
600                     event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input",
601                     ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat,
602                     ioDesc->mChannelMask, ioDesc->mFrameCount, ioDesc->mFrameCountHAL,
603                     ioDesc->getDeviceId());
604 
605         } break;
606         case AUDIO_CLIENT_STARTED: {
607             sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
608             if (oldDesc == 0) {
609                 ALOGW("ioConfigChanged() start client on unknown io! %d", ioDesc->mIoHandle);
610                 break;
611             }
612             ALOGV("ioConfigChanged() AUDIO_CLIENT_STARTED  io %d port %d num callbacks %zu",
613                 ioDesc->mIoHandle, ioDesc->mPortId, mAudioDeviceCallbacks.size());
614             oldDesc->mPatch = ioDesc->mPatch;
615             auto it = mAudioDeviceCallbacks.find(ioDesc->mIoHandle);
616             if (it != mAudioDeviceCallbacks.end()) {
617                 auto cbks = it->second;
618                 auto it2 = cbks.find(ioDesc->mPortId);
619                 if (it2 != cbks.end()) {
620                    callbacks.emplace(ioDesc->mPortId, it2->second);
621                    deviceId = oldDesc->getDeviceId();
622                 }
623             }
624         } break;
625         }
626 
627         for (auto wpCbk : callbacks) {
628             sp<AudioDeviceCallback> spCbk = wpCbk.second.promote();
629             if (spCbk != nullptr) {
630                 callbacksToCall.push_back(spCbk);
631             }
632         }
633     }
634 
635     // Callbacks must be called without mLock held. May lead to dead lock if calling for
636     // example getRoutedDevice that updates the device and tries to acquire mLock.
637     for (auto cb  : callbacksToCall) {
638         // If callbacksToCall is not empty, it implies ioDesc->mIoHandle and deviceId are valid
639         cb->onAudioDeviceUpdate(ioDesc->mIoHandle, deviceId);
640     }
641 }
642 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * buffSize)643 status_t AudioSystem::AudioFlingerClient::getInputBufferSize(
644                                                 uint32_t sampleRate, audio_format_t format,
645                                                 audio_channel_mask_t channelMask, size_t* buffSize)
646 {
647     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
648     if (af == 0) {
649         return PERMISSION_DENIED;
650     }
651     Mutex::Autolock _l(mLock);
652     // Do we have a stale mInBuffSize or are we requesting the input buffer size for new values
653     if ((mInBuffSize == 0) || (sampleRate != mInSamplingRate) || (format != mInFormat)
654         || (channelMask != mInChannelMask)) {
655         size_t inBuffSize = af->getInputBufferSize(sampleRate, format, channelMask);
656         if (inBuffSize == 0) {
657             ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %#x channelMask %#x",
658                     sampleRate, format, channelMask);
659             return BAD_VALUE;
660         }
661         // A benign race is possible here: we could overwrite a fresher cache entry
662         // save the request params
663         mInSamplingRate = sampleRate;
664         mInFormat = format;
665         mInChannelMask = channelMask;
666 
667         mInBuffSize = inBuffSize;
668     }
669 
670     *buffSize = mInBuffSize;
671 
672     return NO_ERROR;
673 }
674 
getIoDescriptor_l(audio_io_handle_t ioHandle)675 sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor_l(audio_io_handle_t ioHandle)
676 {
677     sp<AudioIoDescriptor> desc;
678     ssize_t index = mIoDescriptors.indexOfKey(ioHandle);
679     if (index >= 0) {
680         desc = mIoDescriptors.valueAt(index);
681     }
682     return desc;
683 }
684 
getIoDescriptor(audio_io_handle_t ioHandle)685 sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor(audio_io_handle_t ioHandle)
686 {
687     Mutex::Autolock _l(mLock);
688     return getIoDescriptor_l(ioHandle);
689 }
690 
addAudioDeviceCallback(const wp<AudioDeviceCallback> & callback,audio_io_handle_t audioIo,audio_port_handle_t portId)691 status_t AudioSystem::AudioFlingerClient::addAudioDeviceCallback(
692         const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo,
693         audio_port_handle_t portId)
694 {
695     ALOGV("%s audioIo %d portId %d", __func__, audioIo, portId);
696     Mutex::Autolock _l(mLock);
697     auto& callbacks = mAudioDeviceCallbacks.emplace(audioIo, std::map<audio_port_handle_t, wp<AudioDeviceCallback>>()).first->second;
698     auto result = callbacks.try_emplace(portId, callback);
699     if (!result.second) {
700         return INVALID_OPERATION;
701     }
702     return NO_ERROR;
703 }
704 
removeAudioDeviceCallback(const wp<AudioDeviceCallback> & callback __unused,audio_io_handle_t audioIo,audio_port_handle_t portId)705 status_t AudioSystem::AudioFlingerClient::removeAudioDeviceCallback(
706         const wp<AudioDeviceCallback>& callback __unused, audio_io_handle_t audioIo,
707         audio_port_handle_t portId)
708 {
709     ALOGV("%s audioIo %d portId %d", __func__, audioIo, portId);
710     Mutex::Autolock _l(mLock);
711     auto it = mAudioDeviceCallbacks.find(audioIo);
712     if (it == mAudioDeviceCallbacks.end()) {
713         return INVALID_OPERATION;
714     }
715     if (it->second.erase(portId) == 0) {
716         return INVALID_OPERATION;
717     }
718     if (it->second.size() == 0) {
719         mAudioDeviceCallbacks.erase(audioIo);
720     }
721     return NO_ERROR;
722 }
723 
addErrorCallback(audio_error_callback cb)724 /* static */ uintptr_t AudioSystem::addErrorCallback(audio_error_callback cb)
725 {
726     Mutex::Autolock _l(gLockErrorCallbacks);
727     gAudioErrorCallbacks.insert(cb);
728     return reinterpret_cast<uintptr_t>(cb);
729 }
730 
removeErrorCallback(uintptr_t cb)731 /* static */ void AudioSystem::removeErrorCallback(uintptr_t cb) {
732     Mutex::Autolock _l(gLockErrorCallbacks);
733     gAudioErrorCallbacks.erase(reinterpret_cast<audio_error_callback>(cb));
734 }
735 
reportError(status_t err)736 /* static */ void AudioSystem::reportError(status_t err) {
737     Mutex::Autolock _l(gLockErrorCallbacks);
738     for (auto callback : gAudioErrorCallbacks) {
739       callback(err);
740     }
741 }
742 
setDynPolicyCallback(dynamic_policy_callback cb)743 /*static*/ void AudioSystem::setDynPolicyCallback(dynamic_policy_callback cb)
744 {
745     Mutex::Autolock _l(gLock);
746     gDynPolicyCallback = cb;
747 }
748 
setRecordConfigCallback(record_config_callback cb)749 /*static*/ void AudioSystem::setRecordConfigCallback(record_config_callback cb)
750 {
751     Mutex::Autolock _l(gLock);
752     gRecordConfigCallback = cb;
753 }
754 
755 // client singleton for AudioPolicyService binder interface
756 // protected by gLockAPS
757 sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
758 sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
759 
760 
761 // establish binder interface to AudioPolicy service
get_audio_policy_service()762 const sp<IAudioPolicyService> AudioSystem::get_audio_policy_service()
763 {
764     sp<IAudioPolicyService> ap;
765     sp<AudioPolicyServiceClient> apc;
766     {
767         Mutex::Autolock _l(gLockAPS);
768         if (gAudioPolicyService == 0) {
769             sp<IServiceManager> sm = defaultServiceManager();
770             sp<IBinder> binder;
771             do {
772                 binder = sm->getService(String16("media.audio_policy"));
773                 if (binder != 0)
774                     break;
775                 ALOGW("AudioPolicyService not published, waiting...");
776                 usleep(500000); // 0.5 s
777             } while (true);
778             if (gAudioPolicyServiceClient == NULL) {
779                 gAudioPolicyServiceClient = new AudioPolicyServiceClient();
780             }
781             binder->linkToDeath(gAudioPolicyServiceClient);
782             gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
783             LOG_ALWAYS_FATAL_IF(gAudioPolicyService == 0);
784             apc = gAudioPolicyServiceClient;
785             // Make sure callbacks can be received by gAudioPolicyServiceClient
786             ProcessState::self()->startThreadPool();
787         }
788         ap = gAudioPolicyService;
789     }
790     if (apc != 0) {
791         int64_t token = IPCThreadState::self()->clearCallingIdentity();
792         ap->registerClient(apc);
793         ap->setAudioPortCallbacksEnabled(apc->isAudioPortCbEnabled());
794         ap->setAudioVolumeGroupCallbacksEnabled(apc->isAudioVolumeGroupCbEnabled());
795         IPCThreadState::self()->restoreCallingIdentity(token);
796     }
797 
798     return ap;
799 }
800 
801 // ---------------------------------------------------------------------------
802 
onNewAudioModulesAvailable()803 void AudioSystem::onNewAudioModulesAvailable()
804 {
805     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
806     if (aps == 0) return;
807     aps->onNewAudioModulesAvailable();
808 }
809 
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)810 status_t AudioSystem::setDeviceConnectionState(audio_devices_t device,
811                                                audio_policy_dev_state_t state,
812                                                const char *device_address,
813                                                const char *device_name,
814                                                audio_format_t encodedFormat)
815 {
816     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
817     const char *address = "";
818     const char *name = "";
819 
820     if (aps == 0) return PERMISSION_DENIED;
821 
822     if (device_address != NULL) {
823         address = device_address;
824     }
825     if (device_name != NULL) {
826         name = device_name;
827     }
828     return aps->setDeviceConnectionState(device, state, address, name, encodedFormat);
829 }
830 
getDeviceConnectionState(audio_devices_t device,const char * device_address)831 audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t device,
832                                                   const char *device_address)
833 {
834     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
835     if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
836 
837     return aps->getDeviceConnectionState(device, device_address);
838 }
839 
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name,audio_format_t encodedFormat)840 status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device,
841                                                const char *device_address,
842                                                const char *device_name,
843                                                audio_format_t encodedFormat)
844 {
845     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
846     const char *address = "";
847     const char *name = "";
848 
849     if (aps == 0) return PERMISSION_DENIED;
850 
851     if (device_address != NULL) {
852         address = device_address;
853     }
854     if (device_name != NULL) {
855         name = device_name;
856     }
857     return aps->handleDeviceConfigChange(device, address, name, encodedFormat);
858 }
859 
setPhoneState(audio_mode_t state,uid_t uid)860 status_t AudioSystem::setPhoneState(audio_mode_t state, uid_t uid)
861 {
862     if (uint32_t(state) >= AUDIO_MODE_CNT) return BAD_VALUE;
863     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
864     if (aps == 0) return PERMISSION_DENIED;
865 
866     return aps->setPhoneState(state, uid);
867 }
868 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)869 status_t AudioSystem::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
870 {
871     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
872     if (aps == 0) return PERMISSION_DENIED;
873     return aps->setForceUse(usage, config);
874 }
875 
getForceUse(audio_policy_force_use_t usage)876 audio_policy_forced_cfg_t AudioSystem::getForceUse(audio_policy_force_use_t usage)
877 {
878     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
879     if (aps == 0) return AUDIO_POLICY_FORCE_NONE;
880     return aps->getForceUse(usage);
881 }
882 
883 
getOutput(audio_stream_type_t stream)884 audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream)
885 {
886     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
887     if (aps == 0) return 0;
888     return aps->getOutput(stream);
889 }
890 
getOutputForAttr(audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,pid_t pid,uid_t uid,const audio_config_t * config,audio_output_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId,std::vector<audio_io_handle_t> * secondaryOutputs)891 status_t AudioSystem::getOutputForAttr(audio_attributes_t *attr,
892                                         audio_io_handle_t *output,
893                                         audio_session_t session,
894                                         audio_stream_type_t *stream,
895                                         pid_t pid,
896                                         uid_t uid,
897                                         const audio_config_t *config,
898                                         audio_output_flags_t flags,
899                                         audio_port_handle_t *selectedDeviceId,
900                                         audio_port_handle_t *portId,
901                                         std::vector<audio_io_handle_t> *secondaryOutputs)
902 {
903     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
904     if (aps == 0) return NO_INIT;
905     return aps->getOutputForAttr(attr, output, session, stream, pid, uid,
906                                  config,
907                                  flags, selectedDeviceId, portId, secondaryOutputs);
908 }
909 
startOutput(audio_port_handle_t portId)910 status_t AudioSystem::startOutput(audio_port_handle_t portId)
911 {
912     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
913     if (aps == 0) return PERMISSION_DENIED;
914     return aps->startOutput(portId);
915 }
916 
stopOutput(audio_port_handle_t portId)917 status_t AudioSystem::stopOutput(audio_port_handle_t portId)
918 {
919     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
920     if (aps == 0) return PERMISSION_DENIED;
921     return aps->stopOutput(portId);
922 }
923 
releaseOutput(audio_port_handle_t portId)924 void AudioSystem::releaseOutput(audio_port_handle_t portId)
925 {
926     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
927     if (aps == 0) return;
928     aps->releaseOutput(portId);
929 }
930 
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_unique_id_t riid,audio_session_t session,pid_t pid,uid_t uid,const String16 & opPackageName,const audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId)931 status_t AudioSystem::getInputForAttr(const audio_attributes_t *attr,
932                                 audio_io_handle_t *input,
933                                 audio_unique_id_t riid,
934                                 audio_session_t session,
935                                 pid_t pid,
936                                 uid_t uid,
937                                 const String16& opPackageName,
938                                 const audio_config_base_t *config,
939                                 audio_input_flags_t flags,
940                                 audio_port_handle_t *selectedDeviceId,
941                                 audio_port_handle_t *portId)
942 {
943     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
944     if (aps == 0) return NO_INIT;
945     return aps->getInputForAttr(
946             attr, input, riid, session, pid, uid, opPackageName,
947             config, flags, selectedDeviceId, portId);
948 }
949 
startInput(audio_port_handle_t portId)950 status_t AudioSystem::startInput(audio_port_handle_t portId)
951 {
952     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
953     if (aps == 0) return PERMISSION_DENIED;
954     return aps->startInput(portId);
955 }
956 
stopInput(audio_port_handle_t portId)957 status_t AudioSystem::stopInput(audio_port_handle_t portId)
958 {
959     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
960     if (aps == 0) return PERMISSION_DENIED;
961     return aps->stopInput(portId);
962 }
963 
releaseInput(audio_port_handle_t portId)964 void AudioSystem::releaseInput(audio_port_handle_t portId)
965 {
966     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
967     if (aps == 0) return;
968     aps->releaseInput(portId);
969 }
970 
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)971 status_t AudioSystem::initStreamVolume(audio_stream_type_t stream,
972                                     int indexMin,
973                                     int indexMax)
974 {
975     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
976     if (aps == 0) return PERMISSION_DENIED;
977     return aps->initStreamVolume(stream, indexMin, indexMax);
978 }
979 
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)980 status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
981                                            int index,
982                                            audio_devices_t device)
983 {
984     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
985     if (aps == 0) return PERMISSION_DENIED;
986     return aps->setStreamVolumeIndex(stream, index, device);
987 }
988 
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)989 status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
990                                            int *index,
991                                            audio_devices_t device)
992 {
993     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
994     if (aps == 0) return PERMISSION_DENIED;
995     return aps->getStreamVolumeIndex(stream, index, device);
996 }
997 
setVolumeIndexForAttributes(const audio_attributes_t & attr,int index,audio_devices_t device)998 status_t AudioSystem::setVolumeIndexForAttributes(const audio_attributes_t &attr,
999                                                   int index,
1000                                                   audio_devices_t device)
1001 {
1002     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1003     if (aps == 0) return PERMISSION_DENIED;
1004     return aps->setVolumeIndexForAttributes(attr, index, device);
1005 }
1006 
getVolumeIndexForAttributes(const audio_attributes_t & attr,int & index,audio_devices_t device)1007 status_t AudioSystem::getVolumeIndexForAttributes(const audio_attributes_t &attr,
1008                                                   int &index,
1009                                                   audio_devices_t device)
1010 {
1011     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1012     if (aps == 0) return PERMISSION_DENIED;
1013     return aps->getVolumeIndexForAttributes(attr, index, device);
1014 }
1015 
getMaxVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)1016 status_t AudioSystem::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr, int &index)
1017 {
1018     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1019     if (aps == 0) return PERMISSION_DENIED;
1020     return aps->getMaxVolumeIndexForAttributes(attr, index);
1021 }
1022 
getMinVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)1023 status_t AudioSystem::getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index)
1024 {
1025     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1026     if (aps == 0) return PERMISSION_DENIED;
1027     return aps->getMinVolumeIndexForAttributes(attr, index);
1028 }
1029 
getStrategyForStream(audio_stream_type_t stream)1030 uint32_t AudioSystem::getStrategyForStream(audio_stream_type_t stream)
1031 {
1032     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1033     if (aps == 0) return PRODUCT_STRATEGY_NONE;
1034     return aps->getStrategyForStream(stream);
1035 }
1036 
getDevicesForStream(audio_stream_type_t stream)1037 audio_devices_t AudioSystem::getDevicesForStream(audio_stream_type_t stream)
1038 {
1039     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1040     if (aps == 0) return AUDIO_DEVICE_NONE;
1041     return aps->getDevicesForStream(stream);
1042 }
1043 
getDevicesForAttributes(const AudioAttributes & aa,AudioDeviceTypeAddrVector * devices)1044 status_t AudioSystem::getDevicesForAttributes(const AudioAttributes &aa,
1045                                               AudioDeviceTypeAddrVector *devices) {
1046     if (devices == nullptr) {
1047         return BAD_VALUE;
1048     }
1049     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1050     if (aps == 0) return PERMISSION_DENIED;
1051     return aps->getDevicesForAttributes(aa, devices);
1052 }
1053 
getOutputForEffect(const effect_descriptor_t * desc)1054 audio_io_handle_t AudioSystem::getOutputForEffect(const effect_descriptor_t *desc)
1055 {
1056     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1057     // FIXME change return type to status_t, and return PERMISSION_DENIED here
1058     if (aps == 0) return AUDIO_IO_HANDLE_NONE;
1059     return aps->getOutputForEffect(desc);
1060 }
1061 
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,audio_session_t session,int id)1062 status_t AudioSystem::registerEffect(const effect_descriptor_t *desc,
1063                                 audio_io_handle_t io,
1064                                 uint32_t strategy,
1065                                 audio_session_t session,
1066                                 int id)
1067 {
1068     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1069     if (aps == 0) return PERMISSION_DENIED;
1070     return aps->registerEffect(desc, io, strategy, session, id);
1071 }
1072 
unregisterEffect(int id)1073 status_t AudioSystem::unregisterEffect(int id)
1074 {
1075     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1076     if (aps == 0) return PERMISSION_DENIED;
1077     return aps->unregisterEffect(id);
1078 }
1079 
setEffectEnabled(int id,bool enabled)1080 status_t AudioSystem::setEffectEnabled(int id, bool enabled)
1081 {
1082     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1083     if (aps == 0) return PERMISSION_DENIED;
1084     return aps->setEffectEnabled(id, enabled);
1085 }
1086 
moveEffectsToIo(const std::vector<int> & ids,audio_io_handle_t io)1087 status_t AudioSystem::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
1088 {
1089     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1090     if (aps == 0) return PERMISSION_DENIED;
1091     return aps->moveEffectsToIo(ids, io);
1092 }
1093 
isStreamActive(audio_stream_type_t stream,bool * state,uint32_t inPastMs)1094 status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs)
1095 {
1096     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1097     if (aps == 0) return PERMISSION_DENIED;
1098     if (state == NULL) return BAD_VALUE;
1099     *state = aps->isStreamActive(stream, inPastMs);
1100     return NO_ERROR;
1101 }
1102 
isStreamActiveRemotely(audio_stream_type_t stream,bool * state,uint32_t inPastMs)1103 status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* state,
1104         uint32_t inPastMs)
1105 {
1106     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1107     if (aps == 0) return PERMISSION_DENIED;
1108     if (state == NULL) return BAD_VALUE;
1109     *state = aps->isStreamActiveRemotely(stream, inPastMs);
1110     return NO_ERROR;
1111 }
1112 
isSourceActive(audio_source_t stream,bool * state)1113 status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state)
1114 {
1115     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1116     if (aps == 0) return PERMISSION_DENIED;
1117     if (state == NULL) return BAD_VALUE;
1118     *state = aps->isSourceActive(stream);
1119     return NO_ERROR;
1120 }
1121 
getPrimaryOutputSamplingRate()1122 uint32_t AudioSystem::getPrimaryOutputSamplingRate()
1123 {
1124     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1125     if (af == 0) return 0;
1126     return af->getPrimaryOutputSamplingRate();
1127 }
1128 
getPrimaryOutputFrameCount()1129 size_t AudioSystem::getPrimaryOutputFrameCount()
1130 {
1131     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1132     if (af == 0) return 0;
1133     return af->getPrimaryOutputFrameCount();
1134 }
1135 
setLowRamDevice(bool isLowRamDevice,int64_t totalMemory)1136 status_t AudioSystem::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
1137 {
1138     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1139     if (af == 0) return PERMISSION_DENIED;
1140     return af->setLowRamDevice(isLowRamDevice, totalMemory);
1141 }
1142 
clearAudioConfigCache()1143 void AudioSystem::clearAudioConfigCache()
1144 {
1145     // called by restoreTrack_l(), which needs new IAudioFlinger and IAudioPolicyService instances
1146     ALOGV("clearAudioConfigCache()");
1147     {
1148         Mutex::Autolock _l(gLock);
1149         if (gAudioFlingerClient != 0) {
1150             gAudioFlingerClient->clearIoCache();
1151         }
1152         gAudioFlinger.clear();
1153     }
1154     {
1155         Mutex::Autolock _l(gLockAPS);
1156         gAudioPolicyService.clear();
1157     }
1158 }
1159 
setSupportedSystemUsages(const std::vector<audio_usage_t> & systemUsages)1160 status_t AudioSystem::setSupportedSystemUsages(const std::vector<audio_usage_t>& systemUsages) {
1161     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1162     if (aps == nullptr) return PERMISSION_DENIED;
1163     return aps->setSupportedSystemUsages(systemUsages);
1164 }
1165 
setAllowedCapturePolicy(uid_t uid,audio_flags_mask_t flags)1166 status_t AudioSystem::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t flags) {
1167     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1168     if (aps == nullptr) return PERMISSION_DENIED;
1169     return aps->setAllowedCapturePolicy(uid, flags);
1170 }
1171 
isOffloadSupported(const audio_offload_info_t & info)1172 bool AudioSystem::isOffloadSupported(const audio_offload_info_t& info)
1173 {
1174     ALOGV("isOffloadSupported()");
1175     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1176     if (aps == 0) return false;
1177     return aps->isOffloadSupported(info);
1178 }
1179 
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)1180 status_t AudioSystem::listAudioPorts(audio_port_role_t role,
1181                                      audio_port_type_t type,
1182                                      unsigned int *num_ports,
1183                                      struct audio_port *ports,
1184                                      unsigned int *generation)
1185 {
1186     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1187     if (aps == 0) return PERMISSION_DENIED;
1188     return aps->listAudioPorts(role, type, num_ports, ports, generation);
1189 }
1190 
getAudioPort(struct audio_port * port)1191 status_t AudioSystem::getAudioPort(struct audio_port *port)
1192 {
1193     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1194     if (aps == 0) return PERMISSION_DENIED;
1195     return aps->getAudioPort(port);
1196 }
1197 
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)1198 status_t AudioSystem::createAudioPatch(const struct audio_patch *patch,
1199                                    audio_patch_handle_t *handle)
1200 {
1201     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1202     if (aps == 0) return PERMISSION_DENIED;
1203     return aps->createAudioPatch(patch, handle);
1204 }
1205 
releaseAudioPatch(audio_patch_handle_t handle)1206 status_t AudioSystem::releaseAudioPatch(audio_patch_handle_t handle)
1207 {
1208     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1209     if (aps == 0) return PERMISSION_DENIED;
1210     return aps->releaseAudioPatch(handle);
1211 }
1212 
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)1213 status_t AudioSystem::listAudioPatches(unsigned int *num_patches,
1214                                   struct audio_patch *patches,
1215                                   unsigned int *generation)
1216 {
1217     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1218     if (aps == 0) return PERMISSION_DENIED;
1219     return aps->listAudioPatches(num_patches, patches, generation);
1220 }
1221 
setAudioPortConfig(const struct audio_port_config * config)1222 status_t AudioSystem::setAudioPortConfig(const struct audio_port_config *config)
1223 {
1224     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1225     if (aps == 0) return PERMISSION_DENIED;
1226     return aps->setAudioPortConfig(config);
1227 }
1228 
addAudioPortCallback(const sp<AudioPortCallback> & callback)1229 status_t AudioSystem::addAudioPortCallback(const sp<AudioPortCallback>& callback)
1230 {
1231     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1232     if (aps == 0) return PERMISSION_DENIED;
1233 
1234     Mutex::Autolock _l(gLockAPS);
1235     if (gAudioPolicyServiceClient == 0) {
1236         return NO_INIT;
1237     }
1238     int ret = gAudioPolicyServiceClient->addAudioPortCallback(callback);
1239     if (ret == 1) {
1240         aps->setAudioPortCallbacksEnabled(true);
1241     }
1242     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1243 }
1244 
1245 /*static*/
removeAudioPortCallback(const sp<AudioPortCallback> & callback)1246 status_t AudioSystem::removeAudioPortCallback(const sp<AudioPortCallback>& callback)
1247 {
1248     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1249     if (aps == 0) return PERMISSION_DENIED;
1250 
1251     Mutex::Autolock _l(gLockAPS);
1252     if (gAudioPolicyServiceClient == 0) {
1253         return NO_INIT;
1254     }
1255     int ret = gAudioPolicyServiceClient->removeAudioPortCallback(callback);
1256     if (ret == 0) {
1257         aps->setAudioPortCallbacksEnabled(false);
1258     }
1259     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1260 }
1261 
addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)1262 status_t AudioSystem::addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback)
1263 {
1264     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1265     if (aps == 0) return PERMISSION_DENIED;
1266 
1267     Mutex::Autolock _l(gLockAPS);
1268     if (gAudioPolicyServiceClient == 0) {
1269         return NO_INIT;
1270     }
1271     int ret = gAudioPolicyServiceClient->addAudioVolumeGroupCallback(callback);
1272     if (ret == 1) {
1273         aps->setAudioVolumeGroupCallbacksEnabled(true);
1274     }
1275     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1276 }
1277 
removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)1278 status_t AudioSystem::removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback)
1279 {
1280     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1281     if (aps == 0) return PERMISSION_DENIED;
1282 
1283     Mutex::Autolock _l(gLockAPS);
1284     if (gAudioPolicyServiceClient == 0) {
1285         return NO_INIT;
1286     }
1287     int ret = gAudioPolicyServiceClient->removeAudioVolumeGroupCallback(callback);
1288     if (ret == 0) {
1289         aps->setAudioVolumeGroupCallbacksEnabled(false);
1290     }
1291     return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1292 }
1293 
addAudioDeviceCallback(const wp<AudioDeviceCallback> & callback,audio_io_handle_t audioIo,audio_port_handle_t portId)1294 status_t AudioSystem::addAudioDeviceCallback(
1295         const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo,
1296         audio_port_handle_t portId)
1297 {
1298     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1299     if (afc == 0) {
1300         return NO_INIT;
1301     }
1302     status_t status = afc->addAudioDeviceCallback(callback, audioIo, portId);
1303     if (status == NO_ERROR) {
1304         const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1305         if (af != 0) {
1306             af->registerClient(afc);
1307         }
1308     }
1309     return status;
1310 }
1311 
removeAudioDeviceCallback(const wp<AudioDeviceCallback> & callback,audio_io_handle_t audioIo,audio_port_handle_t portId)1312 status_t AudioSystem::removeAudioDeviceCallback(
1313         const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo,
1314         audio_port_handle_t portId)
1315 {
1316     const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1317     if (afc == 0) {
1318         return NO_INIT;
1319     }
1320     return afc->removeAudioDeviceCallback(callback, audioIo, portId);
1321 }
1322 
getDeviceIdForIo(audio_io_handle_t audioIo)1323 audio_port_handle_t AudioSystem::getDeviceIdForIo(audio_io_handle_t audioIo)
1324 {
1325     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1326     if (af == 0) return PERMISSION_DENIED;
1327     const sp<AudioIoDescriptor> desc = getIoDescriptor(audioIo);
1328     if (desc == 0) {
1329         return AUDIO_PORT_HANDLE_NONE;
1330     }
1331     return desc->getDeviceId();
1332 }
1333 
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)1334 status_t AudioSystem::acquireSoundTriggerSession(audio_session_t *session,
1335                                        audio_io_handle_t *ioHandle,
1336                                        audio_devices_t *device)
1337 {
1338     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1339     if (aps == 0) return PERMISSION_DENIED;
1340     return aps->acquireSoundTriggerSession(session, ioHandle, device);
1341 }
1342 
releaseSoundTriggerSession(audio_session_t session)1343 status_t AudioSystem::releaseSoundTriggerSession(audio_session_t session)
1344 {
1345     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1346     if (aps == 0) return PERMISSION_DENIED;
1347     return aps->releaseSoundTriggerSession(session);
1348 }
1349 
getPhoneState()1350 audio_mode_t AudioSystem::getPhoneState()
1351 {
1352     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1353     if (aps == 0) return AUDIO_MODE_INVALID;
1354     return aps->getPhoneState();
1355 }
1356 
registerPolicyMixes(const Vector<AudioMix> & mixes,bool registration)1357 status_t AudioSystem::registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration)
1358 {
1359     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1360     if (aps == 0) return PERMISSION_DENIED;
1361     return aps->registerPolicyMixes(mixes, registration);
1362 }
1363 
setUidDeviceAffinities(uid_t uid,const Vector<AudioDeviceTypeAddr> & devices)1364 status_t AudioSystem::setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices)
1365 {
1366     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1367     if (aps == 0) return PERMISSION_DENIED;
1368     return aps->setUidDeviceAffinities(uid, devices);
1369 }
1370 
removeUidDeviceAffinities(uid_t uid)1371 status_t AudioSystem::removeUidDeviceAffinities(uid_t uid) {
1372     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1373     if (aps == 0) return PERMISSION_DENIED;
1374     return aps->removeUidDeviceAffinities(uid);
1375 }
1376 
setUserIdDeviceAffinities(int userId,const Vector<AudioDeviceTypeAddr> & devices)1377 status_t AudioSystem::setUserIdDeviceAffinities(int userId,
1378                                                 const Vector<AudioDeviceTypeAddr>& devices)
1379 {
1380     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1381     if (aps == 0) return PERMISSION_DENIED;
1382     return aps->setUserIdDeviceAffinities(userId, devices);
1383 }
1384 
removeUserIdDeviceAffinities(int userId)1385 status_t AudioSystem::removeUserIdDeviceAffinities(int userId)
1386 {
1387     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1388     if (aps == 0) return PERMISSION_DENIED;
1389     return aps->removeUserIdDeviceAffinities(userId);
1390 }
1391 
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId)1392 status_t AudioSystem::startAudioSource(const struct audio_port_config *source,
1393                                        const audio_attributes_t *attributes,
1394                                        audio_port_handle_t *portId)
1395 {
1396     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1397     if (aps == 0) return PERMISSION_DENIED;
1398     return aps->startAudioSource(source, attributes, portId);
1399 }
1400 
stopAudioSource(audio_port_handle_t portId)1401 status_t AudioSystem::stopAudioSource(audio_port_handle_t portId)
1402 {
1403     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1404     if (aps == 0) return PERMISSION_DENIED;
1405     return aps->stopAudioSource(portId);
1406 }
1407 
setMasterMono(bool mono)1408 status_t AudioSystem::setMasterMono(bool mono)
1409 {
1410     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1411     if (aps == 0) return PERMISSION_DENIED;
1412     return aps->setMasterMono(mono);
1413 }
1414 
getMasterMono(bool * mono)1415 status_t AudioSystem::getMasterMono(bool *mono)
1416 {
1417     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1418     if (aps == 0) return PERMISSION_DENIED;
1419     return aps->getMasterMono(mono);
1420 }
1421 
setMasterBalance(float balance)1422 status_t AudioSystem::setMasterBalance(float balance)
1423 {
1424     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1425     if (af == 0) return PERMISSION_DENIED;
1426     return af->setMasterBalance(balance);
1427 }
1428 
getMasterBalance(float * balance)1429 status_t AudioSystem::getMasterBalance(float *balance)
1430 {
1431     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1432     if (af == 0) return PERMISSION_DENIED;
1433     return af->getMasterBalance(balance);
1434 }
1435 
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)1436 float AudioSystem::getStreamVolumeDB(audio_stream_type_t stream, int index, audio_devices_t device)
1437 {
1438     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1439     if (aps == 0) return NAN;
1440     return aps->getStreamVolumeDB(stream, index, device);
1441 }
1442 
getMicrophones(std::vector<media::MicrophoneInfo> * microphones)1443 status_t AudioSystem::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
1444 {
1445     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1446     if (af == 0) return PERMISSION_DENIED;
1447     return af->getMicrophones(microphones);
1448 }
1449 
setAudioHalPids(const std::vector<pid_t> & pids)1450 status_t AudioSystem::setAudioHalPids(const std::vector<pid_t>& pids) {
1451   const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1452   if (af == nullptr) return PERMISSION_DENIED;
1453   return af->setAudioHalPids(pids);
1454 }
1455 
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled,bool reported)1456 status_t AudioSystem::getSurroundFormats(unsigned int *numSurroundFormats,
1457                                          audio_format_t *surroundFormats,
1458                                          bool *surroundFormatsEnabled,
1459                                          bool reported)
1460 {
1461     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1462     if (aps == 0) return PERMISSION_DENIED;
1463     return aps->getSurroundFormats(
1464             numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
1465 }
1466 
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)1467 status_t AudioSystem::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
1468 {
1469     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1470     if (aps == 0) return PERMISSION_DENIED;
1471     return aps->setSurroundFormatEnabled(audioFormat, enabled);
1472 }
1473 
setAssistantUid(uid_t uid)1474 status_t AudioSystem::setAssistantUid(uid_t uid)
1475 {
1476     const sp <IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1477     if (aps == 0) return PERMISSION_DENIED;
1478 
1479     return aps->setAssistantUid(uid);
1480 }
1481 
setA11yServicesUids(const std::vector<uid_t> & uids)1482 status_t AudioSystem::setA11yServicesUids(const std::vector<uid_t>& uids)
1483 {
1484     const sp <IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1485     if (aps == 0) return PERMISSION_DENIED;
1486 
1487     return aps->setA11yServicesUids(uids);
1488 }
1489 
setCurrentImeUid(uid_t uid)1490 status_t AudioSystem::setCurrentImeUid(uid_t uid)
1491 {
1492     const sp <IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1493     if (aps == 0) return PERMISSION_DENIED;
1494 
1495     return aps->setCurrentImeUid(uid);
1496 }
1497 
isHapticPlaybackSupported()1498 bool AudioSystem::isHapticPlaybackSupported()
1499 {
1500     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1501     if (aps == 0) return false;
1502     return aps->isHapticPlaybackSupported();
1503 }
1504 
getHwOffloadEncodingFormatsSupportedForA2DP(std::vector<audio_format_t> * formats)1505 status_t AudioSystem::getHwOffloadEncodingFormatsSupportedForA2DP(
1506                                 std::vector<audio_format_t> *formats) {
1507     const sp <IAudioPolicyService>
1508         & aps = AudioSystem::get_audio_policy_service();
1509     if (aps == 0) return PERMISSION_DENIED;
1510     return aps->getHwOffloadEncodingFormatsSupportedForA2DP(formats);
1511 }
1512 
listAudioProductStrategies(AudioProductStrategyVector & strategies)1513 status_t AudioSystem::listAudioProductStrategies(AudioProductStrategyVector &strategies)
1514 {
1515     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1516     if (aps == 0) return PERMISSION_DENIED;
1517     return aps->listAudioProductStrategies(strategies);
1518 }
1519 
streamTypeToAttributes(audio_stream_type_t stream)1520 audio_attributes_t AudioSystem::streamTypeToAttributes(audio_stream_type_t stream)
1521 {
1522     AudioProductStrategyVector strategies;
1523     listAudioProductStrategies(strategies);
1524     for (const auto &strategy : strategies) {
1525         auto attrVect = strategy.getAudioAttributes();
1526         auto iter = std::find_if(begin(attrVect), end(attrVect), [&stream](const auto &attributes) {
1527                          return attributes.getStreamType() == stream; });
1528         if (iter != end(attrVect)) {
1529             return iter->getAttributes();
1530         }
1531     }
1532     ALOGE("invalid stream type %s when converting to attributes",  toString(stream).c_str());
1533     return AUDIO_ATTRIBUTES_INITIALIZER;
1534 }
1535 
attributesToStreamType(const audio_attributes_t & attr)1536 audio_stream_type_t AudioSystem::attributesToStreamType(const audio_attributes_t &attr)
1537 {
1538     product_strategy_t psId;
1539     status_t ret = AudioSystem::getProductStrategyFromAudioAttributes(AudioAttributes(attr), psId);
1540     if (ret != NO_ERROR) {
1541         ALOGE("no strategy found for attributes %s",  toString(attr).c_str());
1542         return AUDIO_STREAM_MUSIC;
1543     }
1544     AudioProductStrategyVector strategies;
1545     listAudioProductStrategies(strategies);
1546     for (const auto &strategy : strategies) {
1547         if (strategy.getId() == psId) {
1548             auto attrVect = strategy.getAudioAttributes();
1549             auto iter = std::find_if(begin(attrVect), end(attrVect), [&attr](const auto &refAttr) {
1550                              return AudioProductStrategy::attributesMatches(
1551                                  refAttr.getAttributes(), attr); });
1552             if (iter != end(attrVect)) {
1553                 return iter->getStreamType();
1554             }
1555         }
1556     }
1557     switch (attr.usage) {
1558         case AUDIO_USAGE_VIRTUAL_SOURCE:
1559             // virtual source is not expected to have an associated product strategy
1560             break;
1561         default:
1562             ALOGE("invalid attributes %s when converting to stream",  toString(attr).c_str());
1563             break;
1564     }
1565     return AUDIO_STREAM_MUSIC;
1566 }
1567 
getProductStrategyFromAudioAttributes(const AudioAttributes & aa,product_strategy_t & productStrategy)1568 status_t AudioSystem::getProductStrategyFromAudioAttributes(const AudioAttributes &aa,
1569                                                             product_strategy_t &productStrategy)
1570 {
1571     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1572     if (aps == 0) return PERMISSION_DENIED;
1573     return aps->getProductStrategyFromAudioAttributes(aa,productStrategy);
1574 }
1575 
listAudioVolumeGroups(AudioVolumeGroupVector & groups)1576 status_t AudioSystem::listAudioVolumeGroups(AudioVolumeGroupVector &groups)
1577 {
1578     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1579     if (aps == 0) return PERMISSION_DENIED;
1580     return aps->listAudioVolumeGroups(groups);
1581 }
1582 
getVolumeGroupFromAudioAttributes(const AudioAttributes & aa,volume_group_t & volumeGroup)1583 status_t AudioSystem::getVolumeGroupFromAudioAttributes(const AudioAttributes &aa,
1584                                                         volume_group_t &volumeGroup)
1585 {
1586     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1587     if (aps == 0) return PERMISSION_DENIED;
1588     return aps->getVolumeGroupFromAudioAttributes(aa, volumeGroup);
1589 }
1590 
setRttEnabled(bool enabled)1591 status_t AudioSystem::setRttEnabled(bool enabled)
1592 {
1593     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1594     if (aps == 0) return PERMISSION_DENIED;
1595     return aps->setRttEnabled(enabled);
1596 }
1597 
isCallScreenModeSupported()1598 bool AudioSystem::isCallScreenModeSupported()
1599 {
1600     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1601     if (aps == 0) return false;
1602     return aps->isCallScreenModeSupported();
1603 }
1604 
setPreferredDeviceForStrategy(product_strategy_t strategy,const AudioDeviceTypeAddr & device)1605 status_t AudioSystem::setPreferredDeviceForStrategy(product_strategy_t strategy,
1606                                                     const AudioDeviceTypeAddr &device)
1607 {
1608     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1609     if (aps == 0) {
1610         return PERMISSION_DENIED;
1611     }
1612     return aps->setPreferredDeviceForStrategy(strategy, device);
1613 }
1614 
removePreferredDeviceForStrategy(product_strategy_t strategy)1615 status_t AudioSystem::removePreferredDeviceForStrategy(product_strategy_t strategy)
1616 {
1617     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1618     if (aps == 0) {
1619         return PERMISSION_DENIED;
1620     }
1621     return aps->removePreferredDeviceForStrategy(strategy);
1622 }
1623 
getPreferredDeviceForStrategy(product_strategy_t strategy,AudioDeviceTypeAddr & device)1624 status_t AudioSystem::getPreferredDeviceForStrategy(product_strategy_t strategy,
1625         AudioDeviceTypeAddr &device)
1626 {
1627     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1628     if (aps == 0) {
1629         return PERMISSION_DENIED;
1630     }
1631     return aps->getPreferredDeviceForStrategy(strategy, device);
1632 }
1633 
1634 class CaptureStateListenerImpl : public media::BnCaptureStateListener,
1635                                  public IBinder::DeathRecipient {
1636 public:
setCaptureState(bool active)1637     binder::Status setCaptureState(bool active) override {
1638         Mutex::Autolock _l(gSoundTriggerCaptureStateListenerLock);
1639         gSoundTriggerCaptureStateListener->onStateChanged(active);
1640         return binder::Status::ok();
1641     }
1642 
binderDied(const wp<IBinder> &)1643     void binderDied(const wp<IBinder>&) override {
1644         Mutex::Autolock _l(gSoundTriggerCaptureStateListenerLock);
1645         gSoundTriggerCaptureStateListener->onServiceDied();
1646         gSoundTriggerCaptureStateListener = nullptr;
1647     }
1648 };
1649 
registerSoundTriggerCaptureStateListener(const sp<CaptureStateListener> & listener)1650 status_t AudioSystem::registerSoundTriggerCaptureStateListener(
1651     const sp<CaptureStateListener>& listener) {
1652     const sp<IAudioPolicyService>& aps =
1653             AudioSystem::get_audio_policy_service();
1654     if (aps == 0) {
1655         return PERMISSION_DENIED;
1656     }
1657 
1658     sp<CaptureStateListenerImpl> wrapper = new CaptureStateListenerImpl();
1659 
1660     Mutex::Autolock _l(gSoundTriggerCaptureStateListenerLock);
1661 
1662     bool active;
1663     status_t status =
1664         aps->registerSoundTriggerCaptureStateListener(wrapper, &active);
1665     if (status != NO_ERROR) {
1666         listener->onServiceDied();
1667         return NO_ERROR;
1668     }
1669     gSoundTriggerCaptureStateListener = listener;
1670     listener->onStateChanged(active);
1671     sp<IBinder> binder = IInterface::asBinder(aps);
1672     binder->linkToDeath(wrapper);
1673     return NO_ERROR;
1674 }
1675 
1676 // ---------------------------------------------------------------------------
1677 
addAudioPortCallback(const sp<AudioPortCallback> & callback)1678 int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback(
1679         const sp<AudioPortCallback>& callback)
1680 {
1681     Mutex::Autolock _l(mLock);
1682     for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1683         if (mAudioPortCallbacks[i] == callback) {
1684             return -1;
1685         }
1686     }
1687     mAudioPortCallbacks.add(callback);
1688     return mAudioPortCallbacks.size();
1689 }
1690 
removeAudioPortCallback(const sp<AudioPortCallback> & callback)1691 int AudioSystem::AudioPolicyServiceClient::removeAudioPortCallback(
1692         const sp<AudioPortCallback>& callback)
1693 {
1694     Mutex::Autolock _l(mLock);
1695     size_t i;
1696     for (i = 0; i < mAudioPortCallbacks.size(); i++) {
1697         if (mAudioPortCallbacks[i] == callback) {
1698             break;
1699         }
1700     }
1701     if (i == mAudioPortCallbacks.size()) {
1702         return -1;
1703     }
1704     mAudioPortCallbacks.removeAt(i);
1705     return mAudioPortCallbacks.size();
1706 }
1707 
1708 
onAudioPortListUpdate()1709 void AudioSystem::AudioPolicyServiceClient::onAudioPortListUpdate()
1710 {
1711     Mutex::Autolock _l(mLock);
1712     for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1713         mAudioPortCallbacks[i]->onAudioPortListUpdate();
1714     }
1715 }
1716 
onAudioPatchListUpdate()1717 void AudioSystem::AudioPolicyServiceClient::onAudioPatchListUpdate()
1718 {
1719     Mutex::Autolock _l(mLock);
1720     for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1721         mAudioPortCallbacks[i]->onAudioPatchListUpdate();
1722     }
1723 }
1724 
1725 // ----------------------------------------------------------------------------
addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)1726 int AudioSystem::AudioPolicyServiceClient::addAudioVolumeGroupCallback(
1727         const sp<AudioVolumeGroupCallback>& callback)
1728 {
1729     Mutex::Autolock _l(mLock);
1730     for (size_t i = 0; i < mAudioVolumeGroupCallback.size(); i++) {
1731         if (mAudioVolumeGroupCallback[i] == callback) {
1732             return -1;
1733         }
1734     }
1735     mAudioVolumeGroupCallback.add(callback);
1736     return mAudioVolumeGroupCallback.size();
1737 }
1738 
removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback> & callback)1739 int AudioSystem::AudioPolicyServiceClient::removeAudioVolumeGroupCallback(
1740         const sp<AudioVolumeGroupCallback>& callback)
1741 {
1742     Mutex::Autolock _l(mLock);
1743     size_t i;
1744     for (i = 0; i < mAudioVolumeGroupCallback.size(); i++) {
1745         if (mAudioVolumeGroupCallback[i] == callback) {
1746             break;
1747         }
1748     }
1749     if (i == mAudioVolumeGroupCallback.size()) {
1750         return -1;
1751     }
1752     mAudioVolumeGroupCallback.removeAt(i);
1753     return mAudioVolumeGroupCallback.size();
1754 }
1755 
onAudioVolumeGroupChanged(volume_group_t group,int flags)1756 void AudioSystem::AudioPolicyServiceClient::onAudioVolumeGroupChanged(volume_group_t group,
1757                                                                       int flags)
1758 {
1759     Mutex::Autolock _l(mLock);
1760     for (size_t i = 0; i < mAudioVolumeGroupCallback.size(); i++) {
1761         mAudioVolumeGroupCallback[i]->onAudioVolumeGroupChanged(group, flags);
1762     }
1763 }
1764 // ----------------------------------------------------------------------------
1765 
onDynamicPolicyMixStateUpdate(String8 regId,int32_t state)1766 void AudioSystem::AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(
1767         String8 regId, int32_t state)
1768 {
1769     ALOGV("AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(%s, %d)", regId.string(), state);
1770     dynamic_policy_callback cb = NULL;
1771     {
1772         Mutex::Autolock _l(AudioSystem::gLock);
1773         cb = gDynPolicyCallback;
1774     }
1775 
1776     if (cb != NULL) {
1777         cb(DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE, regId, state);
1778     }
1779 }
1780 
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)1781 void AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate(
1782                                                 int event,
1783                                                 const record_client_info_t *clientInfo,
1784                                                 const audio_config_base_t *clientConfig,
1785                                                 std::vector<effect_descriptor_t> clientEffects,
1786                                                 const audio_config_base_t *deviceConfig,
1787                                                 std::vector<effect_descriptor_t> effects,
1788                                                 audio_patch_handle_t patchHandle,
1789                                                 audio_source_t source) {
1790     record_config_callback cb = NULL;
1791     {
1792         Mutex::Autolock _l(AudioSystem::gLock);
1793         cb = gRecordConfigCallback;
1794     }
1795 
1796     if (cb != NULL) {
1797         cb(event, clientInfo, clientConfig, clientEffects,
1798            deviceConfig, effects, patchHandle, source);
1799     }
1800 }
1801 
binderDied(const wp<IBinder> & who __unused)1802 void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who __unused)
1803 {
1804     {
1805         Mutex::Autolock _l(mLock);
1806         for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1807             mAudioPortCallbacks[i]->onServiceDied();
1808         }
1809         for (size_t i = 0; i < mAudioVolumeGroupCallback.size(); i++) {
1810             mAudioVolumeGroupCallback[i]->onServiceDied();
1811         }
1812     }
1813     {
1814         Mutex::Autolock _l(gLockAPS);
1815         AudioSystem::gAudioPolicyService.clear();
1816     }
1817 
1818     ALOGW("AudioPolicyService server died!");
1819 }
1820 
1821 } // namespace android
1822