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