AudioSystem.cpp revision e1dd2075105317ef8ff2b924423c88856e8fe8ea
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 <binder/ProcessState.h>
23#include <media/AudioSystem.h>
24#include <media/IAudioFlinger.h>
25#include <media/IAudioPolicyService.h>
26#include <math.h>
27
28#include <system/audio.h>
29
30// ----------------------------------------------------------------------------
31
32namespace android {
33
34// client singleton for AudioFlinger binder interface
35Mutex AudioSystem::gLock;
36Mutex AudioSystem::gLockAPS;
37sp<IAudioFlinger> AudioSystem::gAudioFlinger;
38sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
39audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
40dynamic_policy_callback AudioSystem::gDynPolicyCallback = NULL;
41record_config_callback  AudioSystem::gRecordConfigCallback = NULL;
42
43
44// establish binder interface to AudioFlinger service
45const sp<IAudioFlinger> AudioSystem::get_audio_flinger()
46{
47    sp<IAudioFlinger> af;
48    sp<AudioFlingerClient> afc;
49    {
50        Mutex::Autolock _l(gLock);
51        if (gAudioFlinger == 0) {
52            sp<IServiceManager> sm = defaultServiceManager();
53            sp<IBinder> binder;
54            do {
55                binder = sm->getService(String16("media.audio_flinger"));
56                if (binder != 0)
57                    break;
58                ALOGW("AudioFlinger not published, waiting...");
59                usleep(500000); // 0.5 s
60            } while (true);
61            if (gAudioFlingerClient == NULL) {
62                gAudioFlingerClient = new AudioFlingerClient();
63            } else {
64                if (gAudioErrorCallback) {
65                    gAudioErrorCallback(NO_ERROR);
66                }
67            }
68            binder->linkToDeath(gAudioFlingerClient);
69            gAudioFlinger = interface_cast<IAudioFlinger>(binder);
70            LOG_ALWAYS_FATAL_IF(gAudioFlinger == 0);
71            afc = gAudioFlingerClient;
72            // Make sure callbacks can be received by gAudioFlingerClient
73            ProcessState::self()->startThreadPool();
74        }
75        af = gAudioFlinger;
76    }
77    if (afc != 0) {
78        af->registerClient(afc);
79    }
80    return af;
81}
82
83const sp<AudioSystem::AudioFlingerClient> AudioSystem::getAudioFlingerClient()
84{
85    // calling get_audio_flinger() will initialize gAudioFlingerClient if needed
86    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
87    if (af == 0) return 0;
88    Mutex::Autolock _l(gLock);
89    return gAudioFlingerClient;
90}
91
92sp<AudioIoDescriptor> AudioSystem::getIoDescriptor(audio_io_handle_t ioHandle)
93{
94    sp<AudioIoDescriptor> desc;
95    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
96    if (afc != 0) {
97        desc = afc->getIoDescriptor(ioHandle);
98    }
99    return desc;
100}
101
102/* static */ status_t AudioSystem::checkAudioFlinger()
103{
104    if (defaultServiceManager()->checkService(String16("media.audio_flinger")) != 0) {
105        return NO_ERROR;
106    }
107    return DEAD_OBJECT;
108}
109
110// FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp
111
112status_t AudioSystem::muteMicrophone(bool state)
113{
114    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
115    if (af == 0) return PERMISSION_DENIED;
116    return af->setMicMute(state);
117}
118
119status_t AudioSystem::isMicrophoneMuted(bool* state)
120{
121    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
122    if (af == 0) return PERMISSION_DENIED;
123    *state = af->getMicMute();
124    return NO_ERROR;
125}
126
127status_t AudioSystem::setMasterVolume(float value)
128{
129    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
130    if (af == 0) return PERMISSION_DENIED;
131    af->setMasterVolume(value);
132    return NO_ERROR;
133}
134
135status_t AudioSystem::setMasterMute(bool mute)
136{
137    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
138    if (af == 0) return PERMISSION_DENIED;
139    af->setMasterMute(mute);
140    return NO_ERROR;
141}
142
143status_t AudioSystem::getMasterVolume(float* volume)
144{
145    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
146    if (af == 0) return PERMISSION_DENIED;
147    *volume = af->masterVolume();
148    return NO_ERROR;
149}
150
151status_t AudioSystem::getMasterMute(bool* mute)
152{
153    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
154    if (af == 0) return PERMISSION_DENIED;
155    *mute = af->masterMute();
156    return NO_ERROR;
157}
158
159status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
160        audio_io_handle_t output)
161{
162    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
163    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
164    if (af == 0) return PERMISSION_DENIED;
165    af->setStreamVolume(stream, value, output);
166    return NO_ERROR;
167}
168
169status_t AudioSystem::setStreamMute(audio_stream_type_t stream, bool mute)
170{
171    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
172    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
173    if (af == 0) return PERMISSION_DENIED;
174    af->setStreamMute(stream, mute);
175    return NO_ERROR;
176}
177
178status_t AudioSystem::getStreamVolume(audio_stream_type_t stream, float* volume,
179        audio_io_handle_t output)
180{
181    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
182    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
183    if (af == 0) return PERMISSION_DENIED;
184    *volume = af->streamVolume(stream, output);
185    return NO_ERROR;
186}
187
188status_t AudioSystem::getStreamMute(audio_stream_type_t stream, bool* mute)
189{
190    if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
191    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
192    if (af == 0) return PERMISSION_DENIED;
193    *mute = af->streamMute(stream);
194    return NO_ERROR;
195}
196
197status_t AudioSystem::setMode(audio_mode_t mode)
198{
199    if (uint32_t(mode) >= AUDIO_MODE_CNT) return BAD_VALUE;
200    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
201    if (af == 0) return PERMISSION_DENIED;
202    return af->setMode(mode);
203}
204
205status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
206{
207    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
208    if (af == 0) return PERMISSION_DENIED;
209    return af->setParameters(ioHandle, keyValuePairs);
210}
211
212String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys)
213{
214    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
215    String8 result = String8("");
216    if (af == 0) return result;
217
218    result = af->getParameters(ioHandle, keys);
219    return result;
220}
221
222status_t AudioSystem::setParameters(const String8& keyValuePairs)
223{
224    return setParameters(AUDIO_IO_HANDLE_NONE, keyValuePairs);
225}
226
227String8 AudioSystem::getParameters(const String8& keys)
228{
229    return getParameters(AUDIO_IO_HANDLE_NONE, keys);
230}
231
232// convert volume steps to natural log scale
233
234// change this value to change volume scaling
235static const float dBPerStep = 0.5f;
236// shouldn't need to touch these
237static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
238static const float dBConvertInverse = 1.0f / dBConvert;
239
240float AudioSystem::linearToLog(int volume)
241{
242    // float v = volume ? exp(float(100 - volume) * dBConvert) : 0;
243    // ALOGD("linearToLog(%d)=%f", volume, v);
244    // return v;
245    return volume ? exp(float(100 - volume) * dBConvert) : 0;
246}
247
248int AudioSystem::logToLinear(float volume)
249{
250    // int v = volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
251    // ALOGD("logTolinear(%d)=%f", v, volume);
252    // return v;
253    return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
254}
255
256status_t AudioSystem::getOutputSamplingRate(uint32_t* samplingRate, audio_stream_type_t streamType)
257{
258    audio_io_handle_t output;
259
260    if (streamType == AUDIO_STREAM_DEFAULT) {
261        streamType = AUDIO_STREAM_MUSIC;
262    }
263
264    output = getOutput(streamType);
265    if (output == 0) {
266        return PERMISSION_DENIED;
267    }
268
269    return getSamplingRate(output, samplingRate);
270}
271
272status_t AudioSystem::getSamplingRate(audio_io_handle_t ioHandle,
273                                      uint32_t* samplingRate)
274{
275    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
276    if (af == 0) return PERMISSION_DENIED;
277    sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
278    if (desc == 0) {
279        *samplingRate = af->sampleRate(ioHandle);
280    } else {
281        *samplingRate = desc->mSamplingRate;
282    }
283    if (*samplingRate == 0) {
284        ALOGE("AudioSystem::getSamplingRate failed for ioHandle %d", ioHandle);
285        return BAD_VALUE;
286    }
287
288    ALOGV("getSamplingRate() ioHandle %d, sampling rate %u", ioHandle, *samplingRate);
289
290    return NO_ERROR;
291}
292
293status_t AudioSystem::getOutputFrameCount(size_t* frameCount, audio_stream_type_t streamType)
294{
295    audio_io_handle_t output;
296
297    if (streamType == AUDIO_STREAM_DEFAULT) {
298        streamType = AUDIO_STREAM_MUSIC;
299    }
300
301    output = getOutput(streamType);
302    if (output == AUDIO_IO_HANDLE_NONE) {
303        return PERMISSION_DENIED;
304    }
305
306    return getFrameCount(output, frameCount);
307}
308
309status_t AudioSystem::getFrameCount(audio_io_handle_t ioHandle,
310                                    size_t* frameCount)
311{
312    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
313    if (af == 0) return PERMISSION_DENIED;
314    sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
315    if (desc == 0) {
316        *frameCount = af->frameCount(ioHandle);
317    } else {
318        *frameCount = desc->mFrameCount;
319    }
320    if (*frameCount == 0) {
321        ALOGE("AudioSystem::getFrameCount failed for ioHandle %d", ioHandle);
322        return BAD_VALUE;
323    }
324
325    ALOGV("getFrameCount() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
326
327    return NO_ERROR;
328}
329
330status_t AudioSystem::getOutputLatency(uint32_t* latency, audio_stream_type_t streamType)
331{
332    audio_io_handle_t output;
333
334    if (streamType == AUDIO_STREAM_DEFAULT) {
335        streamType = AUDIO_STREAM_MUSIC;
336    }
337
338    output = getOutput(streamType);
339    if (output == AUDIO_IO_HANDLE_NONE) {
340        return PERMISSION_DENIED;
341    }
342
343    return getLatency(output, latency);
344}
345
346status_t AudioSystem::getLatency(audio_io_handle_t output,
347                                 uint32_t* latency)
348{
349    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
350    if (af == 0) return PERMISSION_DENIED;
351    sp<AudioIoDescriptor> outputDesc = getIoDescriptor(output);
352    if (outputDesc == 0) {
353        *latency = af->latency(output);
354    } else {
355        *latency = outputDesc->mLatency;
356    }
357
358    ALOGV("getLatency() output %d, latency %d", output, *latency);
359
360    return NO_ERROR;
361}
362
363status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
364        audio_channel_mask_t channelMask, size_t* buffSize)
365{
366    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
367    if (afc == 0) {
368        return NO_INIT;
369    }
370    return afc->getInputBufferSize(sampleRate, format, channelMask, buffSize);
371}
372
373status_t AudioSystem::setVoiceVolume(float value)
374{
375    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
376    if (af == 0) return PERMISSION_DENIED;
377    return af->setVoiceVolume(value);
378}
379
380status_t AudioSystem::getRenderPosition(audio_io_handle_t output, uint32_t *halFrames,
381                                        uint32_t *dspFrames)
382{
383    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
384    if (af == 0) return PERMISSION_DENIED;
385
386    return af->getRenderPosition(halFrames, dspFrames, output);
387}
388
389uint32_t AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle)
390{
391    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
392    uint32_t result = 0;
393    if (af == 0) return result;
394    if (ioHandle == AUDIO_IO_HANDLE_NONE) return result;
395
396    result = af->getInputFramesLost(ioHandle);
397    return result;
398}
399
400audio_unique_id_t AudioSystem::newAudioUniqueId(audio_unique_id_use_t use)
401{
402    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
403    if (af == 0) return AUDIO_UNIQUE_ID_ALLOCATE;
404    return af->newAudioUniqueId(use);
405}
406
407void AudioSystem::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
408{
409    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
410    if (af != 0) {
411        af->acquireAudioSessionId(audioSession, pid);
412    }
413}
414
415void AudioSystem::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
416{
417    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
418    if (af != 0) {
419        af->releaseAudioSessionId(audioSession, pid);
420    }
421}
422
423audio_hw_sync_t AudioSystem::getAudioHwSyncForSession(audio_session_t sessionId)
424{
425    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
426    if (af == 0) return AUDIO_HW_SYNC_INVALID;
427    return af->getAudioHwSyncForSession(sessionId);
428}
429
430status_t AudioSystem::systemReady()
431{
432    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
433    if (af == 0) return NO_INIT;
434    return af->systemReady();
435}
436
437status_t AudioSystem::getFrameCountHAL(audio_io_handle_t ioHandle,
438                                       size_t* frameCount)
439{
440    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
441    if (af == 0) return PERMISSION_DENIED;
442    sp<AudioIoDescriptor> desc = getIoDescriptor(ioHandle);
443    if (desc == 0) {
444        *frameCount = af->frameCountHAL(ioHandle);
445    } else {
446        *frameCount = desc->mFrameCountHAL;
447    }
448    if (*frameCount == 0) {
449        ALOGE("AudioSystem::getFrameCountHAL failed for ioHandle %d", ioHandle);
450        return BAD_VALUE;
451    }
452
453    ALOGV("getFrameCountHAL() ioHandle %d, frameCount %zu", ioHandle, *frameCount);
454
455    return NO_ERROR;
456}
457
458// ---------------------------------------------------------------------------
459
460
461void AudioSystem::AudioFlingerClient::clearIoCache()
462{
463    Mutex::Autolock _l(mLock);
464    mIoDescriptors.clear();
465    mInBuffSize = 0;
466    mInSamplingRate = 0;
467    mInFormat = AUDIO_FORMAT_DEFAULT;
468    mInChannelMask = AUDIO_CHANNEL_NONE;
469}
470
471void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who __unused)
472{
473    audio_error_callback cb = NULL;
474    {
475        Mutex::Autolock _l(AudioSystem::gLock);
476        AudioSystem::gAudioFlinger.clear();
477        cb = gAudioErrorCallback;
478    }
479
480    // clear output handles and stream to output map caches
481    clearIoCache();
482
483    if (cb) {
484        cb(DEAD_OBJECT);
485    }
486    ALOGW("AudioFlinger server died!");
487}
488
489void AudioSystem::AudioFlingerClient::ioConfigChanged(audio_io_config_event event,
490                                                      const sp<AudioIoDescriptor>& ioDesc) {
491    ALOGV("ioConfigChanged() event %d", event);
492
493    if (ioDesc == 0 || ioDesc->mIoHandle == AUDIO_IO_HANDLE_NONE) return;
494
495    audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
496    Vector < wp<AudioDeviceCallback> > callbacks;
497
498    {
499        Mutex::Autolock _l(mLock);
500
501        switch (event) {
502        case AUDIO_OUTPUT_OPENED:
503        case AUDIO_OUTPUT_REGISTERED:
504        case AUDIO_INPUT_OPENED:
505        case AUDIO_INPUT_REGISTERED: {
506            sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
507            if (oldDesc == 0) {
508                mIoDescriptors.add(ioDesc->mIoHandle, ioDesc);
509            } else {
510                deviceId = oldDesc->getDeviceId();
511                mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc);
512            }
513
514            if (ioDesc->getDeviceId() != AUDIO_PORT_HANDLE_NONE) {
515                deviceId = ioDesc->getDeviceId();
516                if (event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED) {
517                    ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(ioDesc->mIoHandle);
518                    if (ioIndex >= 0) {
519                        callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
520                    }
521                }
522            }
523            ALOGV("ioConfigChanged() new %s %s %d samplingRate %u, format %#x channel mask %#x "
524                    "frameCount %zu deviceId %d",
525                    event == AUDIO_OUTPUT_OPENED || event == AUDIO_OUTPUT_REGISTERED ?
526                            "output" : "input",
527                            event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED ?
528                            "opened" : "registered",
529                    ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat, ioDesc->mChannelMask,
530                    ioDesc->mFrameCount, ioDesc->getDeviceId());
531            } break;
532        case AUDIO_OUTPUT_CLOSED:
533        case AUDIO_INPUT_CLOSED: {
534            if (getIoDescriptor_l(ioDesc->mIoHandle) == 0) {
535                ALOGW("ioConfigChanged() closing unknown %s %d",
536                      event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
537                break;
538            }
539            ALOGV("ioConfigChanged() %s %d closed",
540                  event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
541
542            mIoDescriptors.removeItem(ioDesc->mIoHandle);
543            mAudioDeviceCallbacks.removeItem(ioDesc->mIoHandle);
544            } break;
545
546        case AUDIO_OUTPUT_CONFIG_CHANGED:
547        case AUDIO_INPUT_CONFIG_CHANGED: {
548            sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
549            if (oldDesc == 0) {
550                ALOGW("ioConfigChanged() modifying unknown output! %d", ioDesc->mIoHandle);
551                break;
552            }
553
554            deviceId = oldDesc->getDeviceId();
555            mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc);
556
557            if (deviceId != ioDesc->getDeviceId()) {
558                deviceId = ioDesc->getDeviceId();
559                ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(ioDesc->mIoHandle);
560                if (ioIndex >= 0) {
561                    callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
562                }
563            }
564            ALOGV("ioConfigChanged() new config for %s %d samplingRate %u, format %#x "
565                    "channel mask %#x frameCount %zu frameCountHAL %zu deviceId %d",
566                    event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input",
567                    ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat,
568                    ioDesc->mChannelMask, ioDesc->mFrameCount, ioDesc->mFrameCountHAL,
569                    ioDesc->getDeviceId());
570
571        } break;
572        }
573    }
574    bool callbackRemoved = false;
575    // callbacks.size() != 0 =>  ioDesc->mIoHandle and deviceId are valid
576    for (size_t i = 0; i < callbacks.size(); ) {
577        sp<AudioDeviceCallback> callback = callbacks[i].promote();
578        if (callback.get() != nullptr) {
579            callback->onAudioDeviceUpdate(ioDesc->mIoHandle, deviceId);
580            i++;
581        } else {
582            callbacks.removeAt(i);
583            callbackRemoved = true;
584        }
585    }
586    // clean up callback list while we are here if some clients have disappeared without
587    // unregistering their callback
588    if (callbackRemoved) {
589        Mutex::Autolock _l(mLock);
590        mAudioDeviceCallbacks.replaceValueFor(ioDesc->mIoHandle, callbacks);
591    }
592}
593
594status_t AudioSystem::AudioFlingerClient::getInputBufferSize(
595                                                uint32_t sampleRate, audio_format_t format,
596                                                audio_channel_mask_t channelMask, size_t* buffSize)
597{
598    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
599    if (af == 0) {
600        return PERMISSION_DENIED;
601    }
602    Mutex::Autolock _l(mLock);
603    // Do we have a stale mInBuffSize or are we requesting the input buffer size for new values
604    if ((mInBuffSize == 0) || (sampleRate != mInSamplingRate) || (format != mInFormat)
605        || (channelMask != mInChannelMask)) {
606        size_t inBuffSize = af->getInputBufferSize(sampleRate, format, channelMask);
607        if (inBuffSize == 0) {
608            ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %#x channelMask %x",
609                    sampleRate, format, channelMask);
610            return BAD_VALUE;
611        }
612        // A benign race is possible here: we could overwrite a fresher cache entry
613        // save the request params
614        mInSamplingRate = sampleRate;
615        mInFormat = format;
616        mInChannelMask = channelMask;
617
618        mInBuffSize = inBuffSize;
619    }
620
621    *buffSize = mInBuffSize;
622
623    return NO_ERROR;
624}
625
626sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor_l(audio_io_handle_t ioHandle)
627{
628    sp<AudioIoDescriptor> desc;
629    ssize_t index = mIoDescriptors.indexOfKey(ioHandle);
630    if (index >= 0) {
631        desc = mIoDescriptors.valueAt(index);
632    }
633    return desc;
634}
635
636sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor(audio_io_handle_t ioHandle)
637{
638    Mutex::Autolock _l(mLock);
639    return getIoDescriptor_l(ioHandle);
640}
641
642status_t AudioSystem::AudioFlingerClient::addAudioDeviceCallback(
643        const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
644{
645    Mutex::Autolock _l(mLock);
646    Vector < wp<AudioDeviceCallback> > callbacks;
647    ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(audioIo);
648    if (ioIndex >= 0) {
649        callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
650    }
651
652    for (size_t cbIndex = 0; cbIndex < callbacks.size(); cbIndex++) {
653        if (callbacks[cbIndex].unsafe_get() == callback.unsafe_get()) {
654            return INVALID_OPERATION;
655        }
656    }
657    callbacks.add(callback);
658
659    mAudioDeviceCallbacks.replaceValueFor(audioIo, callbacks);
660    return NO_ERROR;
661}
662
663status_t AudioSystem::AudioFlingerClient::removeAudioDeviceCallback(
664        const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
665{
666    Mutex::Autolock _l(mLock);
667    ssize_t ioIndex = mAudioDeviceCallbacks.indexOfKey(audioIo);
668    if (ioIndex < 0) {
669        return INVALID_OPERATION;
670    }
671    Vector < wp<AudioDeviceCallback> > callbacks = mAudioDeviceCallbacks.valueAt(ioIndex);
672
673    size_t cbIndex;
674    for (cbIndex = 0; cbIndex < callbacks.size(); cbIndex++) {
675        if (callbacks[cbIndex].unsafe_get() == callback.unsafe_get()) {
676            break;
677        }
678    }
679    if (cbIndex == callbacks.size()) {
680        return INVALID_OPERATION;
681    }
682    callbacks.removeAt(cbIndex);
683    if (callbacks.size() != 0) {
684        mAudioDeviceCallbacks.replaceValueFor(audioIo, callbacks);
685    } else {
686        mAudioDeviceCallbacks.removeItem(audioIo);
687    }
688    return NO_ERROR;
689}
690
691/* static */ void AudioSystem::setErrorCallback(audio_error_callback cb)
692{
693    Mutex::Autolock _l(gLock);
694    gAudioErrorCallback = cb;
695}
696
697/*static*/ void AudioSystem::setDynPolicyCallback(dynamic_policy_callback cb)
698{
699    Mutex::Autolock _l(gLock);
700    gDynPolicyCallback = cb;
701}
702
703/*static*/ void AudioSystem::setRecordConfigCallback(record_config_callback cb)
704{
705    Mutex::Autolock _l(gLock);
706    gRecordConfigCallback = cb;
707}
708
709// client singleton for AudioPolicyService binder interface
710// protected by gLockAPS
711sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
712sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
713
714
715// establish binder interface to AudioPolicy service
716const sp<IAudioPolicyService> AudioSystem::get_audio_policy_service()
717{
718    sp<IAudioPolicyService> ap;
719    sp<AudioPolicyServiceClient> apc;
720    {
721        Mutex::Autolock _l(gLockAPS);
722        if (gAudioPolicyService == 0) {
723            sp<IServiceManager> sm = defaultServiceManager();
724            sp<IBinder> binder;
725            do {
726                binder = sm->getService(String16("media.audio_policy"));
727                if (binder != 0)
728                    break;
729                ALOGW("AudioPolicyService not published, waiting...");
730                usleep(500000); // 0.5 s
731            } while (true);
732            if (gAudioPolicyServiceClient == NULL) {
733                gAudioPolicyServiceClient = new AudioPolicyServiceClient();
734            }
735            binder->linkToDeath(gAudioPolicyServiceClient);
736            gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
737            LOG_ALWAYS_FATAL_IF(gAudioPolicyService == 0);
738            apc = gAudioPolicyServiceClient;
739            // Make sure callbacks can be received by gAudioPolicyServiceClient
740            ProcessState::self()->startThreadPool();
741        }
742        ap = gAudioPolicyService;
743    }
744    if (apc != 0) {
745        ap->registerClient(apc);
746    }
747
748    return ap;
749}
750
751// ---------------------------------------------------------------------------
752
753status_t AudioSystem::setDeviceConnectionState(audio_devices_t device,
754                                               audio_policy_dev_state_t state,
755                                               const char *device_address,
756                                               const char *device_name)
757{
758    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
759    const char *address = "";
760    const char *name = "";
761
762    if (aps == 0) return PERMISSION_DENIED;
763
764    if (device_address != NULL) {
765        address = device_address;
766    }
767    if (device_name != NULL) {
768        name = device_name;
769    }
770    return aps->setDeviceConnectionState(device, state, address, name);
771}
772
773audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t device,
774                                                  const char *device_address)
775{
776    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
777    if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
778
779    return aps->getDeviceConnectionState(device, device_address);
780}
781
782status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device,
783                                               const char *device_address,
784                                               const char *device_name)
785{
786    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
787    const char *address = "";
788    const char *name = "";
789
790    if (aps == 0) return PERMISSION_DENIED;
791
792    if (device_address != NULL) {
793        address = device_address;
794    }
795    if (device_name != NULL) {
796        name = device_name;
797    }
798    return aps->handleDeviceConfigChange(device, address, name);
799}
800
801status_t AudioSystem::setPhoneState(audio_mode_t state)
802{
803    if (uint32_t(state) >= AUDIO_MODE_CNT) return BAD_VALUE;
804    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
805    if (aps == 0) return PERMISSION_DENIED;
806
807    return aps->setPhoneState(state);
808}
809
810status_t AudioSystem::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
811{
812    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
813    if (aps == 0) return PERMISSION_DENIED;
814    return aps->setForceUse(usage, config);
815}
816
817audio_policy_forced_cfg_t AudioSystem::getForceUse(audio_policy_force_use_t usage)
818{
819    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
820    if (aps == 0) return AUDIO_POLICY_FORCE_NONE;
821    return aps->getForceUse(usage);
822}
823
824
825audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream)
826{
827    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
828    if (aps == 0) return 0;
829    return aps->getOutput(stream);
830}
831
832status_t AudioSystem::getOutputForAttr(const audio_attributes_t *attr,
833                                        audio_io_handle_t *output,
834                                        audio_session_t session,
835                                        audio_stream_type_t *stream,
836                                        uid_t uid,
837                                        const audio_config_t *config,
838                                        audio_output_flags_t flags,
839                                        audio_port_handle_t *selectedDeviceId,
840                                        audio_port_handle_t *portId)
841{
842    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
843    if (aps == 0) return NO_INIT;
844    return aps->getOutputForAttr(attr, output, session, stream, uid,
845                                 config,
846                                 flags, selectedDeviceId, portId);
847}
848
849status_t AudioSystem::startOutput(audio_io_handle_t output,
850                                  audio_stream_type_t stream,
851                                  audio_session_t session)
852{
853    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
854    if (aps == 0) return PERMISSION_DENIED;
855    return aps->startOutput(output, stream, session);
856}
857
858status_t AudioSystem::stopOutput(audio_io_handle_t output,
859                                 audio_stream_type_t stream,
860                                 audio_session_t session)
861{
862    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
863    if (aps == 0) return PERMISSION_DENIED;
864    return aps->stopOutput(output, stream, session);
865}
866
867void AudioSystem::releaseOutput(audio_io_handle_t output,
868                                audio_stream_type_t stream,
869                                audio_session_t session)
870{
871    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
872    if (aps == 0) return;
873    aps->releaseOutput(output, stream, session);
874}
875
876status_t AudioSystem::getInputForAttr(const audio_attributes_t *attr,
877                                audio_io_handle_t *input,
878                                audio_session_t session,
879                                pid_t pid,
880                                uid_t uid,
881                                const audio_config_base_t *config,
882                                audio_input_flags_t flags,
883                                audio_port_handle_t *selectedDeviceId,
884                                audio_port_handle_t *portId)
885{
886    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
887    if (aps == 0) return NO_INIT;
888    return aps->getInputForAttr(
889            attr, input, session, pid, uid,
890            config, flags, selectedDeviceId, portId);
891}
892
893status_t AudioSystem::startInput(audio_io_handle_t input,
894                                 audio_session_t session)
895{
896    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
897    if (aps == 0) return PERMISSION_DENIED;
898    return aps->startInput(input, session);
899}
900
901status_t AudioSystem::stopInput(audio_io_handle_t input,
902                                audio_session_t session)
903{
904    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
905    if (aps == 0) return PERMISSION_DENIED;
906    return aps->stopInput(input, session);
907}
908
909void AudioSystem::releaseInput(audio_io_handle_t input,
910                               audio_session_t session)
911{
912    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
913    if (aps == 0) return;
914    aps->releaseInput(input, session);
915}
916
917status_t AudioSystem::initStreamVolume(audio_stream_type_t stream,
918                                    int indexMin,
919                                    int indexMax)
920{
921    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
922    if (aps == 0) return PERMISSION_DENIED;
923    return aps->initStreamVolume(stream, indexMin, indexMax);
924}
925
926status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
927                                           int index,
928                                           audio_devices_t device)
929{
930    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
931    if (aps == 0) return PERMISSION_DENIED;
932    return aps->setStreamVolumeIndex(stream, index, device);
933}
934
935status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
936                                           int *index,
937                                           audio_devices_t device)
938{
939    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
940    if (aps == 0) return PERMISSION_DENIED;
941    return aps->getStreamVolumeIndex(stream, index, device);
942}
943
944uint32_t AudioSystem::getStrategyForStream(audio_stream_type_t stream)
945{
946    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
947    if (aps == 0) return 0;
948    return aps->getStrategyForStream(stream);
949}
950
951audio_devices_t AudioSystem::getDevicesForStream(audio_stream_type_t stream)
952{
953    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
954    if (aps == 0) return AUDIO_DEVICE_NONE;
955    return aps->getDevicesForStream(stream);
956}
957
958audio_io_handle_t AudioSystem::getOutputForEffect(const effect_descriptor_t *desc)
959{
960    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
961    // FIXME change return type to status_t, and return PERMISSION_DENIED here
962    if (aps == 0) return AUDIO_IO_HANDLE_NONE;
963    return aps->getOutputForEffect(desc);
964}
965
966status_t AudioSystem::registerEffect(const effect_descriptor_t *desc,
967                                audio_io_handle_t io,
968                                uint32_t strategy,
969                                audio_session_t session,
970                                int id)
971{
972    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
973    if (aps == 0) return PERMISSION_DENIED;
974    return aps->registerEffect(desc, io, strategy, session, id);
975}
976
977status_t AudioSystem::unregisterEffect(int id)
978{
979    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
980    if (aps == 0) return PERMISSION_DENIED;
981    return aps->unregisterEffect(id);
982}
983
984status_t AudioSystem::setEffectEnabled(int id, bool enabled)
985{
986    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
987    if (aps == 0) return PERMISSION_DENIED;
988    return aps->setEffectEnabled(id, enabled);
989}
990
991status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs)
992{
993    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
994    if (aps == 0) return PERMISSION_DENIED;
995    if (state == NULL) return BAD_VALUE;
996    *state = aps->isStreamActive(stream, inPastMs);
997    return NO_ERROR;
998}
999
1000status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* state,
1001        uint32_t inPastMs)
1002{
1003    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1004    if (aps == 0) return PERMISSION_DENIED;
1005    if (state == NULL) return BAD_VALUE;
1006    *state = aps->isStreamActiveRemotely(stream, inPastMs);
1007    return NO_ERROR;
1008}
1009
1010status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state)
1011{
1012    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1013    if (aps == 0) return PERMISSION_DENIED;
1014    if (state == NULL) return BAD_VALUE;
1015    *state = aps->isSourceActive(stream);
1016    return NO_ERROR;
1017}
1018
1019uint32_t AudioSystem::getPrimaryOutputSamplingRate()
1020{
1021    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1022    if (af == 0) return 0;
1023    return af->getPrimaryOutputSamplingRate();
1024}
1025
1026size_t AudioSystem::getPrimaryOutputFrameCount()
1027{
1028    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1029    if (af == 0) return 0;
1030    return af->getPrimaryOutputFrameCount();
1031}
1032
1033status_t AudioSystem::setLowRamDevice(bool isLowRamDevice)
1034{
1035    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1036    if (af == 0) return PERMISSION_DENIED;
1037    return af->setLowRamDevice(isLowRamDevice);
1038}
1039
1040void AudioSystem::clearAudioConfigCache()
1041{
1042    // called by restoreTrack_l(), which needs new IAudioFlinger and IAudioPolicyService instances
1043    ALOGV("clearAudioConfigCache()");
1044    {
1045        Mutex::Autolock _l(gLock);
1046        if (gAudioFlingerClient != 0) {
1047            gAudioFlingerClient->clearIoCache();
1048        }
1049        gAudioFlinger.clear();
1050    }
1051    {
1052        Mutex::Autolock _l(gLockAPS);
1053        gAudioPolicyService.clear();
1054    }
1055}
1056
1057bool AudioSystem::isOffloadSupported(const audio_offload_info_t& info)
1058{
1059    ALOGV("isOffloadSupported()");
1060    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1061    if (aps == 0) return false;
1062    return aps->isOffloadSupported(info);
1063}
1064
1065status_t AudioSystem::listAudioPorts(audio_port_role_t role,
1066                                     audio_port_type_t type,
1067                                     unsigned int *num_ports,
1068                                     struct audio_port *ports,
1069                                     unsigned int *generation)
1070{
1071    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1072    if (aps == 0) return PERMISSION_DENIED;
1073    return aps->listAudioPorts(role, type, num_ports, ports, generation);
1074}
1075
1076status_t AudioSystem::getAudioPort(struct audio_port *port)
1077{
1078    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1079    if (aps == 0) return PERMISSION_DENIED;
1080    return aps->getAudioPort(port);
1081}
1082
1083status_t AudioSystem::createAudioPatch(const struct audio_patch *patch,
1084                                   audio_patch_handle_t *handle)
1085{
1086    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1087    if (aps == 0) return PERMISSION_DENIED;
1088    return aps->createAudioPatch(patch, handle);
1089}
1090
1091status_t AudioSystem::releaseAudioPatch(audio_patch_handle_t handle)
1092{
1093    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1094    if (aps == 0) return PERMISSION_DENIED;
1095    return aps->releaseAudioPatch(handle);
1096}
1097
1098status_t AudioSystem::listAudioPatches(unsigned int *num_patches,
1099                                  struct audio_patch *patches,
1100                                  unsigned int *generation)
1101{
1102    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1103    if (aps == 0) return PERMISSION_DENIED;
1104    return aps->listAudioPatches(num_patches, patches, generation);
1105}
1106
1107status_t AudioSystem::setAudioPortConfig(const struct audio_port_config *config)
1108{
1109    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1110    if (aps == 0) return PERMISSION_DENIED;
1111    return aps->setAudioPortConfig(config);
1112}
1113
1114status_t AudioSystem::addAudioPortCallback(const sp<AudioPortCallback>& callback)
1115{
1116    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1117    if (aps == 0) return PERMISSION_DENIED;
1118
1119    Mutex::Autolock _l(gLockAPS);
1120    if (gAudioPolicyServiceClient == 0) {
1121        return NO_INIT;
1122    }
1123    int ret = gAudioPolicyServiceClient->addAudioPortCallback(callback);
1124    if (ret == 1) {
1125        aps->setAudioPortCallbacksEnabled(true);
1126    }
1127    return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1128}
1129
1130/*static*/
1131status_t AudioSystem::removeAudioPortCallback(const sp<AudioPortCallback>& callback)
1132{
1133    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1134    if (aps == 0) return PERMISSION_DENIED;
1135
1136    Mutex::Autolock _l(gLockAPS);
1137    if (gAudioPolicyServiceClient == 0) {
1138        return NO_INIT;
1139    }
1140    int ret = gAudioPolicyServiceClient->removeAudioPortCallback(callback);
1141    if (ret == 0) {
1142        aps->setAudioPortCallbacksEnabled(false);
1143    }
1144    return (ret < 0) ? INVALID_OPERATION : NO_ERROR;
1145}
1146
1147status_t AudioSystem::addAudioDeviceCallback(
1148        const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
1149{
1150    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1151    if (afc == 0) {
1152        return NO_INIT;
1153    }
1154    status_t status = afc->addAudioDeviceCallback(callback, audioIo);
1155    if (status == NO_ERROR) {
1156        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1157        if (af != 0) {
1158            af->registerClient(afc);
1159        }
1160    }
1161    return status;
1162}
1163
1164status_t AudioSystem::removeAudioDeviceCallback(
1165        const wp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
1166{
1167    const sp<AudioFlingerClient> afc = getAudioFlingerClient();
1168    if (afc == 0) {
1169        return NO_INIT;
1170    }
1171    return afc->removeAudioDeviceCallback(callback, audioIo);
1172}
1173
1174audio_port_handle_t AudioSystem::getDeviceIdForIo(audio_io_handle_t audioIo)
1175{
1176    const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
1177    if (af == 0) return PERMISSION_DENIED;
1178    const sp<AudioIoDescriptor> desc = getIoDescriptor(audioIo);
1179    if (desc == 0) {
1180        return AUDIO_PORT_HANDLE_NONE;
1181    }
1182    return desc->getDeviceId();
1183}
1184
1185status_t AudioSystem::acquireSoundTriggerSession(audio_session_t *session,
1186                                       audio_io_handle_t *ioHandle,
1187                                       audio_devices_t *device)
1188{
1189    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1190    if (aps == 0) return PERMISSION_DENIED;
1191    return aps->acquireSoundTriggerSession(session, ioHandle, device);
1192}
1193
1194status_t AudioSystem::releaseSoundTriggerSession(audio_session_t session)
1195{
1196    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1197    if (aps == 0) return PERMISSION_DENIED;
1198    return aps->releaseSoundTriggerSession(session);
1199}
1200
1201audio_mode_t AudioSystem::getPhoneState()
1202{
1203    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1204    if (aps == 0) return AUDIO_MODE_INVALID;
1205    return aps->getPhoneState();
1206}
1207
1208status_t AudioSystem::registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration)
1209{
1210    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1211    if (aps == 0) return PERMISSION_DENIED;
1212    return aps->registerPolicyMixes(mixes, registration);
1213}
1214
1215status_t AudioSystem::startAudioSource(const struct audio_port_config *source,
1216                                       const audio_attributes_t *attributes,
1217                                       audio_patch_handle_t *handle)
1218{
1219    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1220    if (aps == 0) return PERMISSION_DENIED;
1221    return aps->startAudioSource(source, attributes, handle);
1222}
1223
1224status_t AudioSystem::stopAudioSource(audio_patch_handle_t handle)
1225{
1226    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1227    if (aps == 0) return PERMISSION_DENIED;
1228    return aps->stopAudioSource(handle);
1229}
1230
1231status_t AudioSystem::setMasterMono(bool mono)
1232{
1233    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1234    if (aps == 0) return PERMISSION_DENIED;
1235    return aps->setMasterMono(mono);
1236}
1237
1238status_t AudioSystem::getMasterMono(bool *mono)
1239{
1240    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1241    if (aps == 0) return PERMISSION_DENIED;
1242    return aps->getMasterMono(mono);
1243}
1244
1245float AudioSystem::getStreamVolumeDB(audio_stream_type_t stream, int index, audio_devices_t device)
1246{
1247    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
1248    if (aps == 0) return NAN;
1249    return aps->getStreamVolumeDB(stream, index, device);
1250}
1251
1252// ---------------------------------------------------------------------------
1253
1254int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback(
1255        const sp<AudioPortCallback>& callback)
1256{
1257    Mutex::Autolock _l(mLock);
1258    for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1259        if (mAudioPortCallbacks[i] == callback) {
1260            return -1;
1261        }
1262    }
1263    mAudioPortCallbacks.add(callback);
1264    return mAudioPortCallbacks.size();
1265}
1266
1267int AudioSystem::AudioPolicyServiceClient::removeAudioPortCallback(
1268        const sp<AudioPortCallback>& callback)
1269{
1270    Mutex::Autolock _l(mLock);
1271    size_t i;
1272    for (i = 0; i < mAudioPortCallbacks.size(); i++) {
1273        if (mAudioPortCallbacks[i] == callback) {
1274            break;
1275        }
1276    }
1277    if (i == mAudioPortCallbacks.size()) {
1278        return -1;
1279    }
1280    mAudioPortCallbacks.removeAt(i);
1281    return mAudioPortCallbacks.size();
1282}
1283
1284
1285void AudioSystem::AudioPolicyServiceClient::onAudioPortListUpdate()
1286{
1287    Mutex::Autolock _l(mLock);
1288    for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1289        mAudioPortCallbacks[i]->onAudioPortListUpdate();
1290    }
1291}
1292
1293void AudioSystem::AudioPolicyServiceClient::onAudioPatchListUpdate()
1294{
1295    Mutex::Autolock _l(mLock);
1296    for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1297        mAudioPortCallbacks[i]->onAudioPatchListUpdate();
1298    }
1299}
1300
1301void AudioSystem::AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(
1302        String8 regId, int32_t state)
1303{
1304    ALOGV("AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate(%s, %d)", regId.string(), state);
1305    dynamic_policy_callback cb = NULL;
1306    {
1307        Mutex::Autolock _l(AudioSystem::gLock);
1308        cb = gDynPolicyCallback;
1309    }
1310
1311    if (cb != NULL) {
1312        cb(DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE, regId, state);
1313    }
1314}
1315
1316void AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate(
1317        int event, const record_client_info_t *clientInfo,
1318        const audio_config_base_t *clientConfig, const audio_config_base_t *deviceConfig,
1319        audio_patch_handle_t patchHandle) {
1320    record_config_callback cb = NULL;
1321    {
1322        Mutex::Autolock _l(AudioSystem::gLock);
1323        cb = gRecordConfigCallback;
1324    }
1325
1326    if (cb != NULL) {
1327        cb(event, clientInfo, clientConfig, deviceConfig, patchHandle);
1328    }
1329}
1330
1331void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who __unused)
1332{
1333    {
1334        Mutex::Autolock _l(mLock);
1335        for (size_t i = 0; i < mAudioPortCallbacks.size(); i++) {
1336            mAudioPortCallbacks[i]->onServiceDied();
1337        }
1338    }
1339    {
1340        Mutex::Autolock _l(gLockAPS);
1341        AudioSystem::gAudioPolicyService.clear();
1342    }
1343
1344    ALOGW("AudioPolicyService server died!");
1345}
1346
1347} // namespace android
1348