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 #include <binder/IServiceManager.h>
22 #include <media/AudioSystem.h>
23 #include <media/IAudioFlinger.h>
24 #include <media/IAudioPolicyService.h>
25 #include <math.h>
26 
27 #include <system/audio.h>
28 
29 // ----------------------------------------------------------------------------
30 
31 namespace android {
32 
33 // client singleton for AudioFlinger binder interface
34 Mutex AudioSystem::gLock;
35 Mutex AudioSystem::gLockCache;
36 Mutex AudioSystem::gLockAPS;
37 Mutex AudioSystem::gLockAPC;
38 sp<IAudioFlinger> AudioSystem::gAudioFlinger;
39 sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
40 audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
41 
42 // Cached values for output handles
43 DefaultKeyedVector<audio_io_handle_t, AudioSystem::OutputDescriptor *> AudioSystem::gOutputs(NULL);
44 
45 // Cached values for recording queries, all protected by gLock
46 uint32_t AudioSystem::gPrevInSamplingRate;
47 audio_format_t AudioSystem::gPrevInFormat;
48 audio_channel_mask_t AudioSystem::gPrevInChannelMask;
49 size_t AudioSystem::gInBuffSize = 0;    // zero indicates cache is invalid
50 
51 sp<AudioSystem::AudioPortCallback> AudioSystem::gAudioPortCallback;
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     {
59         Mutex::Autolock _l(gLock);
60         if (gAudioFlinger == 0) {
61             sp<IServiceManager> sm = defaultServiceManager();
62             sp<IBinder> binder;
63             do {
64                 binder = sm->getService(String16("media.audio_flinger"));
65                 if (binder != 0)
66                     break;
67                 ALOGW("AudioFlinger not published, waiting...");
68                 usleep(500000); // 0.5 s
69             } while (true);
70             if (gAudioFlingerClient == NULL) {
71                 gAudioFlingerClient = new AudioFlingerClient();
72             } else {
73                 if (gAudioErrorCallback) {
74                     gAudioErrorCallback(NO_ERROR);
75                 }
76             }
77             binder->linkToDeath(gAudioFlingerClient);
78             gAudioFlinger = interface_cast<IAudioFlinger>(binder);
79             LOG_ALWAYS_FATAL_IF(gAudioFlinger == 0);
80             afc = gAudioFlingerClient;
81         }
82         af = gAudioFlinger;
83     }
84     if (afc != 0) {
85         af->registerClient(afc);
86     }
87     return af;
88 }
89 
checkAudioFlinger()90 /* static */ status_t AudioSystem::checkAudioFlinger()
91 {
92     if (defaultServiceManager()->checkService(String16("media.audio_flinger")) != 0) {
93         return NO_ERROR;
94     }
95     return DEAD_OBJECT;
96 }
97 
muteMicrophone(bool state)98 status_t AudioSystem::muteMicrophone(bool state)
99 {
100     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
101     if (af == 0) return PERMISSION_DENIED;
102     return af->setMicMute(state);
103 }
104 
isMicrophoneMuted(bool * state)105 status_t AudioSystem::isMicrophoneMuted(bool* state)
106 {
107     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
108     if (af == 0) return PERMISSION_DENIED;
109     *state = af->getMicMute();
110     return NO_ERROR;
111 }
112 
setMasterVolume(float value)113 status_t AudioSystem::setMasterVolume(float value)
114 {
115     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
116     if (af == 0) return PERMISSION_DENIED;
117     af->setMasterVolume(value);
118     return NO_ERROR;
119 }
120 
setMasterMute(bool mute)121 status_t AudioSystem::setMasterMute(bool mute)
122 {
123     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
124     if (af == 0) return PERMISSION_DENIED;
125     af->setMasterMute(mute);
126     return NO_ERROR;
127 }
128 
getMasterVolume(float * volume)129 status_t AudioSystem::getMasterVolume(float* volume)
130 {
131     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
132     if (af == 0) return PERMISSION_DENIED;
133     *volume = af->masterVolume();
134     return NO_ERROR;
135 }
136 
getMasterMute(bool * mute)137 status_t AudioSystem::getMasterMute(bool* mute)
138 {
139     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
140     if (af == 0) return PERMISSION_DENIED;
141     *mute = af->masterMute();
142     return NO_ERROR;
143 }
144 
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)145 status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
146         audio_io_handle_t output)
147 {
148     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
149     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
150     if (af == 0) return PERMISSION_DENIED;
151     af->setStreamVolume(stream, value, output);
152     return NO_ERROR;
153 }
154 
setStreamMute(audio_stream_type_t stream,bool mute)155 status_t AudioSystem::setStreamMute(audio_stream_type_t stream, bool mute)
156 {
157     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
158     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
159     if (af == 0) return PERMISSION_DENIED;
160     af->setStreamMute(stream, mute);
161     return NO_ERROR;
162 }
163 
getStreamVolume(audio_stream_type_t stream,float * volume,audio_io_handle_t output)164 status_t AudioSystem::getStreamVolume(audio_stream_type_t stream, float* volume,
165         audio_io_handle_t output)
166 {
167     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
168     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
169     if (af == 0) return PERMISSION_DENIED;
170     *volume = af->streamVolume(stream, output);
171     return NO_ERROR;
172 }
173 
getStreamMute(audio_stream_type_t stream,bool * mute)174 status_t AudioSystem::getStreamMute(audio_stream_type_t stream, bool* mute)
175 {
176     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
177     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
178     if (af == 0) return PERMISSION_DENIED;
179     *mute = af->streamMute(stream);
180     return NO_ERROR;
181 }
182 
setMode(audio_mode_t mode)183 status_t AudioSystem::setMode(audio_mode_t mode)
184 {
185     if (uint32_t(mode) >= AUDIO_MODE_CNT) return BAD_VALUE;
186     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
187     if (af == 0) return PERMISSION_DENIED;
188     return af->setMode(mode);
189 }
190 
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)191 status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
192 {
193     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
194     if (af == 0) return PERMISSION_DENIED;
195     return af->setParameters(ioHandle, keyValuePairs);
196 }
197 
getParameters(audio_io_handle_t ioHandle,const String8 & keys)198 String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys)
199 {
200     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
201     String8 result = String8("");
202     if (af == 0) return result;
203 
204     result = af->getParameters(ioHandle, keys);
205     return result;
206 }
207 
setParameters(const String8 & keyValuePairs)208 status_t AudioSystem::setParameters(const String8& keyValuePairs)
209 {
210     return setParameters(AUDIO_IO_HANDLE_NONE, keyValuePairs);
211 }
212 
getParameters(const String8 & keys)213 String8 AudioSystem::getParameters(const String8& keys)
214 {
215     return getParameters(AUDIO_IO_HANDLE_NONE, keys);
216 }
217 
218 // convert volume steps to natural log scale
219 
220 // change this value to change volume scaling
221 static const float dBPerStep = 0.5f;
222 // shouldn't need to touch these
223 static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
224 static const float dBConvertInverse = 1.0f / dBConvert;
225 
linearToLog(int volume)226 float AudioSystem::linearToLog(int volume)
227 {
228     // float v = volume ? exp(float(100 - volume) * dBConvert) : 0;
229     // ALOGD("linearToLog(%d)=%f", volume, v);
230     // return v;
231     return volume ? exp(float(100 - volume) * dBConvert) : 0;
232 }
233 
logToLinear(float volume)234 int AudioSystem::logToLinear(float volume)
235 {
236     // int v = volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
237     // ALOGD("logTolinear(%d)=%f", v, volume);
238     // return v;
239     return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
240 }
241 
getOutputSamplingRate(uint32_t * samplingRate,audio_stream_type_t streamType)242 status_t AudioSystem::getOutputSamplingRate(uint32_t* samplingRate, audio_stream_type_t streamType)
243 {
244     audio_io_handle_t output;
245 
246     if (streamType == AUDIO_STREAM_DEFAULT) {
247         streamType = AUDIO_STREAM_MUSIC;
248     }
249 
250     output = getOutput(streamType);
251     if (output == 0) {
252         return PERMISSION_DENIED;
253     }
254 
255     return getSamplingRate(output, samplingRate);
256 }
257 
getSamplingRate(audio_io_handle_t output,uint32_t * samplingRate)258 status_t AudioSystem::getSamplingRate(audio_io_handle_t output,
259                                       uint32_t* samplingRate)
260 {
261     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
262     if (af == 0) return PERMISSION_DENIED;
263 
264     Mutex::Autolock _l(gLockCache);
265 
266     OutputDescriptor *outputDesc = AudioSystem::gOutputs.valueFor(output);
267     if (outputDesc == NULL) {
268         ALOGV("getOutputSamplingRate() no output descriptor for output %d in gOutputs", output);
269         gLockCache.unlock();
270         *samplingRate = af->sampleRate(output);
271         gLockCache.lock();
272     } else {
273         ALOGV("getOutputSamplingRate() reading from output desc");
274         *samplingRate = outputDesc->samplingRate;
275     }
276     if (*samplingRate == 0) {
277         ALOGE("AudioSystem::getSamplingRate failed for output %d", output);
278         return BAD_VALUE;
279     }
280 
281     ALOGV("getSamplingRate() output %d, sampling rate %u", output, *samplingRate);
282 
283     return NO_ERROR;
284 }
285 
getOutputFrameCount(size_t * frameCount,audio_stream_type_t streamType)286 status_t AudioSystem::getOutputFrameCount(size_t* frameCount, audio_stream_type_t streamType)
287 {
288     audio_io_handle_t output;
289 
290     if (streamType == AUDIO_STREAM_DEFAULT) {
291         streamType = AUDIO_STREAM_MUSIC;
292     }
293 
294     output = getOutput(streamType);
295     if (output == AUDIO_IO_HANDLE_NONE) {
296         return PERMISSION_DENIED;
297     }
298 
299     return getFrameCount(output, frameCount);
300 }
301 
getFrameCount(audio_io_handle_t output,size_t * frameCount)302 status_t AudioSystem::getFrameCount(audio_io_handle_t output,
303                                     size_t* frameCount)
304 {
305     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
306     if (af == 0) return PERMISSION_DENIED;
307 
308     Mutex::Autolock _l(gLockCache);
309 
310     OutputDescriptor *outputDesc = AudioSystem::gOutputs.valueFor(output);
311     if (outputDesc == NULL) {
312         gLockCache.unlock();
313         *frameCount = af->frameCount(output);
314         gLockCache.lock();
315     } else {
316         *frameCount = outputDesc->frameCount;
317     }
318     if (*frameCount == 0) {
319         ALOGE("AudioSystem::getFrameCount failed for output %d", output);
320         return BAD_VALUE;
321     }
322 
323     ALOGV("getFrameCount() output %d, frameCount %zu", output, *frameCount);
324 
325     return NO_ERROR;
326 }
327 
getOutputLatency(uint32_t * latency,audio_stream_type_t streamType)328 status_t AudioSystem::getOutputLatency(uint32_t* latency, audio_stream_type_t streamType)
329 {
330     audio_io_handle_t output;
331 
332     if (streamType == AUDIO_STREAM_DEFAULT) {
333         streamType = AUDIO_STREAM_MUSIC;
334     }
335 
336     output = getOutput(streamType);
337     if (output == AUDIO_IO_HANDLE_NONE) {
338         return PERMISSION_DENIED;
339     }
340 
341     return getLatency(output, latency);
342 }
343 
getLatency(audio_io_handle_t output,uint32_t * latency)344 status_t AudioSystem::getLatency(audio_io_handle_t output,
345                                  uint32_t* latency)
346 {
347     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
348     if (af == 0) return PERMISSION_DENIED;
349 
350     Mutex::Autolock _l(gLockCache);
351 
352     OutputDescriptor *outputDesc = AudioSystem::gOutputs.valueFor(output);
353     if (outputDesc == NULL) {
354         gLockCache.unlock();
355         *latency = af->latency(output);
356         gLockCache.lock();
357     } else {
358         *latency = outputDesc->latency;
359     }
360 
361     ALOGV("getLatency() output %d, latency %d", output, *latency);
362 
363     return NO_ERROR;
364 }
365 
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * buffSize)366 status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
367         audio_channel_mask_t channelMask, size_t* buffSize)
368 {
369     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
370     if (af == 0) {
371         return PERMISSION_DENIED;
372     }
373     Mutex::Autolock _l(gLockCache);
374     // Do we have a stale gInBufferSize or are we requesting the input buffer size for new values
375     size_t inBuffSize = gInBuffSize;
376     if ((inBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat)
377         || (channelMask != gPrevInChannelMask)) {
378         gLockCache.unlock();
379         inBuffSize = af->getInputBufferSize(sampleRate, format, channelMask);
380         gLockCache.lock();
381         if (inBuffSize == 0) {
382             ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %#x channelMask %x",
383                     sampleRate, format, channelMask);
384             return BAD_VALUE;
385         }
386         // A benign race is possible here: we could overwrite a fresher cache entry
387         // save the request params
388         gPrevInSamplingRate = sampleRate;
389         gPrevInFormat = format;
390         gPrevInChannelMask = channelMask;
391 
392         gInBuffSize = inBuffSize;
393     }
394     *buffSize = inBuffSize;
395 
396     return NO_ERROR;
397 }
398 
setVoiceVolume(float value)399 status_t AudioSystem::setVoiceVolume(float value)
400 {
401     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
402     if (af == 0) return PERMISSION_DENIED;
403     return af->setVoiceVolume(value);
404 }
405 
getRenderPosition(audio_io_handle_t output,uint32_t * halFrames,uint32_t * dspFrames)406 status_t AudioSystem::getRenderPosition(audio_io_handle_t output, uint32_t *halFrames,
407                                         uint32_t *dspFrames)
408 {
409     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
410     if (af == 0) return PERMISSION_DENIED;
411 
412     return af->getRenderPosition(halFrames, dspFrames, output);
413 }
414 
getInputFramesLost(audio_io_handle_t ioHandle)415 uint32_t AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle)
416 {
417     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
418     uint32_t result = 0;
419     if (af == 0) return result;
420     if (ioHandle == AUDIO_IO_HANDLE_NONE) return result;
421 
422     result = af->getInputFramesLost(ioHandle);
423     return result;
424 }
425 
newAudioUniqueId()426 audio_unique_id_t AudioSystem::newAudioUniqueId()
427 {
428     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
429     if (af == 0) return AUDIO_UNIQUE_ID_ALLOCATE;
430     return af->newAudioUniqueId();
431 }
432 
acquireAudioSessionId(int audioSession,pid_t pid)433 void AudioSystem::acquireAudioSessionId(int audioSession, pid_t pid)
434 {
435     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
436     if (af != 0) {
437         af->acquireAudioSessionId(audioSession, pid);
438     }
439 }
440 
releaseAudioSessionId(int audioSession,pid_t pid)441 void AudioSystem::releaseAudioSessionId(int audioSession, pid_t pid)
442 {
443     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
444     if (af != 0) {
445         af->releaseAudioSessionId(audioSession, pid);
446     }
447 }
448 
getAudioHwSyncForSession(audio_session_t sessionId)449 audio_hw_sync_t AudioSystem::getAudioHwSyncForSession(audio_session_t sessionId)
450 {
451     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
452     if (af == 0) return AUDIO_HW_SYNC_INVALID;
453     return af->getAudioHwSyncForSession(sessionId);
454 }
455 
456 // ---------------------------------------------------------------------------
457 
binderDied(const wp<IBinder> & who __unused)458 void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who __unused)
459 {
460     audio_error_callback cb = NULL;
461     {
462         Mutex::Autolock _l(AudioSystem::gLock);
463         AudioSystem::gAudioFlinger.clear();
464         cb = gAudioErrorCallback;
465     }
466 
467     {
468         // clear output handles and stream to output map caches
469         Mutex::Autolock _l(gLockCache);
470         AudioSystem::gOutputs.clear();
471     }
472 
473     if (cb) {
474         cb(DEAD_OBJECT);
475     }
476     ALOGW("AudioFlinger server died!");
477 }
478 
ioConfigChanged(int event,audio_io_handle_t ioHandle,const void * param2)479 void AudioSystem::AudioFlingerClient::ioConfigChanged(int event, audio_io_handle_t ioHandle,
480         const void *param2) {
481     ALOGV("ioConfigChanged() event %d", event);
482     const OutputDescriptor *desc;
483     audio_stream_type_t stream;
484 
485     if (ioHandle == AUDIO_IO_HANDLE_NONE) return;
486 
487     Mutex::Autolock _l(AudioSystem::gLockCache);
488 
489     switch (event) {
490     case STREAM_CONFIG_CHANGED:
491         break;
492     case OUTPUT_OPENED: {
493         if (gOutputs.indexOfKey(ioHandle) >= 0) {
494             ALOGV("ioConfigChanged() opening already existing output! %d", ioHandle);
495             break;
496         }
497         if (param2 == NULL) break;
498         desc = (const OutputDescriptor *)param2;
499 
500         OutputDescriptor *outputDesc =  new OutputDescriptor(*desc);
501         gOutputs.add(ioHandle, outputDesc);
502         ALOGV("ioConfigChanged() new output samplingRate %u, format %#x channel mask %#x frameCount %zu "
503                 "latency %d",
504                 outputDesc->samplingRate, outputDesc->format, outputDesc->channelMask,
505                 outputDesc->frameCount, outputDesc->latency);
506         } break;
507     case OUTPUT_CLOSED: {
508         if (gOutputs.indexOfKey(ioHandle) < 0) {
509             ALOGW("ioConfigChanged() closing unknown output! %d", ioHandle);
510             break;
511         }
512         ALOGV("ioConfigChanged() output %d closed", ioHandle);
513 
514         gOutputs.removeItem(ioHandle);
515         } break;
516 
517     case OUTPUT_CONFIG_CHANGED: {
518         int index = gOutputs.indexOfKey(ioHandle);
519         if (index < 0) {
520             ALOGW("ioConfigChanged() modifying unknown output! %d", ioHandle);
521             break;
522         }
523         if (param2 == NULL) break;
524         desc = (const OutputDescriptor *)param2;
525 
526         ALOGV("ioConfigChanged() new config for output %d samplingRate %u, format %#x channel mask %#x "
527                 "frameCount %zu latency %d",
528                 ioHandle, desc->samplingRate, desc->format,
529                 desc->channelMask, desc->frameCount, desc->latency);
530         OutputDescriptor *outputDesc = gOutputs.valueAt(index);
531         delete outputDesc;
532         outputDesc =  new OutputDescriptor(*desc);
533         gOutputs.replaceValueFor(ioHandle, outputDesc);
534     } break;
535     case INPUT_OPENED:
536     case INPUT_CLOSED:
537     case INPUT_CONFIG_CHANGED:
538         break;
539 
540     }
541 }
542 
setErrorCallback(audio_error_callback cb)543 void AudioSystem::setErrorCallback(audio_error_callback cb)
544 {
545     Mutex::Autolock _l(gLock);
546     gAudioErrorCallback = cb;
547 }
548 
549 // client singleton for AudioPolicyService binder interface
550 // protected by gLockAPS
551 sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
552 sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
553 
554 
555 // establish binder interface to AudioPolicy service
get_audio_policy_service()556 const sp<IAudioPolicyService> AudioSystem::get_audio_policy_service()
557 {
558     sp<IAudioPolicyService> ap;
559     sp<AudioPolicyServiceClient> apc;
560     {
561         Mutex::Autolock _l(gLockAPS);
562         if (gAudioPolicyService == 0) {
563             sp<IServiceManager> sm = defaultServiceManager();
564             sp<IBinder> binder;
565             do {
566                 binder = sm->getService(String16("media.audio_policy"));
567                 if (binder != 0)
568                     break;
569                 ALOGW("AudioPolicyService not published, waiting...");
570                 usleep(500000); // 0.5 s
571             } while (true);
572             if (gAudioPolicyServiceClient == NULL) {
573                 gAudioPolicyServiceClient = new AudioPolicyServiceClient();
574             }
575             binder->linkToDeath(gAudioPolicyServiceClient);
576             gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
577             LOG_ALWAYS_FATAL_IF(gAudioPolicyService == 0);
578             apc = gAudioPolicyServiceClient;
579         }
580         ap = gAudioPolicyService;
581     }
582     if (apc != 0) {
583         ap->registerClient(apc);
584     }
585 
586     return ap;
587 }
588 
589 // ---------------------------------------------------------------------------
590 
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address)591 status_t AudioSystem::setDeviceConnectionState(audio_devices_t device,
592                                                audio_policy_dev_state_t state,
593                                                const char *device_address)
594 {
595     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
596     const char *address = "";
597 
598     if (aps == 0) return PERMISSION_DENIED;
599 
600     if (device_address != NULL) {
601         address = device_address;
602     }
603 
604     return aps->setDeviceConnectionState(device, state, address);
605 }
606 
getDeviceConnectionState(audio_devices_t device,const char * device_address)607 audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t device,
608                                                   const char *device_address)
609 {
610     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
611     if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
612 
613     return aps->getDeviceConnectionState(device, device_address);
614 }
615 
setPhoneState(audio_mode_t state)616 status_t AudioSystem::setPhoneState(audio_mode_t state)
617 {
618     if (uint32_t(state) >= AUDIO_MODE_CNT) return BAD_VALUE;
619     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
620     if (aps == 0) return PERMISSION_DENIED;
621 
622     return aps->setPhoneState(state);
623 }
624 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)625 status_t AudioSystem::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
626 {
627     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
628     if (aps == 0) return PERMISSION_DENIED;
629     return aps->setForceUse(usage, config);
630 }
631 
getForceUse(audio_policy_force_use_t usage)632 audio_policy_forced_cfg_t AudioSystem::getForceUse(audio_policy_force_use_t usage)
633 {
634     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
635     if (aps == 0) return AUDIO_POLICY_FORCE_NONE;
636     return aps->getForceUse(usage);
637 }
638 
639 
getOutput(audio_stream_type_t stream,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,const audio_offload_info_t * offloadInfo)640 audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream,
641                                     uint32_t samplingRate,
642                                     audio_format_t format,
643                                     audio_channel_mask_t channelMask,
644                                     audio_output_flags_t flags,
645                                     const audio_offload_info_t *offloadInfo)
646 {
647     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
648     if (aps == 0) return 0;
649     return aps->getOutput(stream, samplingRate, format, channelMask, flags, offloadInfo);
650 }
651 
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,const audio_offload_info_t * offloadInfo)652 status_t AudioSystem::getOutputForAttr(const audio_attributes_t *attr,
653                                         audio_io_handle_t *output,
654                                         audio_session_t session,
655                                         audio_stream_type_t *stream,
656                                         uint32_t samplingRate,
657                                         audio_format_t format,
658                                         audio_channel_mask_t channelMask,
659                                         audio_output_flags_t flags,
660                                         const audio_offload_info_t *offloadInfo)
661 {
662     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
663     if (aps == 0) return NO_INIT;
664     return aps->getOutputForAttr(attr, output, session, stream,
665                                  samplingRate, format, channelMask,
666                                  flags, offloadInfo);
667 }
668 
startOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)669 status_t AudioSystem::startOutput(audio_io_handle_t output,
670                                   audio_stream_type_t stream,
671                                   audio_session_t session)
672 {
673     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
674     if (aps == 0) return PERMISSION_DENIED;
675     return aps->startOutput(output, stream, session);
676 }
677 
stopOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)678 status_t AudioSystem::stopOutput(audio_io_handle_t output,
679                                  audio_stream_type_t stream,
680                                  audio_session_t session)
681 {
682     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
683     if (aps == 0) return PERMISSION_DENIED;
684     return aps->stopOutput(output, stream, session);
685 }
686 
releaseOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)687 void AudioSystem::releaseOutput(audio_io_handle_t output,
688                                 audio_stream_type_t stream,
689                                 audio_session_t session)
690 {
691     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
692     if (aps == 0) return;
693     aps->releaseOutput(output, stream, session);
694 }
695 
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_session_t session,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_input_flags_t flags)696 status_t AudioSystem::getInputForAttr(const audio_attributes_t *attr,
697                                 audio_io_handle_t *input,
698                                 audio_session_t session,
699                                 uint32_t samplingRate,
700                                 audio_format_t format,
701                                 audio_channel_mask_t channelMask,
702                                 audio_input_flags_t flags)
703 {
704     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
705     if (aps == 0) return NO_INIT;
706     return aps->getInputForAttr(attr, input, session, samplingRate, format, channelMask, flags);
707 }
708 
startInput(audio_io_handle_t input,audio_session_t session)709 status_t AudioSystem::startInput(audio_io_handle_t input,
710                                  audio_session_t session)
711 {
712     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
713     if (aps == 0) return PERMISSION_DENIED;
714     return aps->startInput(input, session);
715 }
716 
stopInput(audio_io_handle_t input,audio_session_t session)717 status_t AudioSystem::stopInput(audio_io_handle_t input,
718                                 audio_session_t session)
719 {
720     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
721     if (aps == 0) return PERMISSION_DENIED;
722     return aps->stopInput(input, session);
723 }
724 
releaseInput(audio_io_handle_t input,audio_session_t session)725 void AudioSystem::releaseInput(audio_io_handle_t input,
726                                audio_session_t session)
727 {
728     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
729     if (aps == 0) return;
730     aps->releaseInput(input, session);
731 }
732 
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)733 status_t AudioSystem::initStreamVolume(audio_stream_type_t stream,
734                                     int indexMin,
735                                     int indexMax)
736 {
737     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
738     if (aps == 0) return PERMISSION_DENIED;
739     return aps->initStreamVolume(stream, indexMin, indexMax);
740 }
741 
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)742 status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
743                                            int index,
744                                            audio_devices_t device)
745 {
746     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
747     if (aps == 0) return PERMISSION_DENIED;
748     return aps->setStreamVolumeIndex(stream, index, device);
749 }
750 
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)751 status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
752                                            int *index,
753                                            audio_devices_t device)
754 {
755     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
756     if (aps == 0) return PERMISSION_DENIED;
757     return aps->getStreamVolumeIndex(stream, index, device);
758 }
759 
getStrategyForStream(audio_stream_type_t stream)760 uint32_t AudioSystem::getStrategyForStream(audio_stream_type_t stream)
761 {
762     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
763     if (aps == 0) return 0;
764     return aps->getStrategyForStream(stream);
765 }
766 
getDevicesForStream(audio_stream_type_t stream)767 audio_devices_t AudioSystem::getDevicesForStream(audio_stream_type_t stream)
768 {
769     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
770     if (aps == 0) return AUDIO_DEVICE_NONE;
771     return aps->getDevicesForStream(stream);
772 }
773 
getOutputForEffect(const effect_descriptor_t * desc)774 audio_io_handle_t AudioSystem::getOutputForEffect(const effect_descriptor_t *desc)
775 {
776     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
777     // FIXME change return type to status_t, and return PERMISSION_DENIED here
778     if (aps == 0) return AUDIO_IO_HANDLE_NONE;
779     return aps->getOutputForEffect(desc);
780 }
781 
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,int session,int id)782 status_t AudioSystem::registerEffect(const effect_descriptor_t *desc,
783                                 audio_io_handle_t io,
784                                 uint32_t strategy,
785                                 int session,
786                                 int id)
787 {
788     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
789     if (aps == 0) return PERMISSION_DENIED;
790     return aps->registerEffect(desc, io, strategy, session, id);
791 }
792 
unregisterEffect(int id)793 status_t AudioSystem::unregisterEffect(int id)
794 {
795     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
796     if (aps == 0) return PERMISSION_DENIED;
797     return aps->unregisterEffect(id);
798 }
799 
setEffectEnabled(int id,bool enabled)800 status_t AudioSystem::setEffectEnabled(int id, bool enabled)
801 {
802     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
803     if (aps == 0) return PERMISSION_DENIED;
804     return aps->setEffectEnabled(id, enabled);
805 }
806 
isStreamActive(audio_stream_type_t stream,bool * state,uint32_t inPastMs)807 status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs)
808 {
809     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
810     if (aps == 0) return PERMISSION_DENIED;
811     if (state == NULL) return BAD_VALUE;
812     *state = aps->isStreamActive(stream, inPastMs);
813     return NO_ERROR;
814 }
815 
isStreamActiveRemotely(audio_stream_type_t stream,bool * state,uint32_t inPastMs)816 status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* state,
817         uint32_t inPastMs)
818 {
819     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
820     if (aps == 0) return PERMISSION_DENIED;
821     if (state == NULL) return BAD_VALUE;
822     *state = aps->isStreamActiveRemotely(stream, inPastMs);
823     return NO_ERROR;
824 }
825 
isSourceActive(audio_source_t stream,bool * state)826 status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state)
827 {
828     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
829     if (aps == 0) return PERMISSION_DENIED;
830     if (state == NULL) return BAD_VALUE;
831     *state = aps->isSourceActive(stream);
832     return NO_ERROR;
833 }
834 
getPrimaryOutputSamplingRate()835 uint32_t AudioSystem::getPrimaryOutputSamplingRate()
836 {
837     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
838     if (af == 0) return 0;
839     return af->getPrimaryOutputSamplingRate();
840 }
841 
getPrimaryOutputFrameCount()842 size_t AudioSystem::getPrimaryOutputFrameCount()
843 {
844     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
845     if (af == 0) return 0;
846     return af->getPrimaryOutputFrameCount();
847 }
848 
setLowRamDevice(bool isLowRamDevice)849 status_t AudioSystem::setLowRamDevice(bool isLowRamDevice)
850 {
851     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
852     if (af == 0) return PERMISSION_DENIED;
853     return af->setLowRamDevice(isLowRamDevice);
854 }
855 
clearAudioConfigCache()856 void AudioSystem::clearAudioConfigCache()
857 {
858     // called by restoreTrack_l(), which needs new IAudioFlinger and IAudioPolicyService instances
859     ALOGV("clearAudioConfigCache()");
860     {
861         Mutex::Autolock _l(gLockCache);
862         gOutputs.clear();
863     }
864     {
865         Mutex::Autolock _l(gLock);
866         gAudioFlinger.clear();
867     }
868     {
869         Mutex::Autolock _l(gLockAPS);
870         gAudioPolicyService.clear();
871     }
872     // Do not clear gAudioPortCallback
873 }
874 
isOffloadSupported(const audio_offload_info_t & info)875 bool AudioSystem::isOffloadSupported(const audio_offload_info_t& info)
876 {
877     ALOGV("isOffloadSupported()");
878     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
879     if (aps == 0) return false;
880     return aps->isOffloadSupported(info);
881 }
882 
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)883 status_t AudioSystem::listAudioPorts(audio_port_role_t role,
884                                      audio_port_type_t type,
885                                      unsigned int *num_ports,
886                                      struct audio_port *ports,
887                                      unsigned int *generation)
888 {
889     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
890     if (aps == 0) return PERMISSION_DENIED;
891     return aps->listAudioPorts(role, type, num_ports, ports, generation);
892 }
893 
getAudioPort(struct audio_port * port)894 status_t AudioSystem::getAudioPort(struct audio_port *port)
895 {
896     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
897     if (aps == 0) return PERMISSION_DENIED;
898     return aps->getAudioPort(port);
899 }
900 
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)901 status_t AudioSystem::createAudioPatch(const struct audio_patch *patch,
902                                    audio_patch_handle_t *handle)
903 {
904     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
905     if (aps == 0) return PERMISSION_DENIED;
906     return aps->createAudioPatch(patch, handle);
907 }
908 
releaseAudioPatch(audio_patch_handle_t handle)909 status_t AudioSystem::releaseAudioPatch(audio_patch_handle_t handle)
910 {
911     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
912     if (aps == 0) return PERMISSION_DENIED;
913     return aps->releaseAudioPatch(handle);
914 }
915 
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)916 status_t AudioSystem::listAudioPatches(unsigned int *num_patches,
917                                   struct audio_patch *patches,
918                                   unsigned int *generation)
919 {
920     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
921     if (aps == 0) return PERMISSION_DENIED;
922     return aps->listAudioPatches(num_patches, patches, generation);
923 }
924 
setAudioPortConfig(const struct audio_port_config * config)925 status_t AudioSystem::setAudioPortConfig(const struct audio_port_config *config)
926 {
927     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
928     if (aps == 0) return PERMISSION_DENIED;
929     return aps->setAudioPortConfig(config);
930 }
931 
setAudioPortCallback(sp<AudioPortCallback> callBack)932 void AudioSystem::setAudioPortCallback(sp<AudioPortCallback> callBack)
933 {
934     Mutex::Autolock _l(gLockAPC);
935     gAudioPortCallback = callBack;
936 }
937 
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)938 status_t AudioSystem::acquireSoundTriggerSession(audio_session_t *session,
939                                        audio_io_handle_t *ioHandle,
940                                        audio_devices_t *device)
941 {
942     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
943     if (aps == 0) return PERMISSION_DENIED;
944     return aps->acquireSoundTriggerSession(session, ioHandle, device);
945 }
946 
releaseSoundTriggerSession(audio_session_t session)947 status_t AudioSystem::releaseSoundTriggerSession(audio_session_t session)
948 {
949     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
950     if (aps == 0) return PERMISSION_DENIED;
951     return aps->releaseSoundTriggerSession(session);
952 }
953 
getPhoneState()954 audio_mode_t AudioSystem::getPhoneState()
955 {
956     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
957     if (aps == 0) return AUDIO_MODE_INVALID;
958     return aps->getPhoneState();
959 }
960 
registerPolicyMixes(Vector<AudioMix> mixes,bool registration)961 status_t AudioSystem::registerPolicyMixes(Vector<AudioMix> mixes, bool registration)
962 {
963     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
964     if (aps == 0) return PERMISSION_DENIED;
965     return aps->registerPolicyMixes(mixes, registration);
966 }
967 
968 // ---------------------------------------------------------------------------
969 
binderDied(const wp<IBinder> & who __unused)970 void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who __unused)
971 {
972     {
973         Mutex::Autolock _l(gLockAPC);
974         if (gAudioPortCallback != 0) {
975             gAudioPortCallback->onServiceDied();
976         }
977     }
978     {
979         Mutex::Autolock _l(gLockAPS);
980         AudioSystem::gAudioPolicyService.clear();
981     }
982 
983     ALOGW("AudioPolicyService server died!");
984 }
985 
onAudioPortListUpdate()986 void AudioSystem::AudioPolicyServiceClient::onAudioPortListUpdate()
987 {
988     Mutex::Autolock _l(gLockAPC);
989     if (gAudioPortCallback != 0) {
990         gAudioPortCallback->onAudioPortListUpdate();
991     }
992 }
993 
onAudioPatchListUpdate()994 void AudioSystem::AudioPolicyServiceClient::onAudioPatchListUpdate()
995 {
996     Mutex::Autolock _l(gLockAPC);
997     if (gAudioPortCallback != 0) {
998         gAudioPortCallback->onAudioPatchListUpdate();
999     }
1000 }
1001 
1002 }; // namespace android
1003