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