AudioPolicyManagerBase.cpp revision 582a15744be109fb630db7dbd1d1bdf22ff44f12
1/*
2 * Copyright (C) 2009 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 "AudioPolicyManagerBase"
18//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20#include <hardware_legacy/AudioPolicyManagerBase.h>
21#include <hardware/audio_effect.h>
22#include <math.h>
23
24namespace android_audio_legacy {
25
26// ----------------------------------------------------------------------------
27// AudioPolicyInterface implementation
28// ----------------------------------------------------------------------------
29
30
31status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
32                                                  AudioSystem::device_connection_state state,
33                                                  const char *device_address)
34{
35
36    LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
37
38    // connect/disconnect only 1 device at a time
39    if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
40
41    if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
42        LOGE("setDeviceConnectionState() invalid address: %s", device_address);
43        return BAD_VALUE;
44    }
45
46    // handle output devices
47    if (AudioSystem::isOutputDevice(device)) {
48
49#ifndef WITH_A2DP
50        if (AudioSystem::isA2dpDevice(device)) {
51            LOGE("setDeviceConnectionState() invalid device: %x", device);
52            return BAD_VALUE;
53        }
54#endif
55
56        switch (state)
57        {
58        // handle output device connection
59        case AudioSystem::DEVICE_STATE_AVAILABLE:
60            if (mAvailableOutputDevices & device) {
61                LOGW("setDeviceConnectionState() device already connected: %x", device);
62                return INVALID_OPERATION;
63            }
64            LOGV("setDeviceConnectionState() connecting device %x", device);
65
66            // register new device as available
67            mAvailableOutputDevices |= device;
68
69#ifdef WITH_A2DP
70            // handle A2DP device connection
71            if (AudioSystem::isA2dpDevice(device)) {
72                status_t status = handleA2dpConnection(device, device_address);
73                if (status != NO_ERROR) {
74                    mAvailableOutputDevices &= ~device;
75                    return status;
76                }
77            } else
78#endif
79            {
80                if (AudioSystem::isBluetoothScoDevice(device)) {
81                    LOGV("setDeviceConnectionState() BT SCO  device, address %s", device_address);
82                    // keep track of SCO device address
83                    mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
84                }
85            }
86            break;
87        // handle output device disconnection
88        case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
89            if (!(mAvailableOutputDevices & device)) {
90                LOGW("setDeviceConnectionState() device not connected: %x", device);
91                return INVALID_OPERATION;
92            }
93
94
95            LOGV("setDeviceConnectionState() disconnecting device %x", device);
96            // remove device from available output devices
97            mAvailableOutputDevices &= ~device;
98
99#ifdef WITH_A2DP
100            // handle A2DP device disconnection
101            if (AudioSystem::isA2dpDevice(device)) {
102                status_t status = handleA2dpDisconnection(device, device_address);
103                if (status != NO_ERROR) {
104                    mAvailableOutputDevices |= device;
105                    return status;
106                }
107            } else
108#endif
109            {
110                if (AudioSystem::isBluetoothScoDevice(device)) {
111                    mScoDeviceAddress = "";
112                }
113            }
114            } break;
115
116        default:
117            LOGE("setDeviceConnectionState() invalid state: %x", state);
118            return BAD_VALUE;
119        }
120
121        // request routing change if necessary
122        uint32_t newDevice = getNewDevice(mHardwareOutput, false);
123#ifdef WITH_A2DP
124        checkA2dpSuspend();
125        checkOutputForAllStrategies();
126        // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
127        if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
128            closeA2dpOutputs();
129        }
130#endif
131        updateDeviceForStrategy();
132        setOutputDevice(mHardwareOutput, newDevice);
133
134        if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
135            device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
136        } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
137                   device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
138                   device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
139            device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
140        } else {
141            return NO_ERROR;
142        }
143    }
144    // handle input devices
145    if (AudioSystem::isInputDevice(device)) {
146
147        switch (state)
148        {
149        // handle input device connection
150        case AudioSystem::DEVICE_STATE_AVAILABLE: {
151            if (mAvailableInputDevices & device) {
152                LOGW("setDeviceConnectionState() device already connected: %d", device);
153                return INVALID_OPERATION;
154            }
155            mAvailableInputDevices |= device;
156            }
157            break;
158
159        // handle input device disconnection
160        case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
161            if (!(mAvailableInputDevices & device)) {
162                LOGW("setDeviceConnectionState() device not connected: %d", device);
163                return INVALID_OPERATION;
164            }
165            mAvailableInputDevices &= ~device;
166            } break;
167
168        default:
169            LOGE("setDeviceConnectionState() invalid state: %x", state);
170            return BAD_VALUE;
171        }
172
173        audio_io_handle_t activeInput = getActiveInput();
174        if (activeInput != 0) {
175            AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
176            uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
177            if (newDevice != inputDesc->mDevice) {
178                LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
179                        inputDesc->mDevice, newDevice, activeInput);
180                inputDesc->mDevice = newDevice;
181                AudioParameter param = AudioParameter();
182                param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
183                mpClientInterface->setParameters(activeInput, param.toString());
184            }
185        }
186
187        return NO_ERROR;
188    }
189
190    LOGW("setDeviceConnectionState() invalid device: %x", device);
191    return BAD_VALUE;
192}
193
194AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
195                                                  const char *device_address)
196{
197    AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
198    String8 address = String8(device_address);
199    if (AudioSystem::isOutputDevice(device)) {
200        if (device & mAvailableOutputDevices) {
201#ifdef WITH_A2DP
202            if (AudioSystem::isA2dpDevice(device) &&
203                address != "" && mA2dpDeviceAddress != address) {
204                return state;
205            }
206#endif
207            if (AudioSystem::isBluetoothScoDevice(device) &&
208                address != "" && mScoDeviceAddress != address) {
209                return state;
210            }
211            state = AudioSystem::DEVICE_STATE_AVAILABLE;
212        }
213    } else if (AudioSystem::isInputDevice(device)) {
214        if (device & mAvailableInputDevices) {
215            state = AudioSystem::DEVICE_STATE_AVAILABLE;
216        }
217    }
218
219    return state;
220}
221
222void AudioPolicyManagerBase::setPhoneState(int state)
223{
224    LOGV("setPhoneState() state %d", state);
225    uint32_t newDevice = 0;
226    if (state < 0 || state >= AudioSystem::NUM_MODES) {
227        LOGW("setPhoneState() invalid state %d", state);
228        return;
229    }
230
231    if (state == mPhoneState ) {
232        LOGW("setPhoneState() setting same state %d", state);
233        return;
234    }
235
236    // if leaving call state, handle special case of active streams
237    // pertaining to sonification strategy see handleIncallSonification()
238    if (isInCall()) {
239        LOGV("setPhoneState() in call state management: new state is %d", state);
240        for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
241            handleIncallSonification(stream, false, true);
242        }
243    }
244
245    // store previous phone state for management of sonification strategy below
246    int oldState = mPhoneState;
247    mPhoneState = state;
248    bool force = false;
249
250    // are we entering or starting a call
251    if (!isStateInCall(oldState) && isStateInCall(state)) {
252        LOGV("  Entering call in setPhoneState()");
253        // force routing command to audio hardware when starting a call
254        // even if no device change is needed
255        force = true;
256    } else if (isStateInCall(oldState) && !isStateInCall(state)) {
257        LOGV("  Exiting call in setPhoneState()");
258        // force routing command to audio hardware when exiting a call
259        // even if no device change is needed
260        force = true;
261    } else if (isStateInCall(state) && (state != oldState)) {
262        LOGV("  Switching between telephony and VoIP in setPhoneState()");
263        // force routing command to audio hardware when switching between telephony and VoIP
264        // even if no device change is needed
265        force = true;
266    }
267
268    // check for device and output changes triggered by new phone state
269    newDevice = getNewDevice(mHardwareOutput, false);
270#ifdef WITH_A2DP
271    checkA2dpSuspend();
272    checkOutputForAllStrategies();
273#endif
274    updateDeviceForStrategy();
275
276    AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
277
278    // force routing command to audio hardware when ending call
279    // even if no device change is needed
280    if (isStateInCall(oldState) && newDevice == 0) {
281        newDevice = hwOutputDesc->device();
282    }
283
284    // when changing from ring tone to in call mode, mute the ringing tone
285    // immediately and delay the route change to avoid sending the ring tone
286    // tail into the earpiece or headset.
287    int delayMs = 0;
288    if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
289        // delay the device change command by twice the output latency to have some margin
290        // and be sure that audio buffers not yet affected by the mute are out when
291        // we actually apply the route change
292        delayMs = hwOutputDesc->mLatency*2;
293        setStreamMute(AudioSystem::RING, true, mHardwareOutput);
294    }
295
296    // change routing is necessary
297    setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
298
299    // if entering in call state, handle special case of active streams
300    // pertaining to sonification strategy see handleIncallSonification()
301    if (isStateInCall(state)) {
302        LOGV("setPhoneState() in call state management: new state is %d", state);
303        // unmute the ringing tone after a sufficient delay if it was muted before
304        // setting output device above
305        if (oldState == AudioSystem::MODE_RINGTONE) {
306            setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS);
307        }
308        for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
309            handleIncallSonification(stream, true, true);
310        }
311    }
312
313    // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
314    if (state == AudioSystem::MODE_RINGTONE &&
315        isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
316        mLimitRingtoneVolume = true;
317    } else {
318        mLimitRingtoneVolume = false;
319    }
320}
321
322void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
323{
324    LOGV("setRingerMode() mode %x, mask %x", mode, mask);
325
326    mRingerMode = mode;
327}
328
329void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
330{
331    LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
332
333    bool forceVolumeReeval = false;
334    switch(usage) {
335    case AudioSystem::FOR_COMMUNICATION:
336        if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
337            config != AudioSystem::FORCE_NONE) {
338            LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
339            return;
340        }
341        forceVolumeReeval = true;
342        mForceUse[usage] = config;
343        break;
344    case AudioSystem::FOR_MEDIA:
345        if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
346            config != AudioSystem::FORCE_WIRED_ACCESSORY &&
347            config != AudioSystem::FORCE_ANALOG_DOCK &&
348            config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
349            LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
350            return;
351        }
352        mForceUse[usage] = config;
353        break;
354    case AudioSystem::FOR_RECORD:
355        if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
356            config != AudioSystem::FORCE_NONE) {
357            LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
358            return;
359        }
360        mForceUse[usage] = config;
361        break;
362    case AudioSystem::FOR_DOCK:
363        if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
364            config != AudioSystem::FORCE_BT_DESK_DOCK &&
365            config != AudioSystem::FORCE_WIRED_ACCESSORY &&
366            config != AudioSystem::FORCE_ANALOG_DOCK &&
367            config != AudioSystem::FORCE_DIGITAL_DOCK) {
368            LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
369        }
370        forceVolumeReeval = true;
371        mForceUse[usage] = config;
372        break;
373    default:
374        LOGW("setForceUse() invalid usage %d", usage);
375        break;
376    }
377
378    // check for device and output changes triggered by new phone state
379    uint32_t newDevice = getNewDevice(mHardwareOutput, false);
380#ifdef WITH_A2DP
381    checkA2dpSuspend();
382    checkOutputForAllStrategies();
383#endif
384    updateDeviceForStrategy();
385    setOutputDevice(mHardwareOutput, newDevice);
386    if (forceVolumeReeval) {
387        applyStreamVolumes(mHardwareOutput, newDevice, 0, true);
388    }
389
390    audio_io_handle_t activeInput = getActiveInput();
391    if (activeInput != 0) {
392        AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
393        newDevice = getDeviceForInputSource(inputDesc->mInputSource);
394        if (newDevice != inputDesc->mDevice) {
395            LOGV("setForceUse() changing device from %x to %x for input %d",
396                    inputDesc->mDevice, newDevice, activeInput);
397            inputDesc->mDevice = newDevice;
398            AudioParameter param = AudioParameter();
399            param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
400            mpClientInterface->setParameters(activeInput, param.toString());
401        }
402    }
403
404}
405
406AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
407{
408    return mForceUse[usage];
409}
410
411void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
412{
413    LOGV("setSystemProperty() property %s, value %s", property, value);
414    if (strcmp(property, "ro.camera.sound.forced") == 0) {
415        if (atoi(value)) {
416            LOGV("ENFORCED_AUDIBLE cannot be muted");
417            mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
418        } else {
419            LOGV("ENFORCED_AUDIBLE can be muted");
420            mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
421        }
422    }
423}
424
425audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
426                                    uint32_t samplingRate,
427                                    uint32_t format,
428                                    uint32_t channels,
429                                    AudioSystem::output_flags flags)
430{
431    audio_io_handle_t output = 0;
432    uint32_t latency = 0;
433    routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
434    uint32_t device = getDeviceForStrategy(strategy);
435    LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
436
437#ifdef AUDIO_POLICY_TEST
438    if (mCurOutput != 0) {
439        LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
440                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
441
442        if (mTestOutputs[mCurOutput] == 0) {
443            LOGV("getOutput() opening test output");
444            AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
445            outputDesc->mDevice = mTestDevice;
446            outputDesc->mSamplingRate = mTestSamplingRate;
447            outputDesc->mFormat = mTestFormat;
448            outputDesc->mChannels = mTestChannels;
449            outputDesc->mLatency = mTestLatencyMs;
450            outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
451            outputDesc->mRefCount[stream] = 0;
452            mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
453                                            &outputDesc->mSamplingRate,
454                                            &outputDesc->mFormat,
455                                            &outputDesc->mChannels,
456                                            &outputDesc->mLatency,
457                                            outputDesc->mFlags);
458            if (mTestOutputs[mCurOutput]) {
459                AudioParameter outputCmd = AudioParameter();
460                outputCmd.addInt(String8("set_id"),mCurOutput);
461                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
462                addOutput(mTestOutputs[mCurOutput], outputDesc);
463            }
464        }
465        return mTestOutputs[mCurOutput];
466    }
467#endif //AUDIO_POLICY_TEST
468
469    // open a direct output if required by specified parameters
470    if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
471
472        LOGV("getOutput() opening direct output device %x", device);
473        AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
474        outputDesc->mDevice = device;
475        outputDesc->mSamplingRate = samplingRate;
476        outputDesc->mFormat = format;
477        outputDesc->mChannels = channels;
478        outputDesc->mLatency = 0;
479        outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
480        outputDesc->mRefCount[stream] = 0;
481        outputDesc->mStopTime[stream] = 0;
482        output = mpClientInterface->openOutput(&outputDesc->mDevice,
483                                        &outputDesc->mSamplingRate,
484                                        &outputDesc->mFormat,
485                                        &outputDesc->mChannels,
486                                        &outputDesc->mLatency,
487                                        outputDesc->mFlags);
488
489        // only accept an output with the requeted parameters
490        if (output == 0 ||
491            (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
492            (format != 0 && format != outputDesc->mFormat) ||
493            (channels != 0 && channels != outputDesc->mChannels)) {
494            LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
495                    samplingRate, format, channels);
496            if (output != 0) {
497                mpClientInterface->closeOutput(output);
498            }
499            delete outputDesc;
500            return 0;
501        }
502        addOutput(output, outputDesc);
503        return output;
504    }
505
506    if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
507        channels != AudioSystem::CHANNEL_OUT_STEREO) {
508        return 0;
509    }
510    // open a non direct output
511
512    // get which output is suitable for the specified stream. The actual routing change will happen
513    // when startOutput() will be called
514    uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
515    if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
516#ifdef WITH_A2DP
517        if (a2dpUsedForSonification() && a2dpDevice != 0) {
518            // if playing on 2 devices among which one is A2DP, use duplicated output
519            LOGV("getOutput() using duplicated output");
520            LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
521            output = mDuplicatedOutput;
522        } else
523#endif
524        {
525            // if playing on 2 devices among which none is A2DP, use hardware output
526            output = mHardwareOutput;
527        }
528        LOGV("getOutput() using output %d for 2 devices %x", output, device);
529    } else {
530#ifdef WITH_A2DP
531        if (a2dpDevice != 0) {
532            // if playing on A2DP device, use a2dp output
533            LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
534            output = mA2dpOutput;
535        } else
536#endif
537        {
538            // if playing on not A2DP device, use hardware output
539            output = mHardwareOutput;
540        }
541    }
542
543
544    LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
545                stream, samplingRate, format, channels, flags);
546
547    return output;
548}
549
550status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
551                                             AudioSystem::stream_type stream,
552                                             int session)
553{
554    LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
555    ssize_t index = mOutputs.indexOfKey(output);
556    if (index < 0) {
557        LOGW("startOutput() unknow output %d", output);
558        return BAD_VALUE;
559    }
560
561    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
562    routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
563
564#ifdef WITH_A2DP
565    if (mA2dpOutput != 0  && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
566        setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
567    }
568#endif
569
570    // incremenent usage count for this stream on the requested output:
571    // NOTE that the usage count is the same for duplicated output and hardware output which is
572    // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
573    outputDesc->changeRefCount(stream, 1);
574
575    setOutputDevice(output, getNewDevice(output));
576
577    // handle special case for sonification while in call
578    if (isInCall()) {
579        handleIncallSonification(stream, true, false);
580    }
581
582    // apply volume rules for current stream and device if necessary
583    checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
584
585    return NO_ERROR;
586}
587
588status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
589                                            AudioSystem::stream_type stream,
590                                            int session)
591{
592    LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
593    ssize_t index = mOutputs.indexOfKey(output);
594    if (index < 0) {
595        LOGW("stopOutput() unknow output %d", output);
596        return BAD_VALUE;
597    }
598
599    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
600    routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
601
602    // handle special case for sonification while in call
603    if (isInCall()) {
604        handleIncallSonification(stream, false, false);
605    }
606
607    if (outputDesc->mRefCount[stream] > 0) {
608        // decrement usage count of this stream on the output
609        outputDesc->changeRefCount(stream, -1);
610        // store time at which the stream was stopped - see isStreamActive()
611        outputDesc->mStopTime[stream] = systemTime();
612
613        setOutputDevice(output, getNewDevice(output), false, outputDesc->mLatency*2);
614
615#ifdef WITH_A2DP
616        if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
617                strategy == STRATEGY_SONIFICATION) {
618            setStrategyMute(STRATEGY_MEDIA,
619                            false,
620                            mA2dpOutput,
621                            mOutputs.valueFor(mHardwareOutput)->mLatency*2);
622        }
623#endif
624        if (output != mHardwareOutput) {
625            setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
626        }
627        return NO_ERROR;
628    } else {
629        LOGW("stopOutput() refcount is already 0 for output %d", output);
630        return INVALID_OPERATION;
631    }
632}
633
634void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
635{
636    LOGV("releaseOutput() %d", output);
637    ssize_t index = mOutputs.indexOfKey(output);
638    if (index < 0) {
639        LOGW("releaseOutput() releasing unknown output %d", output);
640        return;
641    }
642
643#ifdef AUDIO_POLICY_TEST
644    int testIndex = testOutputIndex(output);
645    if (testIndex != 0) {
646        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
647        if (outputDesc->refCount() == 0) {
648            mpClientInterface->closeOutput(output);
649            delete mOutputs.valueAt(index);
650            mOutputs.removeItem(output);
651            mTestOutputs[testIndex] = 0;
652        }
653        return;
654    }
655#endif //AUDIO_POLICY_TEST
656
657    if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
658        mpClientInterface->closeOutput(output);
659        delete mOutputs.valueAt(index);
660        mOutputs.removeItem(output);
661    }
662}
663
664audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
665                                    uint32_t samplingRate,
666                                    uint32_t format,
667                                    uint32_t channels,
668                                    AudioSystem::audio_in_acoustics acoustics)
669{
670    audio_io_handle_t input = 0;
671    uint32_t device = getDeviceForInputSource(inputSource);
672
673    LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
674
675    if (device == 0) {
676        return 0;
677    }
678
679    // adapt channel selection to input source
680    switch(inputSource) {
681    case AUDIO_SOURCE_VOICE_UPLINK:
682        channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
683        break;
684    case AUDIO_SOURCE_VOICE_DOWNLINK:
685        channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
686        break;
687    case AUDIO_SOURCE_VOICE_CALL:
688        channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
689        break;
690    default:
691        break;
692    }
693
694    AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
695
696    inputDesc->mInputSource = inputSource;
697    inputDesc->mDevice = device;
698    inputDesc->mSamplingRate = samplingRate;
699    inputDesc->mFormat = format;
700    inputDesc->mChannels = channels;
701    inputDesc->mAcoustics = acoustics;
702    inputDesc->mRefCount = 0;
703    input = mpClientInterface->openInput(&inputDesc->mDevice,
704                                    &inputDesc->mSamplingRate,
705                                    &inputDesc->mFormat,
706                                    &inputDesc->mChannels,
707                                    inputDesc->mAcoustics);
708
709    // only accept input with the exact requested set of parameters
710    if (input == 0 ||
711        (samplingRate != inputDesc->mSamplingRate) ||
712        (format != inputDesc->mFormat) ||
713        (channels != inputDesc->mChannels)) {
714        LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
715                samplingRate, format, channels);
716        if (input != 0) {
717            mpClientInterface->closeInput(input);
718        }
719        delete inputDesc;
720        return 0;
721    }
722    mInputs.add(input, inputDesc);
723    return input;
724}
725
726status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
727{
728    LOGV("startInput() input %d", input);
729    ssize_t index = mInputs.indexOfKey(input);
730    if (index < 0) {
731        LOGW("startInput() unknow input %d", input);
732        return BAD_VALUE;
733    }
734    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
735
736#ifdef AUDIO_POLICY_TEST
737    if (mTestInput == 0)
738#endif //AUDIO_POLICY_TEST
739    {
740        // refuse 2 active AudioRecord clients at the same time
741        if (getActiveInput() != 0) {
742            LOGW("startInput() input %d failed: other input already started", input);
743            return INVALID_OPERATION;
744        }
745    }
746
747    AudioParameter param = AudioParameter();
748    param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
749
750    param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
751    LOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
752
753    mpClientInterface->setParameters(input, param.toString());
754
755    inputDesc->mRefCount = 1;
756    return NO_ERROR;
757}
758
759status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
760{
761    LOGV("stopInput() input %d", input);
762    ssize_t index = mInputs.indexOfKey(input);
763    if (index < 0) {
764        LOGW("stopInput() unknow input %d", input);
765        return BAD_VALUE;
766    }
767    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
768
769    if (inputDesc->mRefCount == 0) {
770        LOGW("stopInput() input %d already stopped", input);
771        return INVALID_OPERATION;
772    } else {
773        AudioParameter param = AudioParameter();
774        param.addInt(String8(AudioParameter::keyRouting), 0);
775        mpClientInterface->setParameters(input, param.toString());
776        inputDesc->mRefCount = 0;
777        return NO_ERROR;
778    }
779}
780
781void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
782{
783    LOGV("releaseInput() %d", input);
784    ssize_t index = mInputs.indexOfKey(input);
785    if (index < 0) {
786        LOGW("releaseInput() releasing unknown input %d", input);
787        return;
788    }
789    mpClientInterface->closeInput(input);
790    delete mInputs.valueAt(index);
791    mInputs.removeItem(input);
792    LOGV("releaseInput() exit");
793}
794
795void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
796                                            int indexMin,
797                                            int indexMax)
798{
799    LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
800    if (indexMin < 0 || indexMin >= indexMax) {
801        LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
802        return;
803    }
804    mStreams[stream].mIndexMin = indexMin;
805    mStreams[stream].mIndexMax = indexMax;
806}
807
808status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
809{
810
811    if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
812        return BAD_VALUE;
813    }
814
815    // Force max volume if stream cannot be muted
816    if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
817
818    LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
819    mStreams[stream].mIndexCur = index;
820
821    // compute and apply stream volume on all outputs according to connected device
822    status_t status = NO_ERROR;
823    for (size_t i = 0; i < mOutputs.size(); i++) {
824        status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
825        if (volStatus != NO_ERROR) {
826            status = volStatus;
827        }
828    }
829    return status;
830}
831
832status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
833{
834    if (index == 0) {
835        return BAD_VALUE;
836    }
837    LOGV("getStreamVolumeIndex() stream %d", stream);
838    *index =  mStreams[stream].mIndexCur;
839    return NO_ERROR;
840}
841
842audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
843{
844    LOGV("getOutputForEffect()");
845    // apply simple rule where global effects are attached to the same output as MUSIC streams
846    return getOutput(AudioSystem::MUSIC);
847}
848
849status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
850                                audio_io_handle_t io,
851                                uint32_t strategy,
852                                int session,
853                                int id)
854{
855    ssize_t index = mOutputs.indexOfKey(io);
856    if (index < 0) {
857        index = mInputs.indexOfKey(io);
858        if (index < 0) {
859            LOGW("registerEffect() unknown io %d", io);
860            return INVALID_OPERATION;
861        }
862    }
863
864    if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
865        LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
866                desc->name, desc->memoryUsage);
867        return INVALID_OPERATION;
868    }
869    mTotalEffectsMemory += desc->memoryUsage;
870    LOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
871            desc->name, io, strategy, session, id);
872    LOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
873
874    EffectDescriptor *pDesc = new EffectDescriptor();
875    memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
876    pDesc->mIo = io;
877    pDesc->mStrategy = (routing_strategy)strategy;
878    pDesc->mSession = session;
879    pDesc->mEnabled = false;
880
881    mEffects.add(id, pDesc);
882
883    return NO_ERROR;
884}
885
886status_t AudioPolicyManagerBase::unregisterEffect(int id)
887{
888    ssize_t index = mEffects.indexOfKey(id);
889    if (index < 0) {
890        LOGW("unregisterEffect() unknown effect ID %d", id);
891        return INVALID_OPERATION;
892    }
893
894    EffectDescriptor *pDesc = mEffects.valueAt(index);
895
896    setEffectEnabled(pDesc, false);
897
898    if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
899        LOGW("unregisterEffect() memory %d too big for total %d",
900                pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
901        pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
902    }
903    mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
904    LOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
905            pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
906
907    mEffects.removeItem(id);
908    delete pDesc;
909
910    return NO_ERROR;
911}
912
913status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
914{
915    ssize_t index = mEffects.indexOfKey(id);
916    if (index < 0) {
917        LOGW("unregisterEffect() unknown effect ID %d", id);
918        return INVALID_OPERATION;
919    }
920
921    return setEffectEnabled(mEffects.valueAt(index), enabled);
922}
923
924status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
925{
926    if (enabled == pDesc->mEnabled) {
927        LOGV("setEffectEnabled(%s) effect already %s",
928             enabled?"true":"false", enabled?"enabled":"disabled");
929        return INVALID_OPERATION;
930    }
931
932    if (enabled) {
933        if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
934            LOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
935                 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
936            return INVALID_OPERATION;
937        }
938        mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
939        LOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
940    } else {
941        if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
942            LOGW("setEffectEnabled(false) CPU load %d too high for total %d",
943                    pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
944            pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
945        }
946        mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
947        LOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
948    }
949    pDesc->mEnabled = enabled;
950    return NO_ERROR;
951}
952
953bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
954{
955    nsecs_t sysTime = systemTime();
956    for (size_t i = 0; i < mOutputs.size(); i++) {
957        if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
958            ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
959            return true;
960        }
961    }
962    return false;
963}
964
965
966status_t AudioPolicyManagerBase::dump(int fd)
967{
968    const size_t SIZE = 256;
969    char buffer[SIZE];
970    String8 result;
971
972    snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
973    result.append(buffer);
974    snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
975    result.append(buffer);
976#ifdef WITH_A2DP
977    snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
978    result.append(buffer);
979    snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
980    result.append(buffer);
981    snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
982    result.append(buffer);
983#endif
984    snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
985    result.append(buffer);
986    snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
987    result.append(buffer);
988    snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
989    result.append(buffer);
990    snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
991    result.append(buffer);
992    snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
993    result.append(buffer);
994    snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
995    result.append(buffer);
996    snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
997    result.append(buffer);
998    snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
999    result.append(buffer);
1000    snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1001    result.append(buffer);
1002    write(fd, result.string(), result.size());
1003
1004    snprintf(buffer, SIZE, "\nOutputs dump:\n");
1005    write(fd, buffer, strlen(buffer));
1006    for (size_t i = 0; i < mOutputs.size(); i++) {
1007        snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1008        write(fd, buffer, strlen(buffer));
1009        mOutputs.valueAt(i)->dump(fd);
1010    }
1011
1012    snprintf(buffer, SIZE, "\nInputs dump:\n");
1013    write(fd, buffer, strlen(buffer));
1014    for (size_t i = 0; i < mInputs.size(); i++) {
1015        snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1016        write(fd, buffer, strlen(buffer));
1017        mInputs.valueAt(i)->dump(fd);
1018    }
1019
1020    snprintf(buffer, SIZE, "\nStreams dump:\n");
1021    write(fd, buffer, strlen(buffer));
1022    snprintf(buffer, SIZE, " Stream  Index Min  Index Max  Index Cur  Can be muted\n");
1023    write(fd, buffer, strlen(buffer));
1024    for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1025        snprintf(buffer, SIZE, " %02d", i);
1026        mStreams[i].dump(buffer + 3, SIZE);
1027        write(fd, buffer, strlen(buffer));
1028    }
1029
1030    snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1031            (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1032    write(fd, buffer, strlen(buffer));
1033
1034    snprintf(buffer, SIZE, "Registered effects:\n");
1035    write(fd, buffer, strlen(buffer));
1036    for (size_t i = 0; i < mEffects.size(); i++) {
1037        snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1038        write(fd, buffer, strlen(buffer));
1039        mEffects.valueAt(i)->dump(fd);
1040    }
1041
1042
1043    return NO_ERROR;
1044}
1045
1046// ----------------------------------------------------------------------------
1047// AudioPolicyManagerBase
1048// ----------------------------------------------------------------------------
1049
1050AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1051    :
1052#ifdef AUDIO_POLICY_TEST
1053    Thread(false),
1054#endif //AUDIO_POLICY_TEST
1055    mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
1056    mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1057    mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1058    mA2dpSuspended(false)
1059{
1060    mpClientInterface = clientInterface;
1061
1062    for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1063        mForceUse[i] = AudioSystem::FORCE_NONE;
1064    }
1065
1066    initializeVolumeCurves();
1067
1068    // devices available by default are speaker, ear piece and microphone
1069    mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1070                        AudioSystem::DEVICE_OUT_SPEAKER;
1071    mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1072
1073#ifdef WITH_A2DP
1074    mA2dpOutput = 0;
1075    mDuplicatedOutput = 0;
1076    mA2dpDeviceAddress = String8("");
1077#endif
1078    mScoDeviceAddress = String8("");
1079
1080    // open hardware output
1081    AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1082    outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1083    mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1084                                    &outputDesc->mSamplingRate,
1085                                    &outputDesc->mFormat,
1086                                    &outputDesc->mChannels,
1087                                    &outputDesc->mLatency,
1088                                    outputDesc->mFlags);
1089
1090    if (mHardwareOutput == 0) {
1091        LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1092                outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1093    } else {
1094        addOutput(mHardwareOutput, outputDesc);
1095        setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
1096        //TODO: configure audio effect output stage here
1097    }
1098
1099    updateDeviceForStrategy();
1100#ifdef AUDIO_POLICY_TEST
1101    if (mHardwareOutput != 0) {
1102        AudioParameter outputCmd = AudioParameter();
1103        outputCmd.addInt(String8("set_id"), 0);
1104        mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1105
1106        mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1107        mTestSamplingRate = 44100;
1108        mTestFormat = AudioSystem::PCM_16_BIT;
1109        mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
1110        mTestLatencyMs = 0;
1111        mCurOutput = 0;
1112        mDirectOutput = false;
1113        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1114            mTestOutputs[i] = 0;
1115        }
1116
1117        const size_t SIZE = 256;
1118        char buffer[SIZE];
1119        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1120        run(buffer, ANDROID_PRIORITY_AUDIO);
1121    }
1122#endif //AUDIO_POLICY_TEST
1123}
1124
1125AudioPolicyManagerBase::~AudioPolicyManagerBase()
1126{
1127#ifdef AUDIO_POLICY_TEST
1128    exit();
1129#endif //AUDIO_POLICY_TEST
1130   for (size_t i = 0; i < mOutputs.size(); i++) {
1131        mpClientInterface->closeOutput(mOutputs.keyAt(i));
1132        delete mOutputs.valueAt(i);
1133   }
1134   mOutputs.clear();
1135   for (size_t i = 0; i < mInputs.size(); i++) {
1136        mpClientInterface->closeInput(mInputs.keyAt(i));
1137        delete mInputs.valueAt(i);
1138   }
1139   mInputs.clear();
1140}
1141
1142status_t AudioPolicyManagerBase::initCheck()
1143{
1144    return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1145}
1146
1147#ifdef AUDIO_POLICY_TEST
1148bool AudioPolicyManagerBase::threadLoop()
1149{
1150    LOGV("entering threadLoop()");
1151    while (!exitPending())
1152    {
1153        String8 command;
1154        int valueInt;
1155        String8 value;
1156
1157        Mutex::Autolock _l(mLock);
1158        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1159
1160        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1161        AudioParameter param = AudioParameter(command);
1162
1163        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1164            valueInt != 0) {
1165            LOGV("Test command %s received", command.string());
1166            String8 target;
1167            if (param.get(String8("target"), target) != NO_ERROR) {
1168                target = "Manager";
1169            }
1170            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1171                param.remove(String8("test_cmd_policy_output"));
1172                mCurOutput = valueInt;
1173            }
1174            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1175                param.remove(String8("test_cmd_policy_direct"));
1176                if (value == "false") {
1177                    mDirectOutput = false;
1178                } else if (value == "true") {
1179                    mDirectOutput = true;
1180                }
1181            }
1182            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1183                param.remove(String8("test_cmd_policy_input"));
1184                mTestInput = valueInt;
1185            }
1186
1187            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1188                param.remove(String8("test_cmd_policy_format"));
1189                int format = AudioSystem::INVALID_FORMAT;
1190                if (value == "PCM 16 bits") {
1191                    format = AudioSystem::PCM_16_BIT;
1192                } else if (value == "PCM 8 bits") {
1193                    format = AudioSystem::PCM_8_BIT;
1194                } else if (value == "Compressed MP3") {
1195                    format = AudioSystem::MP3;
1196                }
1197                if (format != AudioSystem::INVALID_FORMAT) {
1198                    if (target == "Manager") {
1199                        mTestFormat = format;
1200                    } else if (mTestOutputs[mCurOutput] != 0) {
1201                        AudioParameter outputParam = AudioParameter();
1202                        outputParam.addInt(String8("format"), format);
1203                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1204                    }
1205                }
1206            }
1207            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1208                param.remove(String8("test_cmd_policy_channels"));
1209                int channels = 0;
1210
1211                if (value == "Channels Stereo") {
1212                    channels =  AudioSystem::CHANNEL_OUT_STEREO;
1213                } else if (value == "Channels Mono") {
1214                    channels =  AudioSystem::CHANNEL_OUT_MONO;
1215                }
1216                if (channels != 0) {
1217                    if (target == "Manager") {
1218                        mTestChannels = channels;
1219                    } else if (mTestOutputs[mCurOutput] != 0) {
1220                        AudioParameter outputParam = AudioParameter();
1221                        outputParam.addInt(String8("channels"), channels);
1222                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1223                    }
1224                }
1225            }
1226            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1227                param.remove(String8("test_cmd_policy_sampleRate"));
1228                if (valueInt >= 0 && valueInt <= 96000) {
1229                    int samplingRate = valueInt;
1230                    if (target == "Manager") {
1231                        mTestSamplingRate = samplingRate;
1232                    } else if (mTestOutputs[mCurOutput] != 0) {
1233                        AudioParameter outputParam = AudioParameter();
1234                        outputParam.addInt(String8("sampling_rate"), samplingRate);
1235                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1236                    }
1237                }
1238            }
1239
1240            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1241                param.remove(String8("test_cmd_policy_reopen"));
1242
1243                mpClientInterface->closeOutput(mHardwareOutput);
1244                delete mOutputs.valueFor(mHardwareOutput);
1245                mOutputs.removeItem(mHardwareOutput);
1246
1247                AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1248                outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1249                mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1250                                                &outputDesc->mSamplingRate,
1251                                                &outputDesc->mFormat,
1252                                                &outputDesc->mChannels,
1253                                                &outputDesc->mLatency,
1254                                                outputDesc->mFlags);
1255                if (mHardwareOutput == 0) {
1256                    LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1257                            outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1258                } else {
1259                    AudioParameter outputCmd = AudioParameter();
1260                    outputCmd.addInt(String8("set_id"), 0);
1261                    mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1262                    addOutput(mHardwareOutput, outputDesc);
1263                }
1264            }
1265
1266
1267            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1268        }
1269    }
1270    return false;
1271}
1272
1273void AudioPolicyManagerBase::exit()
1274{
1275    {
1276        AutoMutex _l(mLock);
1277        requestExit();
1278        mWaitWorkCV.signal();
1279    }
1280    requestExitAndWait();
1281}
1282
1283int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1284{
1285    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1286        if (output == mTestOutputs[i]) return i;
1287    }
1288    return 0;
1289}
1290#endif //AUDIO_POLICY_TEST
1291
1292// ---
1293
1294void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1295{
1296    outputDesc->mId = id;
1297    mOutputs.add(id, outputDesc);
1298}
1299
1300
1301#ifdef WITH_A2DP
1302status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1303                                                 const char *device_address)
1304{
1305    // when an A2DP device is connected, open an A2DP and a duplicated output
1306    LOGV("opening A2DP output for device %s", device_address);
1307    AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1308    outputDesc->mDevice = device;
1309    mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1310                                            &outputDesc->mSamplingRate,
1311                                            &outputDesc->mFormat,
1312                                            &outputDesc->mChannels,
1313                                            &outputDesc->mLatency,
1314                                            outputDesc->mFlags);
1315    if (mA2dpOutput) {
1316        // add A2DP output descriptor
1317        addOutput(mA2dpOutput, outputDesc);
1318
1319        //TODO: configure audio effect output stage here
1320
1321        // set initial stream volume for A2DP device
1322        applyStreamVolumes(mA2dpOutput, device);
1323        if (a2dpUsedForSonification()) {
1324            mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1325        }
1326        if (mDuplicatedOutput != 0 ||
1327            !a2dpUsedForSonification()) {
1328            // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1329            // interface
1330            AudioParameter param;
1331            param.add(String8("a2dp_sink_address"), String8(device_address));
1332            mpClientInterface->setParameters(mA2dpOutput, param.toString());
1333            mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1334
1335            if (a2dpUsedForSonification()) {
1336                // add duplicated output descriptor
1337                AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1338                dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1339                dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1340                dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1341                dupOutputDesc->mFormat = outputDesc->mFormat;
1342                dupOutputDesc->mChannels = outputDesc->mChannels;
1343                dupOutputDesc->mLatency = outputDesc->mLatency;
1344                addOutput(mDuplicatedOutput, dupOutputDesc);
1345                applyStreamVolumes(mDuplicatedOutput, device);
1346            }
1347        } else {
1348            LOGW("getOutput() could not open duplicated output for %d and %d",
1349                    mHardwareOutput, mA2dpOutput);
1350            mpClientInterface->closeOutput(mA2dpOutput);
1351            mOutputs.removeItem(mA2dpOutput);
1352            mA2dpOutput = 0;
1353            delete outputDesc;
1354            return NO_INIT;
1355        }
1356    } else {
1357        LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1358        delete outputDesc;
1359        return NO_INIT;
1360    }
1361    AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1362
1363    if (!a2dpUsedForSonification()) {
1364        // mute music on A2DP output if a notification or ringtone is playing
1365        uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1366        for (uint32_t i = 0; i < refCount; i++) {
1367            setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1368        }
1369    }
1370
1371    mA2dpSuspended = false;
1372
1373    return NO_ERROR;
1374}
1375
1376status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1377                                                    const char *device_address)
1378{
1379    if (mA2dpOutput == 0) {
1380        LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1381        return INVALID_OPERATION;
1382    }
1383
1384    if (mA2dpDeviceAddress != device_address) {
1385        LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1386        return INVALID_OPERATION;
1387    }
1388
1389    // mute media strategy to avoid outputting sound on hardware output while music stream
1390    // is switched from A2DP output and before music is paused by music application
1391    setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
1392    setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
1393
1394    if (!a2dpUsedForSonification()) {
1395        // unmute music on A2DP output if a notification or ringtone is playing
1396        uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1397        for (uint32_t i = 0; i < refCount; i++) {
1398            setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1399        }
1400    }
1401    mA2dpDeviceAddress = "";
1402    mA2dpSuspended = false;
1403    return NO_ERROR;
1404}
1405
1406void AudioPolicyManagerBase::closeA2dpOutputs()
1407{
1408
1409    LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1410
1411    if (mDuplicatedOutput != 0) {
1412        AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1413        AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1414        // As all active tracks on duplicated output will be deleted,
1415        // and as they were also referenced on hardware output, the reference
1416        // count for their stream type must be adjusted accordingly on
1417        // hardware output.
1418        for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1419            int refCount = dupOutputDesc->mRefCount[i];
1420            hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1421        }
1422
1423        mpClientInterface->closeOutput(mDuplicatedOutput);
1424        delete mOutputs.valueFor(mDuplicatedOutput);
1425        mOutputs.removeItem(mDuplicatedOutput);
1426        mDuplicatedOutput = 0;
1427    }
1428    if (mA2dpOutput != 0) {
1429        AudioParameter param;
1430        param.add(String8("closing"), String8("true"));
1431        mpClientInterface->setParameters(mA2dpOutput, param.toString());
1432
1433        mpClientInterface->closeOutput(mA2dpOutput);
1434        delete mOutputs.valueFor(mA2dpOutput);
1435        mOutputs.removeItem(mA2dpOutput);
1436        mA2dpOutput = 0;
1437    }
1438}
1439
1440void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1441{
1442    uint32_t prevDevice = getDeviceForStrategy(strategy);
1443    uint32_t curDevice = getDeviceForStrategy(strategy, false);
1444    bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1445    bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1446    audio_io_handle_t srcOutput = 0;
1447    audio_io_handle_t dstOutput = 0;
1448
1449    if (a2dpWasUsed && !a2dpIsUsed) {
1450        bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
1451        dstOutput = mHardwareOutput;
1452        if (dupUsed) {
1453            LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1454            srcOutput = mDuplicatedOutput;
1455        } else {
1456            LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1457            srcOutput = mA2dpOutput;
1458        }
1459    }
1460    if (a2dpIsUsed && !a2dpWasUsed) {
1461        bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
1462        srcOutput = mHardwareOutput;
1463        if (dupUsed) {
1464            LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1465            dstOutput = mDuplicatedOutput;
1466        } else {
1467            LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1468            dstOutput = mA2dpOutput;
1469        }
1470    }
1471
1472    if (srcOutput != 0 && dstOutput != 0) {
1473        // Move effects associated to this strategy from previous output to new output
1474        for (size_t i = 0; i < mEffects.size(); i++) {
1475            EffectDescriptor *desc = mEffects.valueAt(i);
1476            if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1477                    desc->mStrategy == strategy &&
1478                    desc->mIo == srcOutput) {
1479                LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1480                mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1481                desc->mIo = dstOutput;
1482            }
1483        }
1484        // Move tracks associated to this strategy from previous output to new output
1485        for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1486            if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1487                mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
1488            }
1489        }
1490    }
1491}
1492
1493void AudioPolicyManagerBase::checkOutputForAllStrategies()
1494{
1495    checkOutputForStrategy(STRATEGY_PHONE);
1496    checkOutputForStrategy(STRATEGY_SONIFICATION);
1497    checkOutputForStrategy(STRATEGY_MEDIA);
1498    checkOutputForStrategy(STRATEGY_DTMF);
1499}
1500
1501void AudioPolicyManagerBase::checkA2dpSuspend()
1502{
1503    // suspend A2DP output if:
1504    //      (NOT already suspended) &&
1505    //      ((SCO device is connected &&
1506    //       (forced usage for communication || for record is SCO))) ||
1507    //      (phone state is ringing || in call)
1508    //
1509    // restore A2DP output if:
1510    //      (Already suspended) &&
1511    //      ((SCO device is NOT connected ||
1512    //       (forced usage NOT for communication && NOT for record is SCO))) &&
1513    //      (phone state is NOT ringing && NOT in call)
1514    //
1515    if (mA2dpOutput == 0) {
1516        return;
1517    }
1518
1519    if (mA2dpSuspended) {
1520        if (((mScoDeviceAddress == "") ||
1521             ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1522              (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1523             ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1524              (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1525
1526            mpClientInterface->restoreOutput(mA2dpOutput);
1527            mA2dpSuspended = false;
1528        }
1529    } else {
1530        if (((mScoDeviceAddress != "") &&
1531             ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1532              (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1533             ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1534              (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1535
1536            mpClientInterface->suspendOutput(mA2dpOutput);
1537            mA2dpSuspended = true;
1538        }
1539    }
1540}
1541
1542
1543#endif
1544
1545uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1546{
1547    uint32_t device = 0;
1548
1549    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1550    // check the following by order of priority to request a routing change if necessary:
1551    // 1: we are in call or the strategy phone is active on the hardware output:
1552    //      use device for strategy phone
1553    // 2: the strategy sonification is active on the hardware output:
1554    //      use device for strategy sonification
1555    // 3: the strategy media is active on the hardware output:
1556    //      use device for strategy media
1557    // 4: the strategy DTMF is active on the hardware output:
1558    //      use device for strategy DTMF
1559    if (isInCall() ||
1560        outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1561        device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1562    } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1563        device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1564    } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1565        device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1566    } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1567        device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1568    }
1569
1570    LOGV("getNewDevice() selected device %x", device);
1571    return device;
1572}
1573
1574uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1575    return (uint32_t)getStrategy(stream);
1576}
1577
1578uint32_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1579    uint32_t devices;
1580    // By checking the range of stream before calling getStrategy, we avoid
1581    // getStrategy's behavior for invalid streams.  getStrategy would do a LOGE
1582    // and then return STRATEGY_MEDIA, but we want to return the empty set.
1583    if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1584        devices = 0;
1585    } else {
1586        AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1587        devices = getDeviceForStrategy(strategy, true);
1588    }
1589    return devices;
1590}
1591
1592AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1593        AudioSystem::stream_type stream) {
1594    // stream to strategy mapping
1595    switch (stream) {
1596    case AudioSystem::VOICE_CALL:
1597    case AudioSystem::BLUETOOTH_SCO:
1598        return STRATEGY_PHONE;
1599    case AudioSystem::RING:
1600    case AudioSystem::NOTIFICATION:
1601    case AudioSystem::ALARM:
1602    case AudioSystem::ENFORCED_AUDIBLE:
1603        return STRATEGY_SONIFICATION;
1604    case AudioSystem::DTMF:
1605        return STRATEGY_DTMF;
1606    default:
1607        LOGE("unknown stream type");
1608    case AudioSystem::SYSTEM:
1609        // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1610        // while key clicks are played produces a poor result
1611    case AudioSystem::TTS:
1612    case AudioSystem::MUSIC:
1613        return STRATEGY_MEDIA;
1614    }
1615}
1616
1617uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1618{
1619    uint32_t device = 0;
1620
1621    if (fromCache) {
1622        LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1623        return mDeviceForStrategy[strategy];
1624    }
1625
1626    switch (strategy) {
1627    case STRATEGY_DTMF:
1628        if (!isInCall()) {
1629            // when off call, DTMF strategy follows the same rules as MEDIA strategy
1630            device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1631            break;
1632        }
1633        // when in call, DTMF and PHONE strategies follow the same rules
1634        // FALL THROUGH
1635
1636    case STRATEGY_PHONE:
1637        // for phone strategy, we first consider the forced use and then the available devices by order
1638        // of priority
1639        switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1640        case AudioSystem::FORCE_BT_SCO:
1641            if (!isInCall() || strategy != STRATEGY_DTMF) {
1642                device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1643                if (device) break;
1644            }
1645            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1646            if (device) break;
1647            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1648            if (device) break;
1649            // if SCO device is requested but no SCO device is available, fall back to default case
1650            // FALL THROUGH
1651
1652        default:    // FORCE_NONE
1653            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1654            if (device) break;
1655            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1656            if (device) break;
1657#ifdef WITH_A2DP
1658            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1659            if (!isInCall() && !mA2dpSuspended) {
1660                device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1661                if (device) break;
1662                device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1663                if (device) break;
1664            }
1665#endif
1666            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1667            if (device) break;
1668            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1669            if (device) break;
1670            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1671            if (device) break;
1672            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1673            if (device == 0) {
1674                LOGE("getDeviceForStrategy() earpiece device not found");
1675            }
1676            break;
1677
1678        case AudioSystem::FORCE_SPEAKER:
1679#ifdef WITH_A2DP
1680            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1681            // A2DP speaker when forcing to speaker output
1682            if (!isInCall() && !mA2dpSuspended) {
1683                device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1684                if (device) break;
1685            }
1686#endif
1687            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1688            if (device) break;
1689            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1690            if (device) break;
1691            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1692            if (device) break;
1693            device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1694            if (device == 0) {
1695                LOGE("getDeviceForStrategy() speaker device not found");
1696            }
1697            break;
1698        }
1699    break;
1700
1701    case STRATEGY_SONIFICATION:
1702
1703        // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1704        // handleIncallSonification().
1705        if (isInCall()) {
1706            device = getDeviceForStrategy(STRATEGY_PHONE, false);
1707            break;
1708        }
1709        device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1710        if (device == 0) {
1711            LOGE("getDeviceForStrategy() speaker device not found");
1712        }
1713        // The second device used for sonification is the same as the device used by media strategy
1714        // FALL THROUGH
1715
1716    case STRATEGY_MEDIA: {
1717        uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1718        if (device2 == 0) {
1719            device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1720        }
1721#ifdef WITH_A2DP
1722        if ((mA2dpOutput != 0) && !mA2dpSuspended &&
1723                (strategy != STRATEGY_SONIFICATION || a2dpUsedForSonification())) {
1724            if (device2 == 0) {
1725                device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1726            }
1727            if (device2 == 0) {
1728                device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1729            }
1730            if (device2 == 0) {
1731                device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1732            }
1733        }
1734#endif
1735        if (device2 == 0) {
1736            device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1737        }
1738        if (device2 == 0) {
1739            device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1740        }
1741        if (device2 == 0) {
1742            device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1743        }
1744        if (device2 == 0) {
1745            device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1746        }
1747
1748        // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1749        device |= device2;
1750        if (device == 0) {
1751            LOGE("getDeviceForStrategy() speaker device not found");
1752        }
1753        } break;
1754
1755    default:
1756        LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1757        break;
1758    }
1759
1760    LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1761    return device;
1762}
1763
1764void AudioPolicyManagerBase::updateDeviceForStrategy()
1765{
1766    for (int i = 0; i < NUM_STRATEGIES; i++) {
1767        mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1768    }
1769}
1770
1771void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1772{
1773    LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1774    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1775
1776
1777    if (outputDesc->isDuplicated()) {
1778        setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1779        setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1780        return;
1781    }
1782#ifdef WITH_A2DP
1783    // filter devices according to output selected
1784    if (output == mA2dpOutput) {
1785        device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
1786    } else {
1787        device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
1788    }
1789#endif
1790
1791    uint32_t prevDevice = (uint32_t)outputDesc->device();
1792    // Do not change the routing if:
1793    //  - the requestede device is 0
1794    //  - the requested device is the same as current device and force is not specified.
1795    // Doing this check here allows the caller to call setOutputDevice() without conditions
1796    if ((device == 0 || device == prevDevice) && !force) {
1797        LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1798        return;
1799    }
1800
1801    outputDesc->mDevice = device;
1802    // mute media streams if both speaker and headset are selected
1803    if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1804        setStrategyMute(STRATEGY_MEDIA, true, output);
1805        // wait for the PCM output buffers to empty before proceeding with the rest of the command
1806        usleep(outputDesc->mLatency*2*1000);
1807    }
1808
1809    // do the routing
1810    AudioParameter param = AudioParameter();
1811    param.addInt(String8(AudioParameter::keyRouting), (int)device);
1812    mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1813    // update stream volumes according to new device
1814    applyStreamVolumes(output, device, delayMs);
1815
1816    // if changing from a combined headset + speaker route, unmute media streams
1817    if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1818        setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1819    }
1820}
1821
1822uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1823{
1824    uint32_t device;
1825
1826    switch(inputSource) {
1827    case AUDIO_SOURCE_DEFAULT:
1828    case AUDIO_SOURCE_MIC:
1829    case AUDIO_SOURCE_VOICE_RECOGNITION:
1830    case AUDIO_SOURCE_VOICE_COMMUNICATION:
1831        if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1832            mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1833            device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1834        } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1835            device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1836        } else {
1837            device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1838        }
1839        break;
1840    case AUDIO_SOURCE_CAMCORDER:
1841        if (hasBackMicrophone()) {
1842            device = AudioSystem::DEVICE_IN_BACK_MIC;
1843        } else {
1844            device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1845        }
1846        break;
1847    case AUDIO_SOURCE_VOICE_UPLINK:
1848    case AUDIO_SOURCE_VOICE_DOWNLINK:
1849    case AUDIO_SOURCE_VOICE_CALL:
1850        device = AudioSystem::DEVICE_IN_VOICE_CALL;
1851        break;
1852    default:
1853        LOGW("getDeviceForInputSource() invalid input source %d", inputSource);
1854        device = 0;
1855        break;
1856    }
1857    LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1858    return device;
1859}
1860
1861audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1862{
1863    for (size_t i = 0; i < mInputs.size(); i++) {
1864        if (mInputs.valueAt(i)->mRefCount > 0) {
1865            return mInputs.keyAt(i);
1866        }
1867    }
1868    return 0;
1869}
1870
1871float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
1872        int indexInUi) {
1873    // the volume index in the UI is relative to the min and max volume indices for this stream type
1874    int nbSteps = 1 + streamDesc.mVolIndex[StreamDescriptor::VOLMAX] -
1875            streamDesc.mVolIndex[StreamDescriptor::VOLMIN];
1876    int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
1877            (streamDesc.mIndexMax - streamDesc.mIndexMin);
1878
1879    // find what part of the curve this index volume belongs to, or if it's out of bounds
1880    int segment = 0;
1881    if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLMIN]) {         // out of bounds
1882        return 0.0f;
1883    } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE1]) {
1884        segment = 0;
1885    } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE2]) {
1886        segment = 1;
1887    } else if (volIdx <= streamDesc.mVolIndex[StreamDescriptor::VOLMAX]) {
1888        segment = 2;
1889    } else {                                                               // out of bounds
1890        return 1.0f;
1891    }
1892
1893    // linear interpolation in the attenuation table in dB
1894    float decibels = streamDesc.mVolDbAtt[segment] +
1895            ((float)(volIdx - streamDesc.mVolIndex[segment])) *
1896                ( (streamDesc.mVolDbAtt[segment+1] - streamDesc.mVolDbAtt[segment]) /
1897                    ((float)(streamDesc.mVolIndex[segment+1] - streamDesc.mVolIndex[segment])) );
1898
1899    float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
1900
1901    LOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
1902            streamDesc.mVolIndex[segment], volIdx, streamDesc.mVolIndex[segment+1],
1903            streamDesc.mVolDbAtt[segment], decibels, streamDesc.mVolDbAtt[segment+1],
1904            amplification);
1905
1906    return amplification;
1907}
1908
1909void AudioPolicyManagerBase::initializeVolumeCurves() {
1910    // initialize the volume curves to a (-49.5 - 0 dB) attenuation in 0.5dB steps
1911    for (int i=0 ; i< AudioSystem::NUM_STREAM_TYPES ; i++) {
1912        mStreams[i].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1913        mStreams[i].mVolDbAtt[StreamDescriptor::VOLMIN] = -49.5f;
1914        mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE1] = 33;
1915        mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -33.5f;
1916        mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE2] = 66;
1917        mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1918        // here we use 100 steps to avoid rounding errors
1919        // when computing the volume in volIndexToAmpl()
1920        mStreams[i].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1921        mStreams[i].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
1922    }
1923
1924    // Modification for music: more attenuation for lower volumes, finer steps at high volumes
1925    mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1926    mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLMIN] = -58.0f;
1927    mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLKNEE1] = 20;
1928    mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -40.0f;
1929    mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLKNEE2] = 60;
1930    mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1931    mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1932    mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
1933}
1934
1935float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1936{
1937    float volume = 1.0;
1938    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1939    StreamDescriptor &streamDesc = mStreams[stream];
1940
1941    if (device == 0) {
1942        device = outputDesc->device();
1943    }
1944
1945    // if volume is not 0 (not muted), force media volume to max on digital output
1946    if (stream == AudioSystem::MUSIC &&
1947        index != mStreams[stream].mIndexMin &&
1948        device == AudioSystem::DEVICE_OUT_AUX_DIGITAL) {
1949        return 1.0;
1950    }
1951
1952    volume = volIndexToAmpl(device, streamDesc, index);
1953
1954    // if a headset is connected, apply the following rules to ring tones and notifications
1955    // to avoid sound level bursts in user's ears:
1956    // - always attenuate ring tones and notifications volume by 6dB
1957    // - if music is playing, always limit the volume to current music volume,
1958    // with a minimum threshold at -36dB so that notification is always perceived.
1959    if ((device &
1960        (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1961        AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1962        AudioSystem::DEVICE_OUT_WIRED_HEADSET |
1963        AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
1964        ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) ||
1965         (stream == AudioSystem::SYSTEM)) &&
1966        streamDesc.mCanBeMuted) {
1967        volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1968        // when the phone is ringing we must consider that music could have been paused just before
1969        // by the music application and behave as if music was active if the last music track was
1970        // just stopped
1971        if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1972            float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1973            float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1974            if (volume > minVol) {
1975                volume = minVol;
1976                LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1977            }
1978        }
1979    }
1980
1981    return volume;
1982}
1983
1984status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1985{
1986
1987    // do not change actual stream volume if the stream is muted
1988    if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1989        LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1990        return NO_ERROR;
1991    }
1992
1993    // do not change in call volume if bluetooth is connected and vice versa
1994    if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1995        (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1996        LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1997             stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1998        return INVALID_OPERATION;
1999    }
2000
2001    float volume = computeVolume(stream, index, output, device);
2002    // We actually change the volume if:
2003    // - the float value returned by computeVolume() changed
2004    // - the force flag is set
2005    if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2006            force) {
2007        mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2008        LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2009        if (stream == AudioSystem::VOICE_CALL ||
2010            stream == AudioSystem::DTMF ||
2011            stream == AudioSystem::BLUETOOTH_SCO) {
2012            // offset value to reflect actual hardware volume that never reaches 0
2013            // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2014            volume = 0.01 + 0.99 * volume;
2015            // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2016            // enabled
2017            if (stream == AudioSystem::BLUETOOTH_SCO) {
2018                mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2019            }
2020        }
2021
2022        mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2023    }
2024
2025    if (stream == AudioSystem::VOICE_CALL ||
2026        stream == AudioSystem::BLUETOOTH_SCO) {
2027        float voiceVolume;
2028        // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2029        if (stream == AudioSystem::VOICE_CALL) {
2030            voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2031        } else {
2032            voiceVolume = 1.0;
2033        }
2034
2035        if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
2036            mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2037            mLastVoiceVolume = voiceVolume;
2038        }
2039    }
2040
2041    return NO_ERROR;
2042}
2043
2044void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs, bool force)
2045{
2046    LOGV("applyStreamVolumes() for output %d and device %x", output, device);
2047
2048    for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2049        checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs, force);
2050    }
2051}
2052
2053void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2054{
2055    LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2056    for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2057        if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2058            setStreamMute(stream, on, output, delayMs);
2059        }
2060    }
2061}
2062
2063void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2064{
2065    StreamDescriptor &streamDesc = mStreams[stream];
2066    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2067
2068    LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2069
2070    if (on) {
2071        if (outputDesc->mMuteCount[stream] == 0) {
2072            if (streamDesc.mCanBeMuted) {
2073                checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
2074            }
2075        }
2076        // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2077        outputDesc->mMuteCount[stream]++;
2078    } else {
2079        if (outputDesc->mMuteCount[stream] == 0) {
2080            LOGW("setStreamMute() unmuting non muted stream!");
2081            return;
2082        }
2083        if (--outputDesc->mMuteCount[stream] == 0) {
2084            checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
2085        }
2086    }
2087}
2088
2089void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2090{
2091    // if the stream pertains to sonification strategy and we are in call we must
2092    // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2093    // in the device used for phone strategy and play the tone if the selected device does not
2094    // interfere with the device used for phone strategy
2095    // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2096    // many times as there are active tracks on the output
2097
2098    if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
2099        AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
2100        LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2101                stream, starting, outputDesc->mDevice, stateChange);
2102        if (outputDesc->mRefCount[stream]) {
2103            int muteCount = 1;
2104            if (stateChange) {
2105                muteCount = outputDesc->mRefCount[stream];
2106            }
2107            if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2108                LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2109                for (int i = 0; i < muteCount; i++) {
2110                    setStreamMute(stream, starting, mHardwareOutput);
2111                }
2112            } else {
2113                LOGV("handleIncallSonification() high visibility");
2114                if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
2115                    LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2116                    for (int i = 0; i < muteCount; i++) {
2117                        setStreamMute(stream, starting, mHardwareOutput);
2118                    }
2119                }
2120                if (starting) {
2121                    mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2122                } else {
2123                    mpClientInterface->stopTone();
2124                }
2125            }
2126        }
2127    }
2128}
2129
2130bool AudioPolicyManagerBase::isInCall()
2131{
2132    return isStateInCall(mPhoneState);
2133}
2134
2135bool AudioPolicyManagerBase::isStateInCall(int state) {
2136    return ((state == AudioSystem::MODE_IN_CALL) ||
2137            (state == AudioSystem::MODE_IN_COMMUNICATION));
2138}
2139
2140bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2141                                    uint32_t samplingRate,
2142                                    uint32_t format,
2143                                    uint32_t channels,
2144                                    AudioSystem::output_flags flags,
2145                                    uint32_t device)
2146{
2147   return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2148          (format !=0 && !AudioSystem::isLinearPCM(format)));
2149}
2150
2151uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2152{
2153    return MAX_EFFECTS_CPU_LOAD;
2154}
2155
2156uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2157{
2158    return MAX_EFFECTS_MEMORY;
2159}
2160
2161// --- AudioOutputDescriptor class implementation
2162
2163AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2164    : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2165    mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2166{
2167    // clear usage count for all stream types
2168    for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2169        mRefCount[i] = 0;
2170        mCurVolume[i] = -1.0;
2171        mMuteCount[i] = 0;
2172        mStopTime[i] = 0;
2173    }
2174}
2175
2176uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2177{
2178    uint32_t device = 0;
2179    if (isDuplicated()) {
2180        device = mOutput1->mDevice | mOutput2->mDevice;
2181    } else {
2182        device = mDevice;
2183    }
2184    return device;
2185}
2186
2187void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2188{
2189    // forward usage count change to attached outputs
2190    if (isDuplicated()) {
2191        mOutput1->changeRefCount(stream, delta);
2192        mOutput2->changeRefCount(stream, delta);
2193    }
2194    if ((delta + (int)mRefCount[stream]) < 0) {
2195        LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2196        mRefCount[stream] = 0;
2197        return;
2198    }
2199    mRefCount[stream] += delta;
2200    LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2201}
2202
2203uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2204{
2205    uint32_t refcount = 0;
2206    for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2207        refcount += mRefCount[i];
2208    }
2209    return refcount;
2210}
2211
2212uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2213{
2214    uint32_t refCount = 0;
2215    for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2216        if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2217            refCount += mRefCount[i];
2218        }
2219    }
2220    return refCount;
2221}
2222
2223status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2224{
2225    const size_t SIZE = 256;
2226    char buffer[SIZE];
2227    String8 result;
2228
2229    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2230    result.append(buffer);
2231    snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2232    result.append(buffer);
2233    snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2234    result.append(buffer);
2235    snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2236    result.append(buffer);
2237    snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2238    result.append(buffer);
2239    snprintf(buffer, SIZE, " Devices %08x\n", device());
2240    result.append(buffer);
2241    snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2242    result.append(buffer);
2243    for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2244        snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2245        result.append(buffer);
2246    }
2247    write(fd, result.string(), result.size());
2248
2249    return NO_ERROR;
2250}
2251
2252// --- AudioInputDescriptor class implementation
2253
2254AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2255    : mSamplingRate(0), mFormat(0), mChannels(0),
2256      mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0),
2257      mInputSource(0)
2258{
2259}
2260
2261status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2262{
2263    const size_t SIZE = 256;
2264    char buffer[SIZE];
2265    String8 result;
2266
2267    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2268    result.append(buffer);
2269    snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2270    result.append(buffer);
2271    snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2272    result.append(buffer);
2273    snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2274    result.append(buffer);
2275    snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2276    result.append(buffer);
2277    snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2278    result.append(buffer);
2279    write(fd, result.string(), result.size());
2280
2281    return NO_ERROR;
2282}
2283
2284// --- StreamDescriptor class implementation
2285
2286void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2287{
2288    snprintf(buffer, size, "      %02d         %02d         %02d         %d\n",
2289            mIndexMin,
2290            mIndexMax,
2291            mIndexCur,
2292            mCanBeMuted);
2293}
2294
2295// --- EffectDescriptor class implementation
2296
2297status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2298{
2299    const size_t SIZE = 256;
2300    char buffer[SIZE];
2301    String8 result;
2302
2303    snprintf(buffer, SIZE, " I/O: %d\n", mIo);
2304    result.append(buffer);
2305    snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2306    result.append(buffer);
2307    snprintf(buffer, SIZE, " Session: %d\n", mSession);
2308    result.append(buffer);
2309    snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
2310    result.append(buffer);
2311    snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
2312    result.append(buffer);
2313    write(fd, result.string(), result.size());
2314
2315    return NO_ERROR;
2316}
2317
2318
2319
2320}; // namespace android
2321