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