AudioSystem.cpp revision 0ebd5f95b68a3a5c9e5509f21938c9e51e74d71b
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::gLockCache;
36Mutex AudioSystem::gLockAPS;
37Mutex AudioSystem::gLockAPC;
38sp<IAudioFlinger> AudioSystem::gAudioFlinger;
39sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
40audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
41
42// Cached values for output handles
43DefaultKeyedVector<audio_io_handle_t, AudioSystem::OutputDescriptor *> AudioSystem::gOutputs(NULL);
44
45// Cached values for recording queries, all protected by gLock
46uint32_t AudioSystem::gPrevInSamplingRate;
47audio_format_t AudioSystem::gPrevInFormat;
48audio_channel_mask_t AudioSystem::gPrevInChannelMask;
49size_t AudioSystem::gInBuffSize = 0;    // zero indicates cache is invalid
50
51sp<AudioSystem::AudioPortCallback> AudioSystem::gAudioPortCallback;
52
53// establish binder interface to AudioFlinger service
54const 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
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
98status_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
105status_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
113status_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
121status_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
129status_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
137status_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
145status_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
155status_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
164status_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
174status_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
183status_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
191status_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
198String8 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
208status_t AudioSystem::setParameters(const String8& keyValuePairs)
209{
210    return setParameters(AUDIO_IO_HANDLE_NONE, keyValuePairs);
211}
212
213String8 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
221static const float dBPerStep = 0.5f;
222// shouldn't need to touch these
223static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
224static const float dBConvertInverse = 1.0f / dBConvert;
225
226float 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
234int 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
242status_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
258status_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
286status_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
302status_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
328status_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
344status_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
366status_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
399status_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
406status_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
415uint32_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
426audio_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
433void 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
441void 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
449audio_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
458void 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
479void 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
543void 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
551sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
552sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
553
554
555// establish binder interface to AudioPolicy service
556const 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
591status_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
607audio_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
616status_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
625status_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
632audio_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
640audio_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
652audio_io_handle_t AudioSystem::getOutputForAttr(const audio_attributes_t *attr,
653                                    uint32_t samplingRate,
654                                    audio_format_t format,
655                                    audio_channel_mask_t channelMask,
656                                    audio_output_flags_t flags,
657                                    const audio_offload_info_t *offloadInfo)
658{
659    if (attr == NULL) return 0;
660    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
661    if (aps == 0) return 0;
662    return aps->getOutputForAttr(attr, samplingRate, format, channelMask, flags, offloadInfo);
663}
664
665status_t AudioSystem::startOutput(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->startOutput(output, stream, session);
672}
673
674status_t AudioSystem::stopOutput(audio_io_handle_t output,
675                                 audio_stream_type_t stream,
676                                 int session)
677{
678    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
679    if (aps == 0) return PERMISSION_DENIED;
680    return aps->stopOutput(output, stream, session);
681}
682
683void AudioSystem::releaseOutput(audio_io_handle_t output)
684{
685    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
686    if (aps == 0) return;
687    aps->releaseOutput(output);
688}
689
690audio_io_handle_t AudioSystem::getInput(audio_source_t inputSource,
691                                    uint32_t samplingRate,
692                                    audio_format_t format,
693                                    audio_channel_mask_t channelMask,
694                                    int sessionId,
695                                    audio_input_flags_t flags)
696{
697    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
698    if (aps == 0) return 0;
699    return aps->getInput(inputSource, samplingRate, format, channelMask, sessionId, flags);
700}
701
702status_t AudioSystem::startInput(audio_io_handle_t input,
703                                 audio_session_t session)
704{
705    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
706    if (aps == 0) return PERMISSION_DENIED;
707    return aps->startInput(input, session);
708}
709
710status_t AudioSystem::stopInput(audio_io_handle_t input,
711                                audio_session_t session)
712{
713    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
714    if (aps == 0) return PERMISSION_DENIED;
715    return aps->stopInput(input, session);
716}
717
718void AudioSystem::releaseInput(audio_io_handle_t input,
719                               audio_session_t session)
720{
721    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
722    if (aps == 0) return;
723    aps->releaseInput(input, session);
724}
725
726status_t AudioSystem::initStreamVolume(audio_stream_type_t stream,
727                                    int indexMin,
728                                    int indexMax)
729{
730    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
731    if (aps == 0) return PERMISSION_DENIED;
732    return aps->initStreamVolume(stream, indexMin, indexMax);
733}
734
735status_t AudioSystem::setStreamVolumeIndex(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->setStreamVolumeIndex(stream, index, device);
742}
743
744status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
745                                           int *index,
746                                           audio_devices_t device)
747{
748    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
749    if (aps == 0) return PERMISSION_DENIED;
750    return aps->getStreamVolumeIndex(stream, index, device);
751}
752
753uint32_t AudioSystem::getStrategyForStream(audio_stream_type_t stream)
754{
755    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
756    if (aps == 0) return 0;
757    return aps->getStrategyForStream(stream);
758}
759
760audio_devices_t AudioSystem::getDevicesForStream(audio_stream_type_t stream)
761{
762    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
763    if (aps == 0) return AUDIO_DEVICE_NONE;
764    return aps->getDevicesForStream(stream);
765}
766
767audio_io_handle_t AudioSystem::getOutputForEffect(const effect_descriptor_t *desc)
768{
769    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
770    // FIXME change return type to status_t, and return PERMISSION_DENIED here
771    if (aps == 0) return AUDIO_IO_HANDLE_NONE;
772    return aps->getOutputForEffect(desc);
773}
774
775status_t AudioSystem::registerEffect(const effect_descriptor_t *desc,
776                                audio_io_handle_t io,
777                                uint32_t strategy,
778                                int session,
779                                int id)
780{
781    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
782    if (aps == 0) return PERMISSION_DENIED;
783    return aps->registerEffect(desc, io, strategy, session, id);
784}
785
786status_t AudioSystem::unregisterEffect(int id)
787{
788    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
789    if (aps == 0) return PERMISSION_DENIED;
790    return aps->unregisterEffect(id);
791}
792
793status_t AudioSystem::setEffectEnabled(int id, bool enabled)
794{
795    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
796    if (aps == 0) return PERMISSION_DENIED;
797    return aps->setEffectEnabled(id, enabled);
798}
799
800status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs)
801{
802    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
803    if (aps == 0) return PERMISSION_DENIED;
804    if (state == NULL) return BAD_VALUE;
805    *state = aps->isStreamActive(stream, inPastMs);
806    return NO_ERROR;
807}
808
809status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* state,
810        uint32_t inPastMs)
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->isStreamActiveRemotely(stream, inPastMs);
816    return NO_ERROR;
817}
818
819status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state)
820{
821    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
822    if (aps == 0) return PERMISSION_DENIED;
823    if (state == NULL) return BAD_VALUE;
824    *state = aps->isSourceActive(stream);
825    return NO_ERROR;
826}
827
828uint32_t AudioSystem::getPrimaryOutputSamplingRate()
829{
830    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
831    if (af == 0) return 0;
832    return af->getPrimaryOutputSamplingRate();
833}
834
835size_t AudioSystem::getPrimaryOutputFrameCount()
836{
837    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
838    if (af == 0) return 0;
839    return af->getPrimaryOutputFrameCount();
840}
841
842status_t AudioSystem::setLowRamDevice(bool isLowRamDevice)
843{
844    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
845    if (af == 0) return PERMISSION_DENIED;
846    return af->setLowRamDevice(isLowRamDevice);
847}
848
849void AudioSystem::clearAudioConfigCache()
850{
851    // called by restoreTrack_l(), which needs new IAudioFlinger and IAudioPolicyService instances
852    ALOGV("clearAudioConfigCache()");
853    {
854        Mutex::Autolock _l(gLockCache);
855        gOutputs.clear();
856    }
857    {
858        Mutex::Autolock _l(gLock);
859        gAudioFlinger.clear();
860    }
861    {
862        Mutex::Autolock _l(gLockAPS);
863        gAudioPolicyService.clear();
864    }
865    // Do not clear gAudioPortCallback
866}
867
868bool AudioSystem::isOffloadSupported(const audio_offload_info_t& info)
869{
870    ALOGV("isOffloadSupported()");
871    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
872    if (aps == 0) return false;
873    return aps->isOffloadSupported(info);
874}
875
876status_t AudioSystem::listAudioPorts(audio_port_role_t role,
877                                     audio_port_type_t type,
878                                     unsigned int *num_ports,
879                                     struct audio_port *ports,
880                                     unsigned int *generation)
881{
882    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
883    if (aps == 0) return PERMISSION_DENIED;
884    return aps->listAudioPorts(role, type, num_ports, ports, generation);
885}
886
887status_t AudioSystem::getAudioPort(struct audio_port *port)
888{
889    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
890    if (aps == 0) return PERMISSION_DENIED;
891    return aps->getAudioPort(port);
892}
893
894status_t AudioSystem::createAudioPatch(const struct audio_patch *patch,
895                                   audio_patch_handle_t *handle)
896{
897    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
898    if (aps == 0) return PERMISSION_DENIED;
899    return aps->createAudioPatch(patch, handle);
900}
901
902status_t AudioSystem::releaseAudioPatch(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->releaseAudioPatch(handle);
907}
908
909status_t AudioSystem::listAudioPatches(unsigned int *num_patches,
910                                  struct audio_patch *patches,
911                                  unsigned int *generation)
912{
913    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
914    if (aps == 0) return PERMISSION_DENIED;
915    return aps->listAudioPatches(num_patches, patches, generation);
916}
917
918status_t AudioSystem::setAudioPortConfig(const struct audio_port_config *config)
919{
920    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
921    if (aps == 0) return PERMISSION_DENIED;
922    return aps->setAudioPortConfig(config);
923}
924
925void AudioSystem::setAudioPortCallback(sp<AudioPortCallback> callBack)
926{
927    Mutex::Autolock _l(gLockAPC);
928    gAudioPortCallback = callBack;
929}
930
931status_t AudioSystem::acquireSoundTriggerSession(audio_session_t *session,
932                                       audio_io_handle_t *ioHandle,
933                                       audio_devices_t *device)
934{
935    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
936    if (aps == 0) return PERMISSION_DENIED;
937    return aps->acquireSoundTriggerSession(session, ioHandle, device);
938}
939
940status_t AudioSystem::releaseSoundTriggerSession(audio_session_t session)
941{
942    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
943    if (aps == 0) return PERMISSION_DENIED;
944    return aps->releaseSoundTriggerSession(session);
945}
946
947audio_mode_t AudioSystem::getPhoneState()
948{
949    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
950    if (aps == 0) return AUDIO_MODE_INVALID;
951    return aps->getPhoneState();
952}
953
954
955// ---------------------------------------------------------------------------
956
957void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who __unused)
958{
959    {
960        Mutex::Autolock _l(gLockAPC);
961        if (gAudioPortCallback != 0) {
962            gAudioPortCallback->onServiceDied();
963        }
964    }
965    {
966        Mutex::Autolock _l(gLockAPS);
967        AudioSystem::gAudioPolicyService.clear();
968    }
969
970    ALOGW("AudioPolicyService server died!");
971}
972
973void AudioSystem::AudioPolicyServiceClient::onAudioPortListUpdate()
974{
975    Mutex::Autolock _l(gLockAPC);
976    if (gAudioPortCallback != 0) {
977        gAudioPortCallback->onAudioPortListUpdate();
978    }
979}
980
981void AudioSystem::AudioPolicyServiceClient::onAudioPatchListUpdate()
982{
983    Mutex::Autolock _l(gLockAPC);
984    if (gAudioPortCallback != 0) {
985        gAudioPortCallback->onAudioPatchListUpdate();
986    }
987}
988
989}; // namespace android
990