AudioSystem.cpp revision eda6c364c253ba97ee45a3adeb8c2b45db1f81db
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/IAudioPolicyService.h>
24#include <math.h>
25
26// ----------------------------------------------------------------------------
27// the sim build doesn't have gettid
28
29#ifndef HAVE_GETTID
30# define gettid getpid
31#endif
32
33// ----------------------------------------------------------------------------
34
35namespace android {
36
37// client singleton for AudioFlinger binder interface
38Mutex AudioSystem::gLock;
39sp<IAudioFlinger> AudioSystem::gAudioFlinger;
40sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
41audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
42// Cached values
43DefaultKeyedVector<int, audio_io_handle_t> AudioSystem::gStreamOutputMap(0);
44DefaultKeyedVector<audio_io_handle_t, AudioSystem::OutputDescriptor *> AudioSystem::gOutputs(0);
45
46// Cached values for recording queries
47uint32_t AudioSystem::gPrevInSamplingRate = 16000;
48int AudioSystem::gPrevInFormat = AudioSystem::PCM_16_BIT;
49int AudioSystem::gPrevInChannelCount = 1;
50size_t AudioSystem::gInBuffSize = 0;
51
52
53// establish binder interface to AudioFlinger service
54const sp<IAudioFlinger>& AudioSystem::get_audio_flinger()
55{
56    Mutex::Autolock _l(gLock);
57    if (gAudioFlinger.get() == 0) {
58        sp<IServiceManager> sm = defaultServiceManager();
59        sp<IBinder> binder;
60        do {
61            binder = sm->getService(String16("media.audio_flinger"));
62            if (binder != 0)
63                break;
64            LOGW("AudioFlinger not published, waiting...");
65            usleep(500000); // 0.5 s
66        } while(true);
67        if (gAudioFlingerClient == NULL) {
68            gAudioFlingerClient = new AudioFlingerClient();
69        } else {
70            if (gAudioErrorCallback) {
71                gAudioErrorCallback(NO_ERROR);
72            }
73         }
74        binder->linkToDeath(gAudioFlingerClient);
75        gAudioFlinger = interface_cast<IAudioFlinger>(binder);
76        gAudioFlinger->registerClient(gAudioFlingerClient);
77    }
78    LOGE_IF(gAudioFlinger==0, "no AudioFlinger!?");
79
80    return gAudioFlinger;
81}
82
83status_t AudioSystem::muteMicrophone(bool state) {
84    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
85    if (af == 0) return PERMISSION_DENIED;
86    return af->setMicMute(state);
87}
88
89status_t AudioSystem::isMicrophoneMuted(bool* state) {
90    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
91    if (af == 0) return PERMISSION_DENIED;
92    *state = af->getMicMute();
93    return NO_ERROR;
94}
95
96status_t AudioSystem::setMasterVolume(float value)
97{
98    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
99    if (af == 0) return PERMISSION_DENIED;
100    af->setMasterVolume(value);
101    return NO_ERROR;
102}
103
104status_t AudioSystem::setMasterMute(bool mute)
105{
106    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
107    if (af == 0) return PERMISSION_DENIED;
108    af->setMasterMute(mute);
109    return NO_ERROR;
110}
111
112status_t AudioSystem::getMasterVolume(float* volume)
113{
114    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
115    if (af == 0) return PERMISSION_DENIED;
116    *volume = af->masterVolume();
117    return NO_ERROR;
118}
119
120status_t AudioSystem::getMasterMute(bool* mute)
121{
122    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
123    if (af == 0) return PERMISSION_DENIED;
124    *mute = af->masterMute();
125    return NO_ERROR;
126}
127
128status_t AudioSystem::setStreamVolume(int stream, float value, int output)
129{
130    if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
131    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
132    if (af == 0) return PERMISSION_DENIED;
133    af->setStreamVolume(stream, value, output);
134    return NO_ERROR;
135}
136
137status_t AudioSystem::setStreamMute(int stream, bool mute)
138{
139    if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
140    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
141    if (af == 0) return PERMISSION_DENIED;
142    af->setStreamMute(stream, mute);
143    return NO_ERROR;
144}
145
146status_t AudioSystem::getStreamVolume(int stream, float* volume, int output)
147{
148    if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
149    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
150    if (af == 0) return PERMISSION_DENIED;
151    *volume = af->streamVolume(stream, output);
152    return NO_ERROR;
153}
154
155status_t AudioSystem::getStreamMute(int stream, bool* mute)
156{
157    if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
158    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
159    if (af == 0) return PERMISSION_DENIED;
160    *mute = af->streamMute(stream);
161    return NO_ERROR;
162}
163
164status_t AudioSystem::setMode(int mode)
165{
166    if (mode >= NUM_MODES) return BAD_VALUE;
167    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
168    if (af == 0) return PERMISSION_DENIED;
169    return af->setMode(mode);
170}
171
172status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) {
173    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
174    if (af == 0) return PERMISSION_DENIED;
175    return af->setParameters(ioHandle, keyValuePairs);
176}
177
178String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys) {
179    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
180    String8 result = String8("");
181    if (af == 0) return result;
182
183    result = af->getParameters(ioHandle, keys);
184    return result;
185}
186
187// convert volume steps to natural log scale
188
189// change this value to change volume scaling
190static const float dBPerStep = 0.5f;
191// shouldn't need to touch these
192static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
193static const float dBConvertInverse = 1.0f / dBConvert;
194
195float AudioSystem::linearToLog(int volume)
196{
197    // float v = volume ? exp(float(100 - volume) * dBConvert) : 0;
198    // LOGD("linearToLog(%d)=%f", volume, v);
199    // return v;
200    return volume ? exp(float(100 - volume) * dBConvert) : 0;
201}
202
203int AudioSystem::logToLinear(float volume)
204{
205    // int v = volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
206    // LOGD("logTolinear(%d)=%f", v, volume);
207    // return v;
208    return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
209}
210
211status_t AudioSystem::getOutputSamplingRate(int* samplingRate, int streamType)
212{
213    OutputDescriptor *outputDesc;
214    audio_io_handle_t output;
215
216    if (streamType == DEFAULT) {
217        streamType = MUSIC;
218    }
219
220    output = getOutput((stream_type)streamType);
221    if (output == 0) {
222        return PERMISSION_DENIED;
223    }
224
225    gLock.lock();
226    outputDesc = AudioSystem::gOutputs.valueFor(output);
227    if (outputDesc == 0) {
228        LOGV("getOutputSamplingRate() no output descriptor for output %d in gOutputs", output);
229        gLock.unlock();
230        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
231        if (af == 0) return PERMISSION_DENIED;
232        *samplingRate = af->sampleRate(output);
233    } else {
234        LOGV("getOutputSamplingRate() reading from output desc");
235        *samplingRate = outputDesc->samplingRate;
236        gLock.unlock();
237    }
238
239    LOGV("getOutputSamplingRate() streamType %d, output %d, sampling rate %d", streamType, output, *samplingRate);
240
241    return NO_ERROR;
242}
243
244status_t AudioSystem::getOutputFrameCount(int* frameCount, int streamType)
245{
246    OutputDescriptor *outputDesc;
247    audio_io_handle_t output;
248
249    if (streamType == DEFAULT) {
250        streamType = MUSIC;
251    }
252
253    output = getOutput((stream_type)streamType);
254    if (output == 0) {
255        return PERMISSION_DENIED;
256    }
257
258    gLock.lock();
259    outputDesc = AudioSystem::gOutputs.valueFor(output);
260    if (outputDesc == 0) {
261        gLock.unlock();
262        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
263        if (af == 0) return PERMISSION_DENIED;
264        *frameCount = af->frameCount(output);
265    } else {
266        *frameCount = outputDesc->frameCount;
267        gLock.unlock();
268    }
269
270    LOGV("getOutputFrameCount() streamType %d, output %d, frameCount %d", streamType, output, *frameCount);
271
272    return NO_ERROR;
273}
274
275status_t AudioSystem::getOutputLatency(uint32_t* latency, int streamType)
276{
277    OutputDescriptor *outputDesc;
278    audio_io_handle_t output;
279
280    if (streamType == DEFAULT) {
281        streamType = MUSIC;
282    }
283
284    output = getOutput((stream_type)streamType);
285    if (output == 0) {
286        return PERMISSION_DENIED;
287    }
288
289    gLock.lock();
290    outputDesc = AudioSystem::gOutputs.valueFor(output);
291    if (outputDesc == 0) {
292        gLock.unlock();
293        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
294        if (af == 0) return PERMISSION_DENIED;
295        *latency = af->latency(output);
296    } else {
297        *latency = outputDesc->latency;
298        gLock.unlock();
299    }
300
301    LOGV("getOutputLatency() streamType %d, output %d, latency %d", streamType, output, *latency);
302
303    return NO_ERROR;
304}
305
306status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
307    size_t* buffSize)
308{
309    // Do we have a stale gInBufferSize or are we requesting the input buffer size for new values
310    if ((gInBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat)
311        || (channelCount != gPrevInChannelCount)) {
312        // save the request params
313        gPrevInSamplingRate = sampleRate;
314        gPrevInFormat = format;
315        gPrevInChannelCount = channelCount;
316
317        gInBuffSize = 0;
318        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
319        if (af == 0) {
320            return PERMISSION_DENIED;
321        }
322        gInBuffSize = af->getInputBufferSize(sampleRate, format, channelCount);
323    }
324    *buffSize = gInBuffSize;
325
326    return NO_ERROR;
327}
328
329status_t AudioSystem::setVoiceVolume(float value)
330{
331    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
332    if (af == 0) return PERMISSION_DENIED;
333    return af->setVoiceVolume(value);
334}
335
336status_t AudioSystem::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream)
337{
338    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
339    if (af == 0) return PERMISSION_DENIED;
340
341    if (stream == DEFAULT) {
342        stream = MUSIC;
343    }
344
345    return af->getRenderPosition(halFrames, dspFrames, getOutput((stream_type)stream));
346}
347
348unsigned int AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle) {
349    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
350    unsigned int result = 0;
351    if (af == 0) return result;
352    if (ioHandle == 0) return result;
353
354    result = af->getInputFramesLost(ioHandle);
355    return result;
356}
357
358int AudioSystem::newAudioSessionId() {
359    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
360    if (af == 0) return 0;
361    return af->newAudioSessionId();
362}
363
364// ---------------------------------------------------------------------------
365
366void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who) {
367    Mutex::Autolock _l(AudioSystem::gLock);
368
369    AudioSystem::gAudioFlinger.clear();
370    // clear output handles and stream to output map caches
371    AudioSystem::gStreamOutputMap.clear();
372    AudioSystem::gOutputs.clear();
373
374    if (gAudioErrorCallback) {
375        gAudioErrorCallback(DEAD_OBJECT);
376    }
377    LOGW("AudioFlinger server died!");
378}
379
380void AudioSystem::AudioFlingerClient::ioConfigChanged(int event, int ioHandle, void *param2) {
381    LOGV("ioConfigChanged() event %d", event);
382    OutputDescriptor *desc;
383    uint32_t stream;
384
385    if (ioHandle == 0) return;
386
387    Mutex::Autolock _l(AudioSystem::gLock);
388
389    switch (event) {
390    case STREAM_CONFIG_CHANGED:
391        if (param2 == 0) break;
392        stream = *(uint32_t *)param2;
393        LOGV("ioConfigChanged() STREAM_CONFIG_CHANGED stream %d, output %d", stream, ioHandle);
394        if (gStreamOutputMap.indexOfKey(stream) >= 0) {
395            gStreamOutputMap.replaceValueFor(stream, ioHandle);
396        }
397        break;
398    case OUTPUT_OPENED: {
399        if (gOutputs.indexOfKey(ioHandle) >= 0) {
400            LOGV("ioConfigChanged() opening already existing output! %d", ioHandle);
401            break;
402        }
403        if (param2 == 0) break;
404        desc = (OutputDescriptor *)param2;
405
406        OutputDescriptor *outputDesc =  new OutputDescriptor(*desc);
407        gOutputs.add(ioHandle, outputDesc);
408        LOGV("ioConfigChanged() new output samplingRate %d, format %d channels %d frameCount %d latency %d",
409                outputDesc->samplingRate, outputDesc->format, outputDesc->channels, outputDesc->frameCount, outputDesc->latency);
410        } break;
411    case OUTPUT_CLOSED: {
412        if (gOutputs.indexOfKey(ioHandle) < 0) {
413            LOGW("ioConfigChanged() closing unknow output! %d", ioHandle);
414            break;
415        }
416        LOGV("ioConfigChanged() output %d closed", ioHandle);
417
418        gOutputs.removeItem(ioHandle);
419        for (int i = gStreamOutputMap.size() - 1; i >= 0 ; i--) {
420            if (gStreamOutputMap.valueAt(i) == ioHandle) {
421                gStreamOutputMap.removeItemsAt(i);
422            }
423        }
424        } break;
425
426    case OUTPUT_CONFIG_CHANGED: {
427        int index = gOutputs.indexOfKey(ioHandle);
428        if (index < 0) {
429            LOGW("ioConfigChanged() modifying unknow output! %d", ioHandle);
430            break;
431        }
432        if (param2 == 0) break;
433        desc = (OutputDescriptor *)param2;
434
435        LOGV("ioConfigChanged() new config for output %d samplingRate %d, format %d channels %d frameCount %d latency %d",
436                ioHandle, desc->samplingRate, desc->format,
437                desc->channels, desc->frameCount, desc->latency);
438        OutputDescriptor *outputDesc = gOutputs.valueAt(index);
439        delete outputDesc;
440        outputDesc =  new OutputDescriptor(*desc);
441        gOutputs.replaceValueFor(ioHandle, outputDesc);
442    } break;
443    case INPUT_OPENED:
444    case INPUT_CLOSED:
445    case INPUT_CONFIG_CHANGED:
446        break;
447
448    }
449}
450
451void AudioSystem::setErrorCallback(audio_error_callback cb) {
452    Mutex::Autolock _l(gLock);
453    gAudioErrorCallback = cb;
454}
455
456bool AudioSystem::routedToA2dpOutput(int streamType) {
457    switch(streamType) {
458    case MUSIC:
459    case VOICE_CALL:
460    case BLUETOOTH_SCO:
461    case SYSTEM:
462        return true;
463    default:
464        return false;
465    }
466}
467
468
469// client singleton for AudioPolicyService binder interface
470sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
471sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
472
473
474// establish binder interface to AudioFlinger service
475const sp<IAudioPolicyService>& AudioSystem::get_audio_policy_service()
476{
477    gLock.lock();
478    if (gAudioPolicyService.get() == 0) {
479        sp<IServiceManager> sm = defaultServiceManager();
480        sp<IBinder> binder;
481        do {
482            binder = sm->getService(String16("media.audio_policy"));
483            if (binder != 0)
484                break;
485            LOGW("AudioPolicyService not published, waiting...");
486            usleep(500000); // 0.5 s
487        } while(true);
488        if (gAudioPolicyServiceClient == NULL) {
489            gAudioPolicyServiceClient = new AudioPolicyServiceClient();
490        }
491        binder->linkToDeath(gAudioPolicyServiceClient);
492        gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
493        gLock.unlock();
494    } else {
495        gLock.unlock();
496    }
497    return gAudioPolicyService;
498}
499
500status_t AudioSystem::setDeviceConnectionState(audio_devices device,
501                                                  device_connection_state state,
502                                                  const char *device_address)
503{
504    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
505    if (aps == 0) return PERMISSION_DENIED;
506
507    return aps->setDeviceConnectionState(device, state, device_address);
508}
509
510AudioSystem::device_connection_state AudioSystem::getDeviceConnectionState(audio_devices device,
511                                                  const char *device_address)
512{
513    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
514    if (aps == 0) return DEVICE_STATE_UNAVAILABLE;
515
516    return aps->getDeviceConnectionState(device, device_address);
517}
518
519status_t AudioSystem::setPhoneState(int state)
520{
521    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
522    if (aps == 0) return PERMISSION_DENIED;
523
524    return aps->setPhoneState(state);
525}
526
527status_t AudioSystem::setRingerMode(uint32_t mode, uint32_t mask)
528{
529    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
530    if (aps == 0) return PERMISSION_DENIED;
531    return aps->setRingerMode(mode, mask);
532}
533
534status_t AudioSystem::setForceUse(force_use usage, forced_config config)
535{
536    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
537    if (aps == 0) return PERMISSION_DENIED;
538    return aps->setForceUse(usage, config);
539}
540
541AudioSystem::forced_config AudioSystem::getForceUse(force_use usage)
542{
543    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
544    if (aps == 0) return FORCE_NONE;
545    return aps->getForceUse(usage);
546}
547
548
549audio_io_handle_t AudioSystem::getOutput(stream_type stream,
550                                    uint32_t samplingRate,
551                                    uint32_t format,
552                                    uint32_t channels,
553                                    output_flags flags)
554{
555    audio_io_handle_t output = 0;
556    // Do not use stream to output map cache if the direct output
557    // flag is set or if we are likely to use a direct output
558    // (e.g voice call stream @ 8kHz could use BT SCO device and be routed to
559    // a direct output on some platforms).
560    // TODO: the output cache and stream to output mapping implementation needs to
561    // be reworked for proper operation with direct outputs. This code is too specific
562    // to the first use case we want to cover (Voice Recognition and Voice Dialer over
563    // Bluetooth SCO
564    if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) == 0 &&
565        ((stream != AudioSystem::VOICE_CALL && stream != AudioSystem::BLUETOOTH_SCO) ||
566         channels != AudioSystem::CHANNEL_OUT_MONO ||
567         (samplingRate != 8000 && samplingRate != 16000))) {
568        Mutex::Autolock _l(gLock);
569        output = AudioSystem::gStreamOutputMap.valueFor(stream);
570        LOGV_IF((output != 0), "getOutput() read %d from cache for stream %d", output, stream);
571    }
572    if (output == 0) {
573        const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
574        if (aps == 0) return 0;
575        output = aps->getOutput(stream, samplingRate, format, channels, flags);
576        if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) == 0) {
577            Mutex::Autolock _l(gLock);
578            AudioSystem::gStreamOutputMap.add(stream, output);
579        }
580    }
581    return output;
582}
583
584status_t AudioSystem::startOutput(audio_io_handle_t output,
585                                  AudioSystem::stream_type stream,
586                                  int session)
587{
588    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
589    if (aps == 0) return PERMISSION_DENIED;
590    return aps->startOutput(output, stream, session);
591}
592
593status_t AudioSystem::stopOutput(audio_io_handle_t output,
594                                 AudioSystem::stream_type stream,
595                                 int session)
596{
597    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
598    if (aps == 0) return PERMISSION_DENIED;
599    return aps->stopOutput(output, stream, session);
600}
601
602void AudioSystem::releaseOutput(audio_io_handle_t output)
603{
604    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
605    if (aps == 0) return;
606    aps->releaseOutput(output);
607}
608
609audio_io_handle_t AudioSystem::getInput(int inputSource,
610                                    uint32_t samplingRate,
611                                    uint32_t format,
612                                    uint32_t channels,
613                                    audio_in_acoustics acoustics)
614{
615    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
616    if (aps == 0) return 0;
617    return aps->getInput(inputSource, samplingRate, format, channels, acoustics);
618}
619
620status_t AudioSystem::startInput(audio_io_handle_t input)
621{
622    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
623    if (aps == 0) return PERMISSION_DENIED;
624    return aps->startInput(input);
625}
626
627status_t AudioSystem::stopInput(audio_io_handle_t input)
628{
629    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
630    if (aps == 0) return PERMISSION_DENIED;
631    return aps->stopInput(input);
632}
633
634void AudioSystem::releaseInput(audio_io_handle_t input)
635{
636    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
637    if (aps == 0) return;
638    aps->releaseInput(input);
639}
640
641status_t AudioSystem::initStreamVolume(stream_type stream,
642                                    int indexMin,
643                                    int indexMax)
644{
645    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
646    if (aps == 0) return PERMISSION_DENIED;
647    return aps->initStreamVolume(stream, indexMin, indexMax);
648}
649
650status_t AudioSystem::setStreamVolumeIndex(stream_type stream, int index)
651{
652    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
653    if (aps == 0) return PERMISSION_DENIED;
654    return aps->setStreamVolumeIndex(stream, index);
655}
656
657status_t AudioSystem::getStreamVolumeIndex(stream_type stream, int *index)
658{
659    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
660    if (aps == 0) return PERMISSION_DENIED;
661    return aps->getStreamVolumeIndex(stream, index);
662}
663
664uint32_t AudioSystem::getStrategyForStream(AudioSystem::stream_type stream)
665{
666    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
667    if (aps == 0) return 0;
668    return aps->getStrategyForStream(stream);
669}
670
671audio_io_handle_t AudioSystem::getOutputForEffect(effect_descriptor_t *desc)
672{
673    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
674    if (aps == 0) return PERMISSION_DENIED;
675    return aps->getOutputForEffect(desc);
676}
677
678status_t AudioSystem::registerEffect(effect_descriptor_t *desc,
679                                audio_io_handle_t output,
680                                uint32_t strategy,
681                                int session,
682                                int id)
683{
684    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
685    if (aps == 0) return PERMISSION_DENIED;
686    return aps->registerEffect(desc, output, strategy, session, id);
687}
688
689status_t AudioSystem::unregisterEffect(int id)
690{
691    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
692    if (aps == 0) return PERMISSION_DENIED;
693    return aps->unregisterEffect(id);
694}
695
696status_t AudioSystem::isStreamActive(int stream, bool* state, uint32_t inPastMs) {
697    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
698    if (aps == 0) return PERMISSION_DENIED;
699    *state = aps->isStreamActive(stream, inPastMs);
700    return NO_ERROR;
701}
702
703
704// ---------------------------------------------------------------------------
705
706void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who) {
707    Mutex::Autolock _l(AudioSystem::gLock);
708    AudioSystem::gAudioPolicyService.clear();
709
710    LOGW("AudioPolicyService server died!");
711}
712
713// ---------------------------------------------------------------------------
714
715
716// use emulated popcount optimization
717// http://www.df.lth.se/~john_e/gems/gem002d.html
718uint32_t AudioSystem::popCount(uint32_t u)
719{
720    u = ((u&0x55555555) + ((u>>1)&0x55555555));
721    u = ((u&0x33333333) + ((u>>2)&0x33333333));
722    u = ((u&0x0f0f0f0f) + ((u>>4)&0x0f0f0f0f));
723    u = ((u&0x00ff00ff) + ((u>>8)&0x00ff00ff));
724    u = ( u&0x0000ffff) + (u>>16);
725    return u;
726}
727
728bool AudioSystem::isOutputDevice(audio_devices device)
729{
730    if ((popCount(device) == 1 ) &&
731        ((device & ~AudioSystem::DEVICE_OUT_ALL) == 0)) {
732        return true;
733    } else {
734        return false;
735    }
736}
737
738bool AudioSystem::isInputDevice(audio_devices device)
739{
740    if ((popCount(device) == 1 ) &&
741        ((device & ~AudioSystem::DEVICE_IN_ALL) == 0)) {
742        return true;
743    } else {
744        return false;
745    }
746}
747
748bool AudioSystem::isA2dpDevice(audio_devices device)
749{
750    if ((popCount(device) == 1 ) &&
751        (device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
752                   AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
753                   AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER))) {
754        return true;
755    } else {
756        return false;
757    }
758}
759
760bool AudioSystem::isBluetoothScoDevice(audio_devices device)
761{
762    if ((popCount(device) == 1 ) &&
763        (device & (AudioSystem::DEVICE_OUT_BLUETOOTH_SCO |
764                   AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
765                   AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT |
766                   AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET))) {
767        return true;
768    } else {
769        return false;
770    }
771}
772
773bool AudioSystem::isLowVisibility(stream_type stream)
774{
775    if (stream == AudioSystem::SYSTEM ||
776        stream == AudioSystem::NOTIFICATION ||
777        stream == AudioSystem::RING) {
778        return true;
779    } else {
780        return false;
781    }
782}
783
784bool AudioSystem::isInputChannel(uint32_t channel)
785{
786    if ((channel & ~AudioSystem::CHANNEL_IN_ALL) == 0) {
787        return true;
788    } else {
789        return false;
790    }
791}
792
793bool AudioSystem::isOutputChannel(uint32_t channel)
794{
795    if ((channel & ~AudioSystem::CHANNEL_OUT_ALL) == 0) {
796        return true;
797    } else {
798        return false;
799    }
800}
801
802bool AudioSystem::isValidFormat(uint32_t format)
803{
804    switch (format & MAIN_FORMAT_MASK) {
805    case         PCM:
806    case         MP3:
807    case         AMR_NB:
808    case         AMR_WB:
809    case         AAC:
810    case         HE_AAC_V1:
811    case         HE_AAC_V2:
812    case         VORBIS:
813        return true;
814    default:
815        return false;
816    }
817}
818
819bool AudioSystem::isLinearPCM(uint32_t format)
820{
821    switch (format) {
822    case         PCM_16_BIT:
823    case         PCM_8_BIT:
824        return true;
825    default:
826        return false;
827    }
828}
829
830//------------------------- AudioParameter class implementation ---------------
831
832const char *AudioParameter::keyRouting = "routing";
833const char *AudioParameter::keySamplingRate = "sampling_rate";
834const char *AudioParameter::keyFormat = "format";
835const char *AudioParameter::keyChannels = "channels";
836const char *AudioParameter::keyFrameCount = "frame_count";
837const char *AudioParameter::keyInputSource = "input_source";
838
839AudioParameter::AudioParameter(const String8& keyValuePairs)
840{
841    char *str = new char[keyValuePairs.length()+1];
842    mKeyValuePairs = keyValuePairs;
843
844    strcpy(str, keyValuePairs.string());
845    char *pair = strtok(str, ";");
846    while (pair != NULL) {
847        if (strlen(pair) != 0) {
848            size_t eqIdx = strcspn(pair, "=");
849            String8 key = String8(pair, eqIdx);
850            String8 value;
851            if (eqIdx == strlen(pair)) {
852                value = String8("");
853            } else {
854                value = String8(pair + eqIdx + 1);
855            }
856            if (mParameters.indexOfKey(key) < 0) {
857                mParameters.add(key, value);
858            } else {
859                mParameters.replaceValueFor(key, value);
860            }
861        } else {
862            LOGV("AudioParameter() cstor empty key value pair");
863        }
864        pair = strtok(NULL, ";");
865    }
866
867    delete[] str;
868}
869
870AudioParameter::~AudioParameter()
871{
872    mParameters.clear();
873}
874
875String8 AudioParameter::toString()
876{
877    String8 str = String8("");
878
879    size_t size = mParameters.size();
880    for (size_t i = 0; i < size; i++) {
881        str += mParameters.keyAt(i);
882        str += "=";
883        str += mParameters.valueAt(i);
884        if (i < (size - 1)) str += ";";
885    }
886    return str;
887}
888
889status_t AudioParameter::add(const String8& key, const String8& value)
890{
891    if (mParameters.indexOfKey(key) < 0) {
892        mParameters.add(key, value);
893        return NO_ERROR;
894    } else {
895        mParameters.replaceValueFor(key, value);
896        return ALREADY_EXISTS;
897    }
898}
899
900status_t AudioParameter::addInt(const String8& key, const int value)
901{
902    char str[12];
903    if (snprintf(str, 12, "%d", value) > 0) {
904        String8 str8 = String8(str);
905        return add(key, str8);
906    } else {
907        return BAD_VALUE;
908    }
909}
910
911status_t AudioParameter::addFloat(const String8& key, const float value)
912{
913    char str[23];
914    if (snprintf(str, 23, "%.10f", value) > 0) {
915        String8 str8 = String8(str);
916        return add(key, str8);
917    } else {
918        return BAD_VALUE;
919    }
920}
921
922status_t AudioParameter::remove(const String8& key)
923{
924    if (mParameters.indexOfKey(key) >= 0) {
925        mParameters.removeItem(key);
926        return NO_ERROR;
927    } else {
928        return BAD_VALUE;
929    }
930}
931
932status_t AudioParameter::get(const String8& key, String8& value)
933{
934    if (mParameters.indexOfKey(key) >= 0) {
935        value = mParameters.valueFor(key);
936        return NO_ERROR;
937    } else {
938        return BAD_VALUE;
939    }
940}
941
942status_t AudioParameter::getInt(const String8& key, int& value)
943{
944    String8 str8;
945    status_t result = get(key, str8);
946    value = 0;
947    if (result == NO_ERROR) {
948        int val;
949        if (sscanf(str8.string(), "%d", &val) == 1) {
950            value = val;
951        } else {
952            result = INVALID_OPERATION;
953        }
954    }
955    return result;
956}
957
958status_t AudioParameter::getFloat(const String8& key, float& value)
959{
960    String8 str8;
961    status_t result = get(key, str8);
962    value = 0;
963    if (result == NO_ERROR) {
964        float val;
965        if (sscanf(str8.string(), "%f", &val) == 1) {
966            value = val;
967        } else {
968            result = INVALID_OPERATION;
969        }
970    }
971    return result;
972}
973
974status_t AudioParameter::getAt(size_t index, String8& key, String8& value)
975{
976    if (mParameters.size() > index) {
977        key = mParameters.keyAt(index);
978        value = mParameters.valueAt(index);
979        return NO_ERROR;
980    } else {
981        return BAD_VALUE;
982    }
983}
984}; // namespace android
985
986