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