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