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