AudioPolicyManagerBase.cpp revision f466bfe146aa7fb22a687acc264eebe96e19e39b
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
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL  AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL  AUDIO_DEVICE_OUT_REMOTE_SUBMIX
33
34#include <inttypes.h>
35#include <math.h>
36
37#include <cutils/properties.h>
38#include <utils/Log.h>
39
40#include <hardware/audio.h>
41#include <hardware/audio_effect.h>
42#include <hardware_legacy/audio_policy_conf.h>
43#include <hardware_legacy/AudioPolicyManagerBase.h>
44
45namespace android_audio_legacy {
46
47// ----------------------------------------------------------------------------
48// AudioPolicyInterface implementation
49// ----------------------------------------------------------------------------
50
51
52status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
53                                                  AudioSystem::device_connection_state state,
54                                                  const char *device_address)
55{
56    ALOGV("setDeviceConnectionState() device: 0x%X, state %d, address %s", device, state, device_address);
57
58    // connect/disconnect only 1 device at a time
59    if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
60
61    if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
62        ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
63        return BAD_VALUE;
64    }
65
66    // handle output devices
67    if (audio_is_output_device(device)) {
68        SortedVector <audio_io_handle_t> outputs;
69
70        if (!mHasA2dp && audio_is_a2dp_out_device(device)) {
71            ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
72            return BAD_VALUE;
73        }
74        if (!mHasUsb && audio_is_usb_out_device(device)) {
75            ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
76            return BAD_VALUE;
77        }
78        if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
79            ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
80            return BAD_VALUE;
81        }
82
83        // save a copy of the opened output descriptors before any output is opened or closed
84        // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
85        mPreviousOutputs = mOutputs;
86        String8 paramStr;
87        switch (state)
88        {
89        // handle output device connection
90        case AudioSystem::DEVICE_STATE_AVAILABLE:
91            if (mAvailableOutputDevices & device) {
92                ALOGW("setDeviceConnectionState() device already connected: %x", device);
93                return INVALID_OPERATION;
94            }
95            ALOGV("setDeviceConnectionState() connecting device %x", device);
96
97            if (mHasA2dp && audio_is_a2dp_out_device(device)) {
98                // handle A2DP device connection
99                AudioParameter param;
100                param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
101                paramStr = param.toString();
102            } else if (mHasUsb && audio_is_usb_out_device(device)) {
103                // handle USB device connection
104                paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
105            }
106
107            if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
108                return INVALID_OPERATION;
109            }
110            ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
111                  outputs.size());
112            // register new device as available
113            mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
114
115            if (mHasA2dp && audio_is_a2dp_out_device(device)) {
116                // handle A2DP device connection
117                mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
118                mA2dpSuspended = false;
119            } else if (audio_is_bluetooth_sco_device(device)) {
120                // handle SCO device connection
121                mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
122            } else if (mHasUsb && audio_is_usb_out_device(device)) {
123                // handle USB device connection
124                mUsbOutCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
125            }
126
127            break;
128        // handle output device disconnection
129        case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
130            if (!(mAvailableOutputDevices & device)) {
131                ALOGW("setDeviceConnectionState() device not connected: %x", device);
132                return INVALID_OPERATION;
133            }
134
135            ALOGV("setDeviceConnectionState() disconnecting device %x", device);
136            // remove device from available output devices
137            mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
138            checkOutputsForDevice(device, state, outputs, paramStr);
139
140            if (mHasA2dp && audio_is_a2dp_out_device(device)) {
141                // handle A2DP device disconnection
142                mA2dpDeviceAddress = "";
143                mA2dpSuspended = false;
144            } else if (audio_is_bluetooth_sco_device(device)) {
145                // handle SCO device disconnection
146                mScoDeviceAddress = "";
147            } else if (mHasUsb && audio_is_usb_out_device(device)) {
148                // handle USB device disconnection
149                mUsbOutCardAndDevice = "";
150            }
151            // not currently handling multiple simultaneous submixes: ignoring remote submix
152            //   case and address
153            } break;
154
155        default:
156            ALOGE("setDeviceConnectionState() invalid state: %x", state);
157            return BAD_VALUE;
158        }
159
160        checkA2dpSuspend();
161        checkOutputForAllStrategies();
162        // outputs must be closed after checkOutputForAllStrategies() is executed
163        if (!outputs.isEmpty()) {
164            for (size_t i = 0; i < outputs.size(); i++) {
165                AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
166                // close unused outputs after device disconnection or direct outputs that have been
167                // opened by checkOutputsForDevice() to query dynamic parameters
168                if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
169                        (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
170                         (desc->mDirectOpenCount == 0))) {
171                    closeOutput(outputs[i]);
172                }
173            }
174        }
175
176        updateDevicesAndOutputs();
177        for (size_t i = 0; i < mOutputs.size(); i++) {
178            // do not force device change on duplicated output because if device is 0, it will
179            // also force a device 0 for the two outputs it is duplicated to which may override
180            // a valid device selection on those outputs.
181            setOutputDevice(mOutputs.keyAt(i),
182                            getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
183                            !mOutputs.valueAt(i)->isDuplicated(),
184                            0);
185        }
186
187        return NO_ERROR;
188    }  // end if is output device
189
190    // handle input devices
191    if (audio_is_input_device(device)) {
192        SortedVector <audio_io_handle_t> inputs;
193
194        String8 paramStr;
195        switch (state)
196        {
197        // handle input device connection
198        case AudioSystem::DEVICE_STATE_AVAILABLE: {
199            if (mAvailableInputDevices & device) {
200                ALOGW("setDeviceConnectionState() device already connected: %d", device);
201                return INVALID_OPERATION;
202            }
203
204            if (mHasUsb && audio_is_usb_in_device(device)) {
205                // handle USB device connection
206                paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
207            } else if (mHasA2dp && audio_is_a2dp_in_device(device)) {
208                // handle A2DP device connection
209                AudioParameter param;
210                param.add(String8(AUDIO_PARAMETER_A2DP_SOURCE_ADDRESS), String8(device_address));
211                paramStr = param.toString();
212            }
213
214            if (checkInputsForDevice(device, state, inputs, paramStr) != NO_ERROR) {
215                return INVALID_OPERATION;
216            }
217            mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
218            }
219            break;
220
221        // handle input device disconnection
222        case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
223            if (!(mAvailableInputDevices & device)) {
224                ALOGW("setDeviceConnectionState() device not connected: %d", device);
225                return INVALID_OPERATION;
226            }
227            checkInputsForDevice(device, state, inputs, paramStr);
228            mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
229        } break;
230
231        default:
232            ALOGE("setDeviceConnectionState() invalid state: %x", state);
233            return BAD_VALUE;
234        }
235
236        closeAllInputs();
237
238        return NO_ERROR;
239    } // end if is input device
240
241    ALOGW("setDeviceConnectionState() invalid device: %x", device);
242    return BAD_VALUE;
243}
244
245AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
246                                                  const char *device_address)
247{
248    AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
249    String8 address = String8(device_address);
250    if (audio_is_output_device(device)) {
251        if (device & mAvailableOutputDevices) {
252            if (audio_is_a2dp_out_device(device) &&
253                (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
254                return state;
255            }
256            if (audio_is_bluetooth_sco_device(device) &&
257                address != "" && mScoDeviceAddress != address) {
258                return state;
259            }
260            if (audio_is_usb_out_device(device) &&
261                (!mHasUsb || (address != "" && mUsbOutCardAndDevice != address))) {
262                ALOGE("getDeviceConnectionState() invalid device: %x", device);
263                return state;
264            }
265            if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
266                return state;
267            }
268            state = AudioSystem::DEVICE_STATE_AVAILABLE;
269        }
270    } else if (audio_is_input_device(device)) {
271        if (device & mAvailableInputDevices) {
272            state = AudioSystem::DEVICE_STATE_AVAILABLE;
273        }
274    }
275
276    return state;
277}
278
279void AudioPolicyManagerBase::setPhoneState(int state)
280{
281    ALOGV("setPhoneState() state %d", state);
282    audio_devices_t newDevice = AUDIO_DEVICE_NONE;
283    if (state < 0 || state >= AudioSystem::NUM_MODES) {
284        ALOGW("setPhoneState() invalid state %d", state);
285        return;
286    }
287
288    if (state == mPhoneState ) {
289        ALOGW("setPhoneState() setting same state %d", state);
290        return;
291    }
292
293    // if leaving call state, handle special case of active streams
294    // pertaining to sonification strategy see handleIncallSonification()
295    if (isInCall()) {
296        ALOGV("setPhoneState() in call state management: new state is %d", state);
297        for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
298            handleIncallSonification(stream, false, true);
299        }
300    }
301
302    // store previous phone state for management of sonification strategy below
303    int oldState = mPhoneState;
304    mPhoneState = state;
305    bool force = false;
306
307    // are we entering or starting a call
308    if (!isStateInCall(oldState) && isStateInCall(state)) {
309        ALOGV("  Entering call in setPhoneState()");
310        // force routing command to audio hardware when starting a call
311        // even if no device change is needed
312        force = true;
313        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
314            mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
315                    sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
316        }
317    } else if (isStateInCall(oldState) && !isStateInCall(state)) {
318        ALOGV("  Exiting call in setPhoneState()");
319        // force routing command to audio hardware when exiting a call
320        // even if no device change is needed
321        force = true;
322        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
323            mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
324                    sVolumeProfiles[AUDIO_STREAM_DTMF][j];
325        }
326    } else if (isStateInCall(state) && (state != oldState)) {
327        ALOGV("  Switching between telephony and VoIP in setPhoneState()");
328        // force routing command to audio hardware when switching between telephony and VoIP
329        // even if no device change is needed
330        force = true;
331    }
332
333    // check for device and output changes triggered by new phone state
334    newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
335    checkA2dpSuspend();
336    checkOutputForAllStrategies();
337    updateDevicesAndOutputs();
338
339    AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
340
341    // force routing command to audio hardware when ending call
342    // even if no device change is needed
343    if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
344        newDevice = hwOutputDesc->device();
345    }
346
347    int delayMs = 0;
348    if (isStateInCall(state)) {
349        nsecs_t sysTime = systemTime();
350        for (size_t i = 0; i < mOutputs.size(); i++) {
351            AudioOutputDescriptor *desc = mOutputs.valueAt(i);
352            // mute media and sonification strategies and delay device switch by the largest
353            // latency of any output where either strategy is active.
354            // This avoid sending the ring tone or music tail into the earpiece or headset.
355            if ((desc->isStrategyActive(STRATEGY_MEDIA,
356                                     SONIFICATION_HEADSET_MUSIC_DELAY,
357                                     sysTime) ||
358                    desc->isStrategyActive(STRATEGY_SONIFICATION,
359                                         SONIFICATION_HEADSET_MUSIC_DELAY,
360                                         sysTime)) &&
361                    (delayMs < (int)desc->mLatency*2)) {
362                delayMs = desc->mLatency*2;
363            }
364            setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
365            setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
366                getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
367            setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
368            setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
369                getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
370        }
371    }
372
373    // change routing is necessary
374    setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
375
376    // if entering in call state, handle special case of active streams
377    // pertaining to sonification strategy see handleIncallSonification()
378    if (isStateInCall(state)) {
379        ALOGV("setPhoneState() in call state management: new state is %d", state);
380        for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
381            handleIncallSonification(stream, true, true);
382        }
383    }
384
385    // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
386    if (state == AudioSystem::MODE_RINGTONE &&
387        isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
388        mLimitRingtoneVolume = true;
389    } else {
390        mLimitRingtoneVolume = false;
391    }
392}
393
394void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
395{
396    ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
397
398    bool forceVolumeReeval = false;
399    switch(usage) {
400    case AudioSystem::FOR_COMMUNICATION:
401        if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
402            config != AudioSystem::FORCE_NONE) {
403            ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
404            return;
405        }
406        forceVolumeReeval = true;
407        mForceUse[usage] = config;
408        break;
409    case AudioSystem::FOR_MEDIA:
410        if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
411            config != AudioSystem::FORCE_WIRED_ACCESSORY &&
412            config != AudioSystem::FORCE_ANALOG_DOCK &&
413            config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
414            config != AudioSystem::FORCE_NO_BT_A2DP) {
415            ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
416            return;
417        }
418        mForceUse[usage] = config;
419        break;
420    case AudioSystem::FOR_RECORD:
421        if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
422            config != AudioSystem::FORCE_NONE) {
423            ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
424            return;
425        }
426        mForceUse[usage] = config;
427        break;
428    case AudioSystem::FOR_DOCK:
429        if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
430            config != AudioSystem::FORCE_BT_DESK_DOCK &&
431            config != AudioSystem::FORCE_WIRED_ACCESSORY &&
432            config != AudioSystem::FORCE_ANALOG_DOCK &&
433            config != AudioSystem::FORCE_DIGITAL_DOCK) {
434            ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
435        }
436        forceVolumeReeval = true;
437        mForceUse[usage] = config;
438        break;
439    case AudioSystem::FOR_SYSTEM:
440        if (config != AudioSystem::FORCE_NONE &&
441            config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
442            ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
443        }
444        forceVolumeReeval = true;
445        mForceUse[usage] = config;
446        break;
447    default:
448        ALOGW("setForceUse() invalid usage %d", usage);
449        break;
450    }
451
452    // check for device and output changes triggered by new force usage
453    checkA2dpSuspend();
454    checkOutputForAllStrategies();
455    updateDevicesAndOutputs();
456    for (size_t i = 0; i < mOutputs.size(); i++) {
457        audio_io_handle_t output = mOutputs.keyAt(i);
458        audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
459        setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
460        if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
461            applyStreamVolumes(output, newDevice, 0, true);
462        }
463    }
464
465    audio_io_handle_t activeInput = getActiveInput();
466    if (activeInput != 0) {
467        AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
468        audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
469        if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
470            ALOGV("setForceUse() changing device from %x to %x for input %d",
471                    inputDesc->mDevice, newDevice, activeInput);
472            inputDesc->mDevice = newDevice;
473            AudioParameter param = AudioParameter();
474            param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
475            mpClientInterface->setParameters(activeInput, param.toString());
476        }
477    }
478
479}
480
481AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
482{
483    return mForceUse[usage];
484}
485
486void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
487{
488    ALOGV("setSystemProperty() property %s, value %s", property, value);
489}
490
491// Find a direct output profile compatible with the parameters passed, even if the input flags do
492// not explicitly request a direct output
493AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
494                                                               audio_devices_t device,
495                                                               uint32_t samplingRate,
496                                                               audio_format_t format,
497                                                               audio_channel_mask_t channelMask,
498                                                               audio_output_flags_t flags)
499{
500    for (size_t i = 0; i < mHwModules.size(); i++) {
501        if (mHwModules[i]->mHandle == 0) {
502            continue;
503        }
504        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
505            IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
506            if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
507                if (profile->isCompatibleProfile(device, samplingRate, format,
508                                           channelMask,
509                                           AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
510                    if (mAvailableOutputDevices & profile->mSupportedDevices) {
511                        return mHwModules[i]->mOutputProfiles[j];
512                    }
513                }
514            } else {
515                if (profile->isCompatibleProfile(device, samplingRate, format,
516                                           channelMask,
517                                           AUDIO_OUTPUT_FLAG_DIRECT)) {
518                    if (mAvailableOutputDevices & profile->mSupportedDevices) {
519                        return mHwModules[i]->mOutputProfiles[j];
520                    }
521                }
522            }
523        }
524    }
525    return 0;
526}
527
528audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
529                                    uint32_t samplingRate,
530                                    audio_format_t format,
531                                    audio_channel_mask_t channelMask,
532                                    AudioSystem::output_flags flags,
533                                    const audio_offload_info_t *offloadInfo)
534{
535    audio_io_handle_t output = 0;
536    uint32_t latency = 0;
537    routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
538    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
539    ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
540          device, stream, samplingRate, format, channelMask, flags);
541
542#ifdef AUDIO_POLICY_TEST
543    if (mCurOutput != 0) {
544        ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
545                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
546
547        if (mTestOutputs[mCurOutput] == 0) {
548            ALOGV("getOutput() opening test output");
549            AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
550            outputDesc->mDevice = mTestDevice;
551            outputDesc->mSamplingRate = mTestSamplingRate;
552            outputDesc->mFormat = mTestFormat;
553            outputDesc->mChannelMask = mTestChannels;
554            outputDesc->mLatency = mTestLatencyMs;
555            outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
556            outputDesc->mRefCount[stream] = 0;
557            mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
558                                            &outputDesc->mSamplingRate,
559                                            &outputDesc->mFormat,
560                                            &outputDesc->mChannelMask,
561                                            &outputDesc->mLatency,
562                                            outputDesc->mFlags,
563                                            offloadInfo);
564            if (mTestOutputs[mCurOutput]) {
565                AudioParameter outputCmd = AudioParameter();
566                outputCmd.addInt(String8("set_id"),mCurOutput);
567                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
568                addOutput(mTestOutputs[mCurOutput], outputDesc);
569            }
570        }
571        return mTestOutputs[mCurOutput];
572    }
573#endif //AUDIO_POLICY_TEST
574
575    // open a direct output if required by specified parameters
576    //force direct flag if offload flag is set: offloading implies a direct output stream
577    // and all common behaviors are driven by checking only the direct flag
578    // this should normally be set appropriately in the policy configuration file
579    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
580        flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
581    }
582
583    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
584    // creating an offloaded track and tearing it down immediately after start when audioflinger
585    // detects there is an active non offloadable effect.
586    // FIXME: We should check the audio session here but we do not have it in this context.
587    // This may prevent offloading in rare situations where effects are left active by apps
588    // in the background.
589    IOProfile *profile = NULL;
590    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
591            !isNonOffloadableEffectEnabled()) {
592        profile = getProfileForDirectOutput(device,
593                                           samplingRate,
594                                           format,
595                                           channelMask,
596                                           (audio_output_flags_t)flags);
597    }
598
599    if (profile != NULL) {
600        AudioOutputDescriptor *outputDesc = NULL;
601
602        for (size_t i = 0; i < mOutputs.size(); i++) {
603            AudioOutputDescriptor *desc = mOutputs.valueAt(i);
604            if (!desc->isDuplicated() && (profile == desc->mProfile)) {
605                outputDesc = desc;
606                // reuse direct output if currently open and configured with same parameters
607                if ((samplingRate == outputDesc->mSamplingRate) &&
608                        (format == outputDesc->mFormat) &&
609                        (channelMask == outputDesc->mChannelMask)) {
610                    outputDesc->mDirectOpenCount++;
611                    ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
612                    return mOutputs.keyAt(i);
613                }
614            }
615        }
616        // close direct output if currently open and configured with different parameters
617        if (outputDesc != NULL) {
618            closeOutput(outputDesc->mId);
619        }
620        outputDesc = new AudioOutputDescriptor(profile);
621        outputDesc->mDevice = device;
622        outputDesc->mSamplingRate = samplingRate;
623        outputDesc->mFormat = format;
624        outputDesc->mChannelMask = channelMask;
625        outputDesc->mLatency = 0;
626        outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
627        outputDesc->mRefCount[stream] = 0;
628        outputDesc->mStopTime[stream] = 0;
629        outputDesc->mDirectOpenCount = 1;
630        output = mpClientInterface->openOutput(profile->mModule->mHandle,
631                                        &outputDesc->mDevice,
632                                        &outputDesc->mSamplingRate,
633                                        &outputDesc->mFormat,
634                                        &outputDesc->mChannelMask,
635                                        &outputDesc->mLatency,
636                                        outputDesc->mFlags,
637                                        offloadInfo);
638
639        // only accept an output with the requested parameters
640        if (output == 0 ||
641            (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
642            (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
643            (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
644            ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
645                    "format %d %d, channelMask %04x %04x", output, samplingRate,
646                    outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
647                    outputDesc->mChannelMask);
648            if (output != 0) {
649                mpClientInterface->closeOutput(output);
650            }
651            delete outputDesc;
652            return 0;
653        }
654        audio_io_handle_t srcOutput = getOutputForEffect();
655        addOutput(output, outputDesc);
656        audio_io_handle_t dstOutput = getOutputForEffect();
657        if (dstOutput == output) {
658            mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
659        }
660        mPreviousOutputs = mOutputs;
661        ALOGV("getOutput() returns new direct output %d", output);
662        return output;
663    }
664
665    // ignoring channel mask due to downmix capability in mixer
666
667    // open a non direct output
668
669    // for non direct outputs, only PCM is supported
670    if (audio_is_linear_pcm(format)) {
671        // get which output is suitable for the specified stream. The actual
672        // routing change will happen when startOutput() will be called
673        SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
674
675        output = selectOutput(outputs, flags);
676    }
677    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
678            "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
679
680    ALOGV("getOutput() returns output %d", output);
681
682    return output;
683}
684
685audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
686                                                       AudioSystem::output_flags flags)
687{
688    // select one output among several that provide a path to a particular device or set of
689    // devices (the list was previously build by getOutputsForDevice()).
690    // The priority is as follows:
691    // 1: the output with the highest number of requested policy flags
692    // 2: the primary output
693    // 3: the first output in the list
694
695    if (outputs.size() == 0) {
696        return 0;
697    }
698    if (outputs.size() == 1) {
699        return outputs[0];
700    }
701
702    int maxCommonFlags = 0;
703    audio_io_handle_t outputFlags = 0;
704    audio_io_handle_t outputPrimary = 0;
705
706    for (size_t i = 0; i < outputs.size(); i++) {
707        AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
708        if (!outputDesc->isDuplicated()) {
709            int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
710            if (commonFlags > maxCommonFlags) {
711                outputFlags = outputs[i];
712                maxCommonFlags = commonFlags;
713                ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
714            }
715            if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
716                outputPrimary = outputs[i];
717            }
718        }
719    }
720
721    if (outputFlags != 0) {
722        return outputFlags;
723    }
724    if (outputPrimary != 0) {
725        return outputPrimary;
726    }
727
728    return outputs[0];
729}
730
731status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
732                                             AudioSystem::stream_type stream,
733                                             int session)
734{
735    ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
736    ssize_t index = mOutputs.indexOfKey(output);
737    if (index < 0) {
738        ALOGW("startOutput() unknown output %d", output);
739        return BAD_VALUE;
740    }
741
742    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
743
744    // increment usage count for this stream on the requested output:
745    // NOTE that the usage count is the same for duplicated output and hardware output which is
746    // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
747    outputDesc->changeRefCount(stream, 1);
748
749    if (outputDesc->mRefCount[stream] == 1) {
750        audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
751        routing_strategy strategy = getStrategy(stream);
752        bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
753                            (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
754        uint32_t waitMs = 0;
755        bool force = false;
756        for (size_t i = 0; i < mOutputs.size(); i++) {
757            AudioOutputDescriptor *desc = mOutputs.valueAt(i);
758            if (desc != outputDesc) {
759                // force a device change if any other output is managed by the same hw
760                // module and has a current device selection that differs from selected device.
761                // In this case, the audio HAL must receive the new device selection so that it can
762                // change the device currently selected by the other active output.
763                if (outputDesc->sharesHwModuleWith(desc) &&
764                    desc->device() != newDevice) {
765                    force = true;
766                }
767                // wait for audio on other active outputs to be presented when starting
768                // a notification so that audio focus effect can propagate.
769                uint32_t latency = desc->latency();
770                if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
771                    waitMs = latency;
772                }
773            }
774        }
775        uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
776
777        // handle special case for sonification while in call
778        if (isInCall()) {
779            handleIncallSonification(stream, true, false);
780        }
781
782        // apply volume rules for current stream and device if necessary
783        checkAndSetVolume(stream,
784                          mStreams[stream].getVolumeIndex(newDevice),
785                          output,
786                          newDevice);
787
788        // update the outputs if starting an output with a stream that can affect notification
789        // routing
790        handleNotificationRoutingForStream(stream);
791        if (waitMs > muteWaitMs) {
792            usleep((waitMs - muteWaitMs) * 2 * 1000);
793        }
794    }
795    return NO_ERROR;
796}
797
798
799status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
800                                            AudioSystem::stream_type stream,
801                                            int session)
802{
803    ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
804    ssize_t index = mOutputs.indexOfKey(output);
805    if (index < 0) {
806        ALOGW("stopOutput() unknown output %d", output);
807        return BAD_VALUE;
808    }
809
810    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
811
812    // handle special case for sonification while in call
813    if (isInCall()) {
814        handleIncallSonification(stream, false, false);
815    }
816
817    if (outputDesc->mRefCount[stream] > 0) {
818        // decrement usage count of this stream on the output
819        outputDesc->changeRefCount(stream, -1);
820        // store time at which the stream was stopped - see isStreamActive()
821        if (outputDesc->mRefCount[stream] == 0) {
822            outputDesc->mStopTime[stream] = systemTime();
823            audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
824            // delay the device switch by twice the latency because stopOutput() is executed when
825            // the track stop() command is received and at that time the audio track buffer can
826            // still contain data that needs to be drained. The latency only covers the audio HAL
827            // and kernel buffers. Also the latency does not always include additional delay in the
828            // audio path (audio DSP, CODEC ...)
829            setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
830
831            // force restoring the device selection on other active outputs if it differs from the
832            // one being selected for this output
833            for (size_t i = 0; i < mOutputs.size(); i++) {
834                audio_io_handle_t curOutput = mOutputs.keyAt(i);
835                AudioOutputDescriptor *desc = mOutputs.valueAt(i);
836                if (curOutput != output &&
837                        desc->isActive() &&
838                        outputDesc->sharesHwModuleWith(desc) &&
839                        (newDevice != desc->device())) {
840                    setOutputDevice(curOutput,
841                                    getNewDevice(curOutput, false /*fromCache*/),
842                                    true,
843                                    outputDesc->mLatency*2);
844                }
845            }
846            // update the outputs if stopping one with a stream that can affect notification routing
847            handleNotificationRoutingForStream(stream);
848        }
849        return NO_ERROR;
850    } else {
851        ALOGW("stopOutput() refcount is already 0 for output %d", output);
852        return INVALID_OPERATION;
853    }
854}
855
856void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
857{
858    ALOGV("releaseOutput() %d", output);
859    ssize_t index = mOutputs.indexOfKey(output);
860    if (index < 0) {
861        ALOGW("releaseOutput() releasing unknown output %d", output);
862        return;
863    }
864
865#ifdef AUDIO_POLICY_TEST
866    int testIndex = testOutputIndex(output);
867    if (testIndex != 0) {
868        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
869        if (outputDesc->isActive()) {
870            mpClientInterface->closeOutput(output);
871            delete mOutputs.valueAt(index);
872            mOutputs.removeItem(output);
873            mTestOutputs[testIndex] = 0;
874        }
875        return;
876    }
877#endif //AUDIO_POLICY_TEST
878
879    AudioOutputDescriptor *desc = mOutputs.valueAt(index);
880    if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
881        if (desc->mDirectOpenCount <= 0) {
882            ALOGW("releaseOutput() invalid open count %d for output %d",
883                                                              desc->mDirectOpenCount, output);
884            return;
885        }
886        if (--desc->mDirectOpenCount == 0) {
887            closeOutput(output);
888            // If effects where present on the output, audioflinger moved them to the primary
889            // output by default: move them back to the appropriate output.
890            audio_io_handle_t dstOutput = getOutputForEffect();
891            if (dstOutput != mPrimaryOutput) {
892                mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
893            }
894        }
895    }
896}
897
898
899audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
900                                    uint32_t samplingRate,
901                                    audio_format_t format,
902                                    audio_channel_mask_t channelMask,
903                                    AudioSystem::audio_in_acoustics acoustics)
904{
905    audio_io_handle_t input = 0;
906    audio_devices_t device = getDeviceForInputSource(inputSource);
907
908    ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
909          inputSource, samplingRate, format, channelMask, acoustics);
910
911    if (device == AUDIO_DEVICE_NONE) {
912        ALOGW("getInput() could not find device for inputSource %d", inputSource);
913        return 0;
914    }
915
916    // adapt channel selection to input source
917    switch(inputSource) {
918    case AUDIO_SOURCE_VOICE_UPLINK:
919        channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
920        break;
921    case AUDIO_SOURCE_VOICE_DOWNLINK:
922        channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
923        break;
924    case AUDIO_SOURCE_VOICE_CALL:
925        channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
926        break;
927    default:
928        break;
929    }
930
931    IOProfile *profile = getInputProfile(device,
932                                         samplingRate,
933                                         format,
934                                         channelMask);
935    if (profile == NULL) {
936        ALOGW("getInput() could not find profile for device 0x%X, samplingRate %d, format %d, "
937                "channelMask 0x%X",
938                device, samplingRate, format, channelMask);
939        return 0;
940    }
941
942    if (profile->mModule->mHandle == 0) {
943        ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
944        return 0;
945    }
946
947    AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
948
949    inputDesc->mInputSource = inputSource;
950    inputDesc->mDevice = device;
951    inputDesc->mSamplingRate = samplingRate;
952    inputDesc->mFormat = format;
953    inputDesc->mChannelMask = channelMask;
954    inputDesc->mRefCount = 0;
955
956    input = mpClientInterface->openInput(profile->mModule->mHandle,
957                                    &inputDesc->mDevice,
958                                    &inputDesc->mSamplingRate,
959                                    &inputDesc->mFormat,
960                                    &inputDesc->mChannelMask);
961
962    // only accept input with the exact requested set of parameters
963    if (input == 0 ||
964        (samplingRate != inputDesc->mSamplingRate) ||
965        (format != inputDesc->mFormat) ||
966        (channelMask != inputDesc->mChannelMask)) {
967        ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask 0x%X",
968                samplingRate, format, channelMask);
969        if (input != 0) {
970            mpClientInterface->closeInput(input);
971        }
972        delete inputDesc;
973        return 0;
974    }
975    addInput(input, inputDesc);
976
977    return input;
978}
979
980status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
981{
982    ALOGV("startInput() input %d", input);
983    ssize_t index = mInputs.indexOfKey(input);
984    if (index < 0) {
985        ALOGW("startInput() unknown input %d", input);
986        return BAD_VALUE;
987    }
988    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
989
990#ifdef AUDIO_POLICY_TEST
991    if (mTestInput == 0)
992#endif //AUDIO_POLICY_TEST
993    {
994        // refuse 2 active AudioRecord clients at the same time except if the active input
995        // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
996        audio_io_handle_t activeInput = getActiveInput();
997        if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
998            AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
999            if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1000                ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1001                stopInput(activeInput);
1002                releaseInput(activeInput);
1003            } else {
1004                ALOGW("startInput() input %d failed: other input already started", input);
1005                return INVALID_OPERATION;
1006            }
1007        }
1008    }
1009
1010    audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1011    if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1012        inputDesc->mDevice = newDevice;
1013    }
1014
1015    // automatically enable the remote submix output when input is started
1016    if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1017        setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1018                AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1019    }
1020
1021    AudioParameter param = AudioParameter();
1022    param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1023
1024    int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1025                                        AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1026
1027    param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1028    ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1029
1030    mpClientInterface->setParameters(input, param.toString());
1031
1032    inputDesc->mRefCount = 1;
1033    return NO_ERROR;
1034}
1035
1036status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
1037{
1038    ALOGV("stopInput() input %d", input);
1039    ssize_t index = mInputs.indexOfKey(input);
1040    if (index < 0) {
1041        ALOGW("stopInput() unknown input %d", input);
1042        return BAD_VALUE;
1043    }
1044    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1045
1046    if (inputDesc->mRefCount == 0) {
1047        ALOGW("stopInput() input %d already stopped", input);
1048        return INVALID_OPERATION;
1049    } else {
1050        // automatically disable the remote submix output when input is stopped
1051        if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1052            setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1053                    AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1054        }
1055
1056        AudioParameter param = AudioParameter();
1057        param.addInt(String8(AudioParameter::keyRouting), 0);
1058        mpClientInterface->setParameters(input, param.toString());
1059        inputDesc->mRefCount = 0;
1060        return NO_ERROR;
1061    }
1062}
1063
1064void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
1065{
1066    ALOGV("releaseInput() %d", input);
1067    ssize_t index = mInputs.indexOfKey(input);
1068    if (index < 0) {
1069        ALOGW("releaseInput() releasing unknown input %d", input);
1070        return;
1071    }
1072    mpClientInterface->closeInput(input);
1073    delete mInputs.valueAt(index);
1074    mInputs.removeItem(input);
1075
1076    ALOGV("releaseInput() exit");
1077}
1078
1079void AudioPolicyManagerBase::closeAllInputs() {
1080    for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1081        mpClientInterface->closeInput(mInputs.keyAt(input_index));
1082    }
1083    mInputs.clear();
1084}
1085
1086void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
1087                                            int indexMin,
1088                                            int indexMax)
1089{
1090    ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1091    if (indexMin < 0 || indexMin >= indexMax) {
1092        ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1093        return;
1094    }
1095    mStreams[stream].mIndexMin = indexMin;
1096    mStreams[stream].mIndexMax = indexMax;
1097}
1098
1099status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
1100                                                      int index,
1101                                                      audio_devices_t device)
1102{
1103
1104    if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1105        return BAD_VALUE;
1106    }
1107    if (!audio_is_output_device(device)) {
1108        return BAD_VALUE;
1109    }
1110
1111    // Force max volume if stream cannot be muted
1112    if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1113
1114    ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1115          stream, device, index);
1116
1117    // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1118    // clear all device specific values
1119    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1120        mStreams[stream].mIndexCur.clear();
1121    }
1122    mStreams[stream].mIndexCur.add(device, index);
1123
1124    // compute and apply stream volume on all outputs according to connected device
1125    status_t status = NO_ERROR;
1126    for (size_t i = 0; i < mOutputs.size(); i++) {
1127        audio_devices_t curDevice =
1128                getDeviceForVolume(mOutputs.valueAt(i)->device());
1129        if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1130            status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1131            if (volStatus != NO_ERROR) {
1132                status = volStatus;
1133            }
1134        }
1135    }
1136    return status;
1137}
1138
1139status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
1140                                                      int *index,
1141                                                      audio_devices_t device)
1142{
1143    if (index == NULL) {
1144        return BAD_VALUE;
1145    }
1146    if (!audio_is_output_device(device)) {
1147        return BAD_VALUE;
1148    }
1149    // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1150    // the strategy the stream belongs to.
1151    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1152        device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1153    }
1154    device = getDeviceForVolume(device);
1155
1156    *index =  mStreams[stream].getVolumeIndex(device);
1157    ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1158    return NO_ERROR;
1159}
1160
1161audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
1162                                            const SortedVector<audio_io_handle_t>& outputs)
1163{
1164    // select one output among several suitable for global effects.
1165    // The priority is as follows:
1166    // 1: An offloaded output. If the effect ends up not being offloadable,
1167    //    AudioFlinger will invalidate the track and the offloaded output
1168    //    will be closed causing the effect to be moved to a PCM output.
1169    // 2: A deep buffer output
1170    // 3: the first output in the list
1171
1172    if (outputs.size() == 0) {
1173        return 0;
1174    }
1175
1176    audio_io_handle_t outputOffloaded = 0;
1177    audio_io_handle_t outputDeepBuffer = 0;
1178
1179    for (size_t i = 0; i < outputs.size(); i++) {
1180        AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1181        ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1182        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1183            outputOffloaded = outputs[i];
1184        }
1185        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1186            outputDeepBuffer = outputs[i];
1187        }
1188    }
1189
1190    ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1191          outputOffloaded, outputDeepBuffer);
1192    if (outputOffloaded != 0) {
1193        return outputOffloaded;
1194    }
1195    if (outputDeepBuffer != 0) {
1196        return outputDeepBuffer;
1197    }
1198
1199    return outputs[0];
1200}
1201
1202audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
1203{
1204    // apply simple rule where global effects are attached to the same output as MUSIC streams
1205
1206    routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1207    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1208    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1209
1210    audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1211    ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1212          output, (desc == NULL) ? "unspecified" : desc->name,  (desc == NULL) ? 0 : desc->flags);
1213
1214    return output;
1215}
1216
1217status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
1218                                audio_io_handle_t io,
1219                                uint32_t strategy,
1220                                int session,
1221                                int id)
1222{
1223    ssize_t index = mOutputs.indexOfKey(io);
1224    if (index < 0) {
1225        index = mInputs.indexOfKey(io);
1226        if (index < 0) {
1227            ALOGW("registerEffect() unknown io %d", io);
1228            return INVALID_OPERATION;
1229        }
1230    }
1231
1232    if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1233        ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1234                desc->name, desc->memoryUsage);
1235        return INVALID_OPERATION;
1236    }
1237    mTotalEffectsMemory += desc->memoryUsage;
1238    ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1239            desc->name, io, strategy, session, id);
1240    ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1241
1242    EffectDescriptor *pDesc = new EffectDescriptor();
1243    memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1244    pDesc->mIo = io;
1245    pDesc->mStrategy = (routing_strategy)strategy;
1246    pDesc->mSession = session;
1247    pDesc->mEnabled = false;
1248
1249    mEffects.add(id, pDesc);
1250
1251    return NO_ERROR;
1252}
1253
1254status_t AudioPolicyManagerBase::unregisterEffect(int id)
1255{
1256    ssize_t index = mEffects.indexOfKey(id);
1257    if (index < 0) {
1258        ALOGW("unregisterEffect() unknown effect ID %d", id);
1259        return INVALID_OPERATION;
1260    }
1261
1262    EffectDescriptor *pDesc = mEffects.valueAt(index);
1263
1264    setEffectEnabled(pDesc, false);
1265
1266    if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1267        ALOGW("unregisterEffect() memory %d too big for total %d",
1268                pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1269        pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1270    }
1271    mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1272    ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1273            pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1274
1275    mEffects.removeItem(id);
1276    delete pDesc;
1277
1278    return NO_ERROR;
1279}
1280
1281status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1282{
1283    ssize_t index = mEffects.indexOfKey(id);
1284    if (index < 0) {
1285        ALOGW("unregisterEffect() unknown effect ID %d", id);
1286        return INVALID_OPERATION;
1287    }
1288
1289    return setEffectEnabled(mEffects.valueAt(index), enabled);
1290}
1291
1292status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1293{
1294    if (enabled == pDesc->mEnabled) {
1295        ALOGV("setEffectEnabled(%s) effect already %s",
1296             enabled?"true":"false", enabled?"enabled":"disabled");
1297        return INVALID_OPERATION;
1298    }
1299
1300    if (enabled) {
1301        if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1302            ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1303                 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1304            return INVALID_OPERATION;
1305        }
1306        mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1307        ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1308    } else {
1309        if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1310            ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1311                    pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1312            pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1313        }
1314        mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1315        ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1316    }
1317    pDesc->mEnabled = enabled;
1318    return NO_ERROR;
1319}
1320
1321bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
1322{
1323    for (size_t i = 0; i < mEffects.size(); i++) {
1324        const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1325        if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1326                ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1327            ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1328                  pDesc->mDesc.name, pDesc->mSession);
1329            return true;
1330        }
1331    }
1332    return false;
1333}
1334
1335bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1336{
1337    nsecs_t sysTime = systemTime();
1338    for (size_t i = 0; i < mOutputs.size(); i++) {
1339        const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1340        if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1341            return true;
1342        }
1343    }
1344    return false;
1345}
1346
1347bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
1348{
1349    nsecs_t sysTime = systemTime();
1350    for (size_t i = 0; i < mOutputs.size(); i++) {
1351        const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1352        if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1353                outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
1354            return true;
1355        }
1356    }
1357    return false;
1358}
1359
1360bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
1361{
1362    for (size_t i = 0; i < mInputs.size(); i++) {
1363        const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1364        if ((inputDescriptor->mInputSource == (int)source ||
1365                (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
1366                 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1367             && (inputDescriptor->mRefCount > 0)) {
1368            return true;
1369        }
1370    }
1371    return false;
1372}
1373
1374
1375status_t AudioPolicyManagerBase::dump(int fd)
1376{
1377    const size_t SIZE = 256;
1378    char buffer[SIZE];
1379    String8 result;
1380
1381    snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1382    result.append(buffer);
1383
1384    snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1385    result.append(buffer);
1386    snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1387    result.append(buffer);
1388    snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1389    result.append(buffer);
1390    snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbOutCardAndDevice.string());
1391    result.append(buffer);
1392    snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1393    result.append(buffer);
1394    snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1395    result.append(buffer);
1396    snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1397    result.append(buffer);
1398    snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1399    result.append(buffer);
1400    snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1401    result.append(buffer);
1402    snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1403    result.append(buffer);
1404    snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1405    result.append(buffer);
1406    snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
1407    result.append(buffer);
1408    write(fd, result.string(), result.size());
1409
1410
1411    snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1412    write(fd, buffer, strlen(buffer));
1413    for (size_t i = 0; i < mHwModules.size(); i++) {
1414        snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1415        write(fd, buffer, strlen(buffer));
1416        mHwModules[i]->dump(fd);
1417    }
1418
1419    snprintf(buffer, SIZE, "\nOutputs dump:\n");
1420    write(fd, buffer, strlen(buffer));
1421    for (size_t i = 0; i < mOutputs.size(); i++) {
1422        snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1423        write(fd, buffer, strlen(buffer));
1424        mOutputs.valueAt(i)->dump(fd);
1425    }
1426
1427    snprintf(buffer, SIZE, "\nInputs dump:\n");
1428    write(fd, buffer, strlen(buffer));
1429    for (size_t i = 0; i < mInputs.size(); i++) {
1430        snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1431        write(fd, buffer, strlen(buffer));
1432        mInputs.valueAt(i)->dump(fd);
1433    }
1434
1435    snprintf(buffer, SIZE, "\nStreams dump:\n");
1436    write(fd, buffer, strlen(buffer));
1437    snprintf(buffer, SIZE,
1438             " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
1439    write(fd, buffer, strlen(buffer));
1440    for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1441        snprintf(buffer, SIZE, " %02zu      ", i);
1442        write(fd, buffer, strlen(buffer));
1443        mStreams[i].dump(fd);
1444    }
1445
1446    snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1447            (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1448    write(fd, buffer, strlen(buffer));
1449
1450    snprintf(buffer, SIZE, "Registered effects:\n");
1451    write(fd, buffer, strlen(buffer));
1452    for (size_t i = 0; i < mEffects.size(); i++) {
1453        snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1454        write(fd, buffer, strlen(buffer));
1455        mEffects.valueAt(i)->dump(fd);
1456    }
1457
1458
1459    return NO_ERROR;
1460}
1461
1462// This function checks for the parameters which can be offloaded.
1463// This can be enhanced depending on the capability of the DSP and policy
1464// of the system.
1465bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1466{
1467    ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1468     " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1469     offloadInfo.sample_rate, offloadInfo.channel_mask,
1470     offloadInfo.format,
1471     offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1472     offloadInfo.has_video);
1473
1474    // Check if offload has been disabled
1475    char propValue[PROPERTY_VALUE_MAX];
1476    if (property_get("audio.offload.disable", propValue, "0")) {
1477        if (atoi(propValue) != 0) {
1478            ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1479            return false;
1480        }
1481    }
1482
1483    // Check if stream type is music, then only allow offload as of now.
1484    if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1485    {
1486        ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1487        return false;
1488    }
1489
1490    //TODO: enable audio offloading with video when ready
1491    if (offloadInfo.has_video)
1492    {
1493        ALOGV("isOffloadSupported: has_video == true, returning false");
1494        return false;
1495    }
1496
1497    //If duration is less than minimum value defined in property, return false
1498    if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1499        if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1500            ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1501            return false;
1502        }
1503    } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1504        ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1505        return false;
1506    }
1507
1508    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1509    // creating an offloaded track and tearing it down immediately after start when audioflinger
1510    // detects there is an active non offloadable effect.
1511    // FIXME: We should check the audio session here but we do not have it in this context.
1512    // This may prevent offloading in rare situations where effects are left active by apps
1513    // in the background.
1514    if (isNonOffloadableEffectEnabled()) {
1515        return false;
1516    }
1517
1518    // See if there is a profile to support this.
1519    // AUDIO_DEVICE_NONE
1520    IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1521                                            offloadInfo.sample_rate,
1522                                            offloadInfo.format,
1523                                            offloadInfo.channel_mask,
1524                                            AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1525    ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1526    return (profile != NULL);
1527}
1528
1529// ----------------------------------------------------------------------------
1530// AudioPolicyManagerBase
1531// ----------------------------------------------------------------------------
1532
1533AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1534    :
1535#ifdef AUDIO_POLICY_TEST
1536    Thread(false),
1537#endif //AUDIO_POLICY_TEST
1538    mPrimaryOutput((audio_io_handle_t)0),
1539    mAvailableOutputDevices(AUDIO_DEVICE_NONE),
1540    mPhoneState(AudioSystem::MODE_NORMAL),
1541    mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1542    mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1543    mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
1544    mSpeakerDrcEnabled(false)
1545{
1546    mpClientInterface = clientInterface;
1547
1548    for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1549        mForceUse[i] = AudioSystem::FORCE_NONE;
1550    }
1551
1552    mA2dpDeviceAddress = String8("");
1553    mScoDeviceAddress = String8("");
1554    mUsbOutCardAndDevice = String8("");
1555
1556    if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1557        if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1558            ALOGE("could not load audio policy configuration file, setting defaults");
1559            defaultAudioPolicyConfig();
1560        }
1561    }
1562
1563    // must be done after reading the policy
1564    initializeVolumeCurves();
1565
1566    // open all output streams needed to access attached devices
1567    for (size_t i = 0; i < mHwModules.size(); i++) {
1568        mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1569        if (mHwModules[i]->mHandle == 0) {
1570            ALOGW("could not open HW module %s", mHwModules[i]->mName);
1571            continue;
1572        }
1573        // open all output streams needed to access attached devices
1574        // except for direct output streams that are only opened when they are actually
1575        // required by an app.
1576        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1577        {
1578            const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1579
1580            if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
1581                    ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1582                AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1583                outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1584                                                            outProfile->mSupportedDevices);
1585                audio_io_handle_t output = mpClientInterface->openOutput(
1586                                                outProfile->mModule->mHandle,
1587                                                &outputDesc->mDevice,
1588                                                &outputDesc->mSamplingRate,
1589                                                &outputDesc->mFormat,
1590                                                &outputDesc->mChannelMask,
1591                                                &outputDesc->mLatency,
1592                                                outputDesc->mFlags);
1593                if (output == 0) {
1594                    delete outputDesc;
1595                } else {
1596                    mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1597                                            (outProfile->mSupportedDevices & mAttachedOutputDevices));
1598                    if (mPrimaryOutput == 0 &&
1599                            outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1600                        mPrimaryOutput = output;
1601                    }
1602                    addOutput(output, outputDesc);
1603                    setOutputDevice(output,
1604                                    (audio_devices_t)(mDefaultOutputDevice &
1605                                                        outProfile->mSupportedDevices),
1606                                    true);
1607                }
1608            }
1609        }
1610    }
1611
1612    ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1613             "Not output found for attached devices %08x",
1614             (mAttachedOutputDevices & ~mAvailableOutputDevices));
1615
1616    ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1617
1618    updateDevicesAndOutputs();
1619
1620#ifdef AUDIO_POLICY_TEST
1621    if (mPrimaryOutput != 0) {
1622        AudioParameter outputCmd = AudioParameter();
1623        outputCmd.addInt(String8("set_id"), 0);
1624        mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1625
1626        mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1627        mTestSamplingRate = 44100;
1628        mTestFormat = AudioSystem::PCM_16_BIT;
1629        mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
1630        mTestLatencyMs = 0;
1631        mCurOutput = 0;
1632        mDirectOutput = false;
1633        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1634            mTestOutputs[i] = 0;
1635        }
1636
1637        const size_t SIZE = 256;
1638        char buffer[SIZE];
1639        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1640        run(buffer, ANDROID_PRIORITY_AUDIO);
1641    }
1642#endif //AUDIO_POLICY_TEST
1643}
1644
1645AudioPolicyManagerBase::~AudioPolicyManagerBase()
1646{
1647#ifdef AUDIO_POLICY_TEST
1648    exit();
1649#endif //AUDIO_POLICY_TEST
1650   for (size_t i = 0; i < mOutputs.size(); i++) {
1651        mpClientInterface->closeOutput(mOutputs.keyAt(i));
1652        delete mOutputs.valueAt(i);
1653   }
1654   for (size_t i = 0; i < mInputs.size(); i++) {
1655        mpClientInterface->closeInput(mInputs.keyAt(i));
1656        delete mInputs.valueAt(i);
1657   }
1658   for (size_t i = 0; i < mHwModules.size(); i++) {
1659        delete mHwModules[i];
1660   }
1661}
1662
1663status_t AudioPolicyManagerBase::initCheck()
1664{
1665    return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1666}
1667
1668#ifdef AUDIO_POLICY_TEST
1669bool AudioPolicyManagerBase::threadLoop()
1670{
1671    ALOGV("entering threadLoop()");
1672    while (!exitPending())
1673    {
1674        String8 command;
1675        int valueInt;
1676        String8 value;
1677
1678        Mutex::Autolock _l(mLock);
1679        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1680
1681        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1682        AudioParameter param = AudioParameter(command);
1683
1684        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1685            valueInt != 0) {
1686            ALOGV("Test command %s received", command.string());
1687            String8 target;
1688            if (param.get(String8("target"), target) != NO_ERROR) {
1689                target = "Manager";
1690            }
1691            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1692                param.remove(String8("test_cmd_policy_output"));
1693                mCurOutput = valueInt;
1694            }
1695            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1696                param.remove(String8("test_cmd_policy_direct"));
1697                if (value == "false") {
1698                    mDirectOutput = false;
1699                } else if (value == "true") {
1700                    mDirectOutput = true;
1701                }
1702            }
1703            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1704                param.remove(String8("test_cmd_policy_input"));
1705                mTestInput = valueInt;
1706            }
1707
1708            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1709                param.remove(String8("test_cmd_policy_format"));
1710                int format = AudioSystem::INVALID_FORMAT;
1711                if (value == "PCM 16 bits") {
1712                    format = AudioSystem::PCM_16_BIT;
1713                } else if (value == "PCM 8 bits") {
1714                    format = AudioSystem::PCM_8_BIT;
1715                } else if (value == "Compressed MP3") {
1716                    format = AudioSystem::MP3;
1717                }
1718                if (format != AudioSystem::INVALID_FORMAT) {
1719                    if (target == "Manager") {
1720                        mTestFormat = format;
1721                    } else if (mTestOutputs[mCurOutput] != 0) {
1722                        AudioParameter outputParam = AudioParameter();
1723                        outputParam.addInt(String8("format"), format);
1724                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1725                    }
1726                }
1727            }
1728            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1729                param.remove(String8("test_cmd_policy_channels"));
1730                int channels = 0;
1731
1732                if (value == "Channels Stereo") {
1733                    channels =  AudioSystem::CHANNEL_OUT_STEREO;
1734                } else if (value == "Channels Mono") {
1735                    channels =  AudioSystem::CHANNEL_OUT_MONO;
1736                }
1737                if (channels != 0) {
1738                    if (target == "Manager") {
1739                        mTestChannels = channels;
1740                    } else if (mTestOutputs[mCurOutput] != 0) {
1741                        AudioParameter outputParam = AudioParameter();
1742                        outputParam.addInt(String8("channels"), channels);
1743                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1744                    }
1745                }
1746            }
1747            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1748                param.remove(String8("test_cmd_policy_sampleRate"));
1749                if (valueInt >= 0 && valueInt <= 96000) {
1750                    int samplingRate = valueInt;
1751                    if (target == "Manager") {
1752                        mTestSamplingRate = samplingRate;
1753                    } else if (mTestOutputs[mCurOutput] != 0) {
1754                        AudioParameter outputParam = AudioParameter();
1755                        outputParam.addInt(String8("sampling_rate"), samplingRate);
1756                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1757                    }
1758                }
1759            }
1760
1761            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1762                param.remove(String8("test_cmd_policy_reopen"));
1763
1764                AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1765                mpClientInterface->closeOutput(mPrimaryOutput);
1766
1767                audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1768
1769                delete mOutputs.valueFor(mPrimaryOutput);
1770                mOutputs.removeItem(mPrimaryOutput);
1771
1772                AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1773                outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1774                mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1775                                                &outputDesc->mDevice,
1776                                                &outputDesc->mSamplingRate,
1777                                                &outputDesc->mFormat,
1778                                                &outputDesc->mChannelMask,
1779                                                &outputDesc->mLatency,
1780                                                outputDesc->mFlags);
1781                if (mPrimaryOutput == 0) {
1782                    ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1783                            outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1784                } else {
1785                    AudioParameter outputCmd = AudioParameter();
1786                    outputCmd.addInt(String8("set_id"), 0);
1787                    mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1788                    addOutput(mPrimaryOutput, outputDesc);
1789                }
1790            }
1791
1792
1793            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1794        }
1795    }
1796    return false;
1797}
1798
1799void AudioPolicyManagerBase::exit()
1800{
1801    {
1802        AutoMutex _l(mLock);
1803        requestExit();
1804        mWaitWorkCV.signal();
1805    }
1806    requestExitAndWait();
1807}
1808
1809int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1810{
1811    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1812        if (output == mTestOutputs[i]) return i;
1813    }
1814    return 0;
1815}
1816#endif //AUDIO_POLICY_TEST
1817
1818// ---
1819
1820void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1821{
1822    outputDesc->mId = id;
1823    mOutputs.add(id, outputDesc);
1824}
1825
1826void AudioPolicyManagerBase::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
1827{
1828    inputDesc->mId = id;
1829    mInputs.add(id, inputDesc);
1830}
1831
1832status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1833                                                       AudioSystem::device_connection_state state,
1834                                                       SortedVector<audio_io_handle_t>& outputs,
1835                                                       const String8 paramStr)
1836{
1837    AudioOutputDescriptor *desc;
1838
1839    if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1840        // first list already open outputs that can be routed to this device
1841        for (size_t i = 0; i < mOutputs.size(); i++) {
1842            desc = mOutputs.valueAt(i);
1843            if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1844                ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1845                outputs.add(mOutputs.keyAt(i));
1846            }
1847        }
1848        // then look for output profiles that can be routed to this device
1849        SortedVector<IOProfile *> profiles;
1850        for (size_t i = 0; i < mHwModules.size(); i++)
1851        {
1852            if (mHwModules[i]->mHandle == 0) {
1853                continue;
1854            }
1855            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1856            {
1857                if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1858                    ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
1859                    profiles.add(mHwModules[i]->mOutputProfiles[j]);
1860                }
1861            }
1862        }
1863
1864        if (profiles.isEmpty() && outputs.isEmpty()) {
1865            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1866            return BAD_VALUE;
1867        }
1868
1869        // open outputs for matching profiles if needed. Direct outputs are also opened to
1870        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1871        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1872            IOProfile *profile = profiles[profile_index];
1873
1874            // nothing to do if one output is already opened for this profile
1875            size_t j;
1876            for (j = 0; j < mOutputs.size(); j++) {
1877                desc = mOutputs.valueAt(j);
1878                if (!desc->isDuplicated() && desc->mProfile == profile) {
1879                    break;
1880                }
1881            }
1882            if (j != mOutputs.size()) {
1883                continue;
1884            }
1885
1886            ALOGV("opening output for device %08x with params %s", device, paramStr.string());
1887            desc = new AudioOutputDescriptor(profile);
1888            desc->mDevice = device;
1889            audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1890            offloadInfo.sample_rate = desc->mSamplingRate;
1891            offloadInfo.format = desc->mFormat;
1892            offloadInfo.channel_mask = desc->mChannelMask;
1893
1894            audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1895                                                                       &desc->mDevice,
1896                                                                       &desc->mSamplingRate,
1897                                                                       &desc->mFormat,
1898                                                                       &desc->mChannelMask,
1899                                                                       &desc->mLatency,
1900                                                                       desc->mFlags,
1901                                                                       &offloadInfo);
1902            if (output != 0) {
1903                if (!paramStr.isEmpty()) {
1904                    // Here is where the out_set_parameters() for card & device gets called
1905                    mpClientInterface->setParameters(output, paramStr);
1906                }
1907
1908                // Here is where we step through and resolve any "dynamic" fields
1909                String8 reply;
1910                char *value;
1911                if (profile->mSamplingRates[0] == 0) {
1912                    reply = mpClientInterface->getParameters(output,
1913                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1914                    ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1915                              reply.string());
1916                    value = strpbrk((char *)reply.string(), "=");
1917                    if (value != NULL) {
1918                        loadSamplingRates(value + 1, profile);
1919                    }
1920                }
1921                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
1922                    reply = mpClientInterface->getParameters(output,
1923                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1924                    ALOGV("checkOutputsForDevice() direct output sup formats %s",
1925                              reply.string());
1926                    value = strpbrk((char *)reply.string(), "=");
1927                    if (value != NULL) {
1928                        loadFormats(value + 1, profile);
1929                    }
1930                }
1931                if (profile->mChannelMasks[0] == 0) {
1932                    reply = mpClientInterface->getParameters(output,
1933                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1934                    ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1935                              reply.string());
1936                    value = strpbrk((char *)reply.string(), "=");
1937                    if (value != NULL) {
1938                        loadOutChannels(value + 1, profile);
1939                    }
1940                }
1941                if (((profile->mSamplingRates[0] == 0) &&
1942                         (profile->mSamplingRates.size() < 2)) ||
1943                     ((profile->mFormats[0] == 0) &&
1944                         (profile->mFormats.size() < 2)) ||
1945                     ((profile->mChannelMasks[0] == 0) &&
1946                         (profile->mChannelMasks.size() < 2))) {
1947                    ALOGW("checkOutputsForDevice() direct output missing param");
1948                    mpClientInterface->closeOutput(output);
1949                    output = 0;
1950                } else if (profile->mSamplingRates[0] == 0) {
1951                    mpClientInterface->closeOutput(output);
1952                    desc->mSamplingRate = profile->mSamplingRates[1];
1953                    offloadInfo.sample_rate = desc->mSamplingRate;
1954                    output = mpClientInterface->openOutput(
1955                                                    profile->mModule->mHandle,
1956                                                    &desc->mDevice,
1957                                                    &desc->mSamplingRate,
1958                                                    &desc->mFormat,
1959                                                    &desc->mChannelMask,
1960                                                    &desc->mLatency,
1961                                                    desc->mFlags,
1962                                                    &offloadInfo);
1963                }
1964
1965                if (output != 0) {
1966                    addOutput(output, desc);
1967                    if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
1968                        audio_io_handle_t duplicatedOutput = 0;
1969
1970                        // set initial stream volume for device
1971                        applyStreamVolumes(output, device, 0, true);
1972
1973                        //TODO: configure audio effect output stage here
1974
1975                        // open a duplicating output thread for the new output and the primary output
1976                        duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1977                                                                                  mPrimaryOutput);
1978                        if (duplicatedOutput != 0) {
1979                            // add duplicated output descriptor
1980                            AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1981                            dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1982                            dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1983                            dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1984                            dupOutputDesc->mFormat = desc->mFormat;
1985                            dupOutputDesc->mChannelMask = desc->mChannelMask;
1986                            dupOutputDesc->mLatency = desc->mLatency;
1987                            addOutput(duplicatedOutput, dupOutputDesc);
1988                            applyStreamVolumes(duplicatedOutput, device, 0, true);
1989                        } else {
1990                            ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1991                                    mPrimaryOutput, output);
1992                            mpClientInterface->closeOutput(output);
1993                            mOutputs.removeItem(output);
1994                            output = 0;
1995                        }
1996                    }
1997                }
1998            }
1999            if (output == 0) {
2000                ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2001                delete desc;
2002                profiles.removeAt(profile_index);
2003                profile_index--;
2004            } else {
2005                outputs.add(output);
2006                ALOGV("checkOutputsForDevice(): adding output %d", output);
2007            }
2008        }
2009
2010        if (profiles.isEmpty()) {
2011            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2012            return BAD_VALUE;
2013        }
2014    } else { // Disconnect
2015        // check if one opened output is not needed any more after disconnecting one device
2016        for (size_t i = 0; i < mOutputs.size(); i++) {
2017            desc = mOutputs.valueAt(i);
2018            if (!desc->isDuplicated() &&
2019                    !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
2020                ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2021                outputs.add(mOutputs.keyAt(i));
2022            }
2023        }
2024        // Clear any profiles associated with the disconnected device.
2025        for (size_t i = 0; i < mHwModules.size(); i++)
2026        {
2027            if (mHwModules[i]->mHandle == 0) {
2028                continue;
2029            }
2030            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2031            {
2032                IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2033                if (profile->mSupportedDevices & device) {
2034                    ALOGV("checkOutputsForDevice(): clearing direct output profile %zu on module %zu",
2035                          j, i);
2036                    if (profile->mSamplingRates[0] == 0) {
2037                        profile->mSamplingRates.clear();
2038                        profile->mSamplingRates.add(0);
2039                    }
2040                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2041                        profile->mFormats.clear();
2042                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2043                    }
2044                    if (profile->mChannelMasks[0] == 0) {
2045                        profile->mChannelMasks.clear();
2046                        profile->mChannelMasks.add(0);
2047                    }
2048                }
2049            }
2050        }
2051    }
2052    return NO_ERROR;
2053}
2054
2055status_t AudioPolicyManagerBase::checkInputsForDevice(audio_devices_t device,
2056                                                      AudioSystem::device_connection_state state,
2057                                                      SortedVector<audio_io_handle_t>& inputs,
2058                                                      const String8 paramStr)
2059{
2060    AudioInputDescriptor *desc;
2061    if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
2062        // first list already open inputs that can be routed to this device
2063        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2064            desc = mInputs.valueAt(input_index);
2065            if (desc->mProfile->mSupportedDevices & (device & ~AUDIO_DEVICE_BIT_IN)) {
2066                ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2067               inputs.add(mInputs.keyAt(input_index));
2068            }
2069        }
2070
2071        // then look for input profiles that can be routed to this device
2072        SortedVector<IOProfile *> profiles;
2073        for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2074        {
2075            if (mHwModules[module_index]->mHandle == 0) {
2076                continue;
2077            }
2078            for (size_t profile_index = 0;
2079                 profile_index < mHwModules[module_index]->mInputProfiles.size();
2080                 profile_index++)
2081            {
2082                if (mHwModules[module_index]->mInputProfiles[profile_index]->mSupportedDevices
2083                        & (device & ~AUDIO_DEVICE_BIT_IN)) {
2084                    ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2085                          profile_index, module_index);
2086                    profiles.add(mHwModules[module_index]->mInputProfiles[profile_index]);
2087                }
2088            }
2089        }
2090
2091        if (profiles.isEmpty() && inputs.isEmpty()) {
2092            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2093            return BAD_VALUE;
2094        }
2095
2096        // open inputs for matching profiles if needed. Direct inputs are also opened to
2097        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2098        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2099
2100            IOProfile *profile = profiles[profile_index];
2101            // nothing to do if one input is already opened for this profile
2102            size_t input_index;
2103            for (input_index = 0; input_index < mInputs.size(); input_index++) {
2104                desc = mInputs.valueAt(input_index);
2105                if (desc->mProfile == profile) {
2106                    break;
2107                }
2108            }
2109            if (input_index != mInputs.size()) {
2110                continue;
2111            }
2112
2113            ALOGV("opening input for device 0x%X with params %s", device, paramStr.string());
2114            desc = new AudioInputDescriptor(profile);
2115            desc->mDevice = device;
2116
2117            audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2118                                            &desc->mDevice,
2119                                            &desc->mSamplingRate,
2120                                            &desc->mFormat,
2121                                            &desc->mChannelMask);
2122
2123            if (input != 0) {
2124                if (!paramStr.isEmpty()) {
2125                    mpClientInterface->setParameters(input, paramStr);
2126                }
2127
2128                // Here is where we step through and resolve any "dynamic" fields
2129                String8 reply;
2130                char *value;
2131                if (profile->mSamplingRates[0] == 0) {
2132                    reply = mpClientInterface->getParameters(input,
2133                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2134                    ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2135                              reply.string());
2136                    value = strpbrk((char *)reply.string(), "=");
2137                    if (value != NULL) {
2138                        loadSamplingRates(value + 1, profile);
2139                    }
2140                }
2141                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2142                    reply = mpClientInterface->getParameters(input,
2143                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2144                    ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2145                    value = strpbrk((char *)reply.string(), "=");
2146                    if (value != NULL) {
2147                        loadFormats(value + 1, profile);
2148                    }
2149                }
2150                if (profile->mChannelMasks[0] == 0) {
2151                    reply = mpClientInterface->getParameters(input,
2152                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2153                    ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2154                              reply.string());
2155                    value = strpbrk((char *)reply.string(), "=");
2156                    if (value != NULL) {
2157                        loadInChannels(value + 1, profile);
2158                    }
2159                }
2160                if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2161                     ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2162                     ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2163                    ALOGW("checkInputsForDevice() direct input missing param");
2164                    mpClientInterface->closeInput(input);
2165                    input = 0;
2166                }
2167
2168                if (input != 0) {
2169                    addInput(input, desc);
2170                }
2171            } // endif input != 0
2172
2173            if (input == 0) {
2174                ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2175                delete desc;
2176                profiles.removeAt(profile_index);
2177                profile_index--;
2178            } else {
2179                inputs.add(input);
2180                ALOGV("checkInputsForDevice(): adding input %d", input);
2181            }
2182        } // end scan profiles
2183
2184        if (profiles.isEmpty()) {
2185            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2186            return BAD_VALUE;
2187        }
2188    } else {
2189        // Disconnect
2190        // check if one opened input is not needed any more after disconnecting one device
2191        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2192            desc = mInputs.valueAt(input_index);
2193            if (!(desc->mProfile->mSupportedDevices & mAvailableInputDevices)) {
2194                ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2195                      mInputs.keyAt(input_index));
2196                inputs.add(mInputs.keyAt(input_index));
2197            }
2198        }
2199        // Clear any profiles associated with the disconnected device.
2200        for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
2201        {
2202            if (mHwModules[module_index]->mHandle == 0) {
2203                continue;
2204            }
2205            for (size_t profile_index = 0;
2206                 profile_index < mHwModules[module_index]->mInputProfiles.size();
2207                 profile_index++)
2208            {
2209                IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
2210                if (profile->mSupportedDevices & device) {
2211                    ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2212                          profile_index, module_index);
2213                    if (profile->mSamplingRates[0] == 0) {
2214                        profile->mSamplingRates.clear();
2215                        profile->mSamplingRates.add(0);
2216                    }
2217                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2218                        profile->mFormats.clear();
2219                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2220                    }
2221                    if (profile->mChannelMasks[0] == 0) {
2222                        profile->mChannelMasks.clear();
2223                        profile->mChannelMasks.add(0);
2224                    }
2225                }
2226            }
2227        }
2228    } // end disconnect
2229
2230    return NO_ERROR;
2231}
2232
2233void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
2234{
2235    ALOGV("closeOutput(%d)", output);
2236
2237    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2238    if (outputDesc == NULL) {
2239        ALOGW("closeOutput() unknown output %d", output);
2240        return;
2241    }
2242
2243    // look for duplicated outputs connected to the output being removed.
2244    for (size_t i = 0; i < mOutputs.size(); i++) {
2245        AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2246        if (dupOutputDesc->isDuplicated() &&
2247                (dupOutputDesc->mOutput1 == outputDesc ||
2248                dupOutputDesc->mOutput2 == outputDesc)) {
2249            AudioOutputDescriptor *outputDesc2;
2250            if (dupOutputDesc->mOutput1 == outputDesc) {
2251                outputDesc2 = dupOutputDesc->mOutput2;
2252            } else {
2253                outputDesc2 = dupOutputDesc->mOutput1;
2254            }
2255            // As all active tracks on duplicated output will be deleted,
2256            // and as they were also referenced on the other output, the reference
2257            // count for their stream type must be adjusted accordingly on
2258            // the other output.
2259            for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
2260                int refCount = dupOutputDesc->mRefCount[j];
2261                outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
2262            }
2263            audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2264            ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2265
2266            mpClientInterface->closeOutput(duplicatedOutput);
2267            delete mOutputs.valueFor(duplicatedOutput);
2268            mOutputs.removeItem(duplicatedOutput);
2269        }
2270    }
2271
2272    AudioParameter param;
2273    param.add(String8("closing"), String8("true"));
2274    mpClientInterface->setParameters(output, param.toString());
2275
2276    mpClientInterface->closeOutput(output);
2277    delete outputDesc;
2278    mOutputs.removeItem(output);
2279    mPreviousOutputs = mOutputs;
2280}
2281
2282SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
2283                        DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2284{
2285    SortedVector<audio_io_handle_t> outputs;
2286
2287    ALOGVV("getOutputsForDevice() device %04x", device);
2288    for (size_t i = 0; i < openOutputs.size(); i++) {
2289        ALOGVV("output %d isDuplicated=%d device=%04x",
2290                i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2291        if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2292            ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2293            outputs.add(openOutputs.keyAt(i));
2294        }
2295    }
2296    return outputs;
2297}
2298
2299bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2300                                   SortedVector<audio_io_handle_t>& outputs2)
2301{
2302    if (outputs1.size() != outputs2.size()) {
2303        return false;
2304    }
2305    for (size_t i = 0; i < outputs1.size(); i++) {
2306        if (outputs1[i] != outputs2[i]) {
2307            return false;
2308        }
2309    }
2310    return true;
2311}
2312
2313void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
2314{
2315    audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2316    audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2317    SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2318    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2319
2320    if (!vectorsEqual(srcOutputs,dstOutputs)) {
2321        ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2322              strategy, srcOutputs[0], dstOutputs[0]);
2323        // mute strategy while moving tracks from one output to another
2324        for (size_t i = 0; i < srcOutputs.size(); i++) {
2325            AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2326            if (desc->isStrategyActive(strategy)) {
2327                setStrategyMute(strategy, true, srcOutputs[i]);
2328                setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2329            }
2330        }
2331
2332        // Move effects associated to this strategy from previous output to new output
2333        if (strategy == STRATEGY_MEDIA) {
2334            audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2335            SortedVector<audio_io_handle_t> moved;
2336            for (size_t i = 0; i < mEffects.size(); i++) {
2337                EffectDescriptor *desc = mEffects.valueAt(i);
2338                if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2339                        desc->mIo != fxOutput) {
2340                    if (moved.indexOf(desc->mIo) < 0) {
2341                        ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2342                              mEffects.keyAt(i), fxOutput);
2343                        mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2344                                                       fxOutput);
2345                        moved.add(desc->mIo);
2346                    }
2347                    desc->mIo = fxOutput;
2348                }
2349            }
2350        }
2351        // Move tracks associated to this strategy from previous output to new output
2352        for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2353            if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2354                mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
2355            }
2356        }
2357    }
2358}
2359
2360void AudioPolicyManagerBase::checkOutputForAllStrategies()
2361{
2362    checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2363    checkOutputForStrategy(STRATEGY_PHONE);
2364    checkOutputForStrategy(STRATEGY_SONIFICATION);
2365    checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2366    checkOutputForStrategy(STRATEGY_MEDIA);
2367    checkOutputForStrategy(STRATEGY_DTMF);
2368}
2369
2370audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
2371{
2372    if (!mHasA2dp) {
2373        return 0;
2374    }
2375
2376    for (size_t i = 0; i < mOutputs.size(); i++) {
2377        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2378        if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2379            return mOutputs.keyAt(i);
2380        }
2381    }
2382
2383    return 0;
2384}
2385
2386void AudioPolicyManagerBase::checkA2dpSuspend()
2387{
2388    if (!mHasA2dp) {
2389        return;
2390    }
2391    audio_io_handle_t a2dpOutput = getA2dpOutput();
2392    if (a2dpOutput == 0) {
2393        return;
2394    }
2395
2396    // suspend A2DP output if:
2397    //      (NOT already suspended) &&
2398    //      ((SCO device is connected &&
2399    //       (forced usage for communication || for record is SCO))) ||
2400    //      (phone state is ringing || in call)
2401    //
2402    // restore A2DP output if:
2403    //      (Already suspended) &&
2404    //      ((SCO device is NOT connected ||
2405    //       (forced usage NOT for communication && NOT for record is SCO))) &&
2406    //      (phone state is NOT ringing && NOT in call)
2407    //
2408    if (mA2dpSuspended) {
2409        if (((mScoDeviceAddress == "") ||
2410             ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
2411              (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
2412             ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
2413              (mPhoneState != AudioSystem::MODE_RINGTONE))) {
2414
2415            mpClientInterface->restoreOutput(a2dpOutput);
2416            mA2dpSuspended = false;
2417        }
2418    } else {
2419        if (((mScoDeviceAddress != "") &&
2420             ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2421              (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
2422             ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
2423              (mPhoneState == AudioSystem::MODE_RINGTONE))) {
2424
2425            mpClientInterface->suspendOutput(a2dpOutput);
2426            mA2dpSuspended = true;
2427        }
2428    }
2429}
2430
2431audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
2432{
2433    audio_devices_t device = AUDIO_DEVICE_NONE;
2434
2435    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2436    // check the following by order of priority to request a routing change if necessary:
2437    // 1: the strategy enforced audible is active on the output:
2438    //      use device for strategy enforced audible
2439    // 2: we are in call or the strategy phone is active on the output:
2440    //      use device for strategy phone
2441    // 3: the strategy sonification is active on the output:
2442    //      use device for strategy sonification
2443    // 4: the strategy "respectful" sonification is active on the output:
2444    //      use device for strategy "respectful" sonification
2445    // 5: the strategy media is active on the output:
2446    //      use device for strategy media
2447    // 6: the strategy DTMF is active on the output:
2448    //      use device for strategy DTMF
2449    if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2450        device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2451    } else if (isInCall() ||
2452                    outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2453        device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2454    } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2455        device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2456    } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2457        device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2458    } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2459        device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2460    } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2461        device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2462    }
2463
2464    ALOGV("getNewDevice() selected device %x", device);
2465    return device;
2466}
2467
2468uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
2469    return (uint32_t)getStrategy(stream);
2470}
2471
2472audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
2473    audio_devices_t devices;
2474    // By checking the range of stream before calling getStrategy, we avoid
2475    // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
2476    // and then return STRATEGY_MEDIA, but we want to return the empty set.
2477    if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
2478        devices = AUDIO_DEVICE_NONE;
2479    } else {
2480        AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
2481        devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2482    }
2483    return devices;
2484}
2485
2486AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
2487        AudioSystem::stream_type stream) {
2488    // stream to strategy mapping
2489    switch (stream) {
2490    case AudioSystem::VOICE_CALL:
2491    case AudioSystem::BLUETOOTH_SCO:
2492        return STRATEGY_PHONE;
2493    case AudioSystem::RING:
2494    case AudioSystem::ALARM:
2495        return STRATEGY_SONIFICATION;
2496    case AudioSystem::NOTIFICATION:
2497        return STRATEGY_SONIFICATION_RESPECTFUL;
2498    case AudioSystem::DTMF:
2499        return STRATEGY_DTMF;
2500    default:
2501        ALOGE("unknown stream type");
2502    case AudioSystem::SYSTEM:
2503        // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2504        // while key clicks are played produces a poor result
2505    case AudioSystem::TTS:
2506    case AudioSystem::MUSIC:
2507        return STRATEGY_MEDIA;
2508    case AudioSystem::ENFORCED_AUDIBLE:
2509        return STRATEGY_ENFORCED_AUDIBLE;
2510    }
2511}
2512
2513void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2514    switch(stream) {
2515    case AudioSystem::MUSIC:
2516        checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2517        updateDevicesAndOutputs();
2518        break;
2519    default:
2520        break;
2521    }
2522}
2523
2524audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2525                                                             bool fromCache)
2526{
2527    uint32_t device = AUDIO_DEVICE_NONE;
2528
2529    if (fromCache) {
2530        ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2531              strategy, mDeviceForStrategy[strategy]);
2532        return mDeviceForStrategy[strategy];
2533    }
2534
2535    switch (strategy) {
2536
2537    case STRATEGY_SONIFICATION_RESPECTFUL:
2538        if (isInCall()) {
2539            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2540        } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
2541                SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2542            // while media is playing on a remote device, use the the sonification behavior.
2543            // Note that we test this usecase before testing if media is playing because
2544            //   the isStreamActive() method only informs about the activity of a stream, not
2545            //   if it's for local playback. Note also that we use the same delay between both tests
2546            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2547        } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2548            // while media is playing (or has recently played), use the same device
2549            device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2550        } else {
2551            // when media is not playing anymore, fall back on the sonification behavior
2552            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2553        }
2554
2555        break;
2556
2557    case STRATEGY_DTMF:
2558        if (!isInCall()) {
2559            // when off call, DTMF strategy follows the same rules as MEDIA strategy
2560            device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2561            break;
2562        }
2563        // when in call, DTMF and PHONE strategies follow the same rules
2564        // FALL THROUGH
2565
2566    case STRATEGY_PHONE:
2567        // for phone strategy, we first consider the forced use and then the available devices by order
2568        // of priority
2569        switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2570        case AudioSystem::FORCE_BT_SCO:
2571            if (!isInCall() || strategy != STRATEGY_DTMF) {
2572                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2573                if (device) break;
2574            }
2575            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2576            if (device) break;
2577            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2578            if (device) break;
2579            // if SCO device is requested but no SCO device is available, fall back to default case
2580            // FALL THROUGH
2581
2582        default:    // FORCE_NONE
2583            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2584            if (mHasA2dp && !isInCall() &&
2585                    (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2586                    (getA2dpOutput() != 0) && !mA2dpSuspended) {
2587                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2588                if (device) break;
2589                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2590                if (device) break;
2591            }
2592            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2593            if (device) break;
2594            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2595            if (device) break;
2596            if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2597                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2598                if (device) break;
2599                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2600                if (device) break;
2601                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2602                if (device) break;
2603                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2604                if (device) break;
2605                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2606                if (device) break;
2607            }
2608            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
2609            if (device) break;
2610            device = mDefaultOutputDevice;
2611            if (device == AUDIO_DEVICE_NONE) {
2612                ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2613            }
2614            break;
2615
2616        case AudioSystem::FORCE_SPEAKER:
2617            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2618            // A2DP speaker when forcing to speaker output
2619            if (mHasA2dp && !isInCall() &&
2620                    (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2621                    (getA2dpOutput() != 0) && !mA2dpSuspended) {
2622                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2623                if (device) break;
2624            }
2625            if (mPhoneState != AudioSystem::MODE_IN_CALL) {
2626                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2627                if (device) break;
2628                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2629                if (device) break;
2630                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2631                if (device) break;
2632                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2633                if (device) break;
2634                device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2635                if (device) break;
2636            }
2637            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2638            if (device) break;
2639            device = mDefaultOutputDevice;
2640            if (device == AUDIO_DEVICE_NONE) {
2641                ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2642            }
2643            break;
2644        }
2645    break;
2646
2647    case STRATEGY_SONIFICATION:
2648
2649        // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2650        // handleIncallSonification().
2651        if (isInCall()) {
2652            device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2653            break;
2654        }
2655        // FALL THROUGH
2656
2657    case STRATEGY_ENFORCED_AUDIBLE:
2658        // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2659        // except:
2660        //   - when in call where it doesn't default to STRATEGY_PHONE behavior
2661        //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
2662
2663        if ((strategy == STRATEGY_SONIFICATION) ||
2664                (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
2665            device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2666            if (device == AUDIO_DEVICE_NONE) {
2667                ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2668            }
2669        }
2670        // The second device used for sonification is the same as the device used by media strategy
2671        // FALL THROUGH
2672
2673    case STRATEGY_MEDIA: {
2674        uint32_t device2 = AUDIO_DEVICE_NONE;
2675        if (strategy != STRATEGY_SONIFICATION) {
2676            // no sonification on remote submix (e.g. WFD)
2677            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2678        }
2679        if ((device2 == AUDIO_DEVICE_NONE) &&
2680                mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2681                (getA2dpOutput() != 0) && !mA2dpSuspended) {
2682            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2683            if (device2 == AUDIO_DEVICE_NONE) {
2684                device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2685            }
2686            if (device2 == AUDIO_DEVICE_NONE) {
2687                device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2688            }
2689        }
2690        if (device2 == AUDIO_DEVICE_NONE) {
2691            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2692        }
2693        if (device2 == AUDIO_DEVICE_NONE) {
2694            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2695        }
2696        if (device2 == AUDIO_DEVICE_NONE) {
2697            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2698        }
2699        if (device2 == AUDIO_DEVICE_NONE) {
2700            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2701        }
2702        if (device2 == AUDIO_DEVICE_NONE) {
2703            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2704        }
2705        if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2706            // no sonification on aux digital (e.g. HDMI)
2707            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2708        }
2709        if ((device2 == AUDIO_DEVICE_NONE) &&
2710                (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
2711            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2712        }
2713        if (device2 == AUDIO_DEVICE_NONE) {
2714            device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
2715        }
2716
2717        // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2718        // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2719        device |= device2;
2720        if (device) break;
2721        device = mDefaultOutputDevice;
2722        if (device == AUDIO_DEVICE_NONE) {
2723            ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2724        }
2725        } break;
2726
2727    default:
2728        ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2729        break;
2730    }
2731
2732    ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2733    return device;
2734}
2735
2736void AudioPolicyManagerBase::updateDevicesAndOutputs()
2737{
2738    for (int i = 0; i < NUM_STRATEGIES; i++) {
2739        mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2740    }
2741    mPreviousOutputs = mOutputs;
2742}
2743
2744uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2745                                                       audio_devices_t prevDevice,
2746                                                       uint32_t delayMs)
2747{
2748    // mute/unmute strategies using an incompatible device combination
2749    // if muting, wait for the audio in pcm buffer to be drained before proceeding
2750    // if unmuting, unmute only after the specified delay
2751    if (outputDesc->isDuplicated()) {
2752        return 0;
2753    }
2754
2755    uint32_t muteWaitMs = 0;
2756    audio_devices_t device = outputDesc->device();
2757    bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
2758    // temporary mute output if device selection changes to avoid volume bursts due to
2759    // different per device volumes
2760    bool tempMute = outputDesc->isActive() && (device != prevDevice);
2761
2762    for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2763        audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2764        bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2765        bool doMute = false;
2766
2767        if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2768            doMute = true;
2769            outputDesc->mStrategyMutedByDevice[i] = true;
2770        } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2771            doMute = true;
2772            outputDesc->mStrategyMutedByDevice[i] = false;
2773        }
2774        if (doMute || tempMute) {
2775            for (size_t j = 0; j < mOutputs.size(); j++) {
2776                AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2777                // skip output if it does not share any device with current output
2778                if ((desc->supportedDevices() & outputDesc->supportedDevices())
2779                        == AUDIO_DEVICE_NONE) {
2780                    continue;
2781                }
2782                audio_io_handle_t curOutput = mOutputs.keyAt(j);
2783                ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2784                      mute ? "muting" : "unmuting", i, curDevice, curOutput);
2785                setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2786                if (desc->isStrategyActive((routing_strategy)i)) {
2787                    // do tempMute only for current output
2788                    if (tempMute && (desc == outputDesc)) {
2789                        setStrategyMute((routing_strategy)i, true, curOutput);
2790                        setStrategyMute((routing_strategy)i, false, curOutput,
2791                                            desc->latency() * 2, device);
2792                    }
2793                    if ((tempMute && (desc == outputDesc)) || mute) {
2794                        if (muteWaitMs < desc->latency()) {
2795                            muteWaitMs = desc->latency();
2796                        }
2797                    }
2798                }
2799            }
2800        }
2801    }
2802
2803    // FIXME: should not need to double latency if volume could be applied immediately by the
2804    // audioflinger mixer. We must account for the delay between now and the next time
2805    // the audioflinger thread for this output will process a buffer (which corresponds to
2806    // one buffer size, usually 1/2 or 1/4 of the latency).
2807    muteWaitMs *= 2;
2808    // wait for the PCM output buffers to empty before proceeding with the rest of the command
2809    if (muteWaitMs > delayMs) {
2810        muteWaitMs -= delayMs;
2811        usleep(muteWaitMs * 1000);
2812        return muteWaitMs;
2813    }
2814    return 0;
2815}
2816
2817uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2818                                             audio_devices_t device,
2819                                             bool force,
2820                                             int delayMs)
2821{
2822    ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2823    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2824    AudioParameter param;
2825    uint32_t muteWaitMs;
2826
2827    if (outputDesc->isDuplicated()) {
2828        muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2829        muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2830        return muteWaitMs;
2831    }
2832    // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2833    // output profile
2834    if ((device != AUDIO_DEVICE_NONE) &&
2835            ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
2836        return 0;
2837    }
2838
2839    // filter devices according to output selected
2840    device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2841
2842    audio_devices_t prevDevice = outputDesc->mDevice;
2843
2844    ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2845
2846    if (device != AUDIO_DEVICE_NONE) {
2847        outputDesc->mDevice = device;
2848    }
2849    muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2850
2851    // Do not change the routing if:
2852    //  - the requested device is AUDIO_DEVICE_NONE
2853    //  - the requested device is the same as current device and force is not specified.
2854    // Doing this check here allows the caller to call setOutputDevice() without conditions
2855    if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2856        ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2857        return muteWaitMs;
2858    }
2859
2860    ALOGV("setOutputDevice() changing device");
2861    // do the routing
2862    param.addInt(String8(AudioParameter::keyRouting), (int)device);
2863    mpClientInterface->setParameters(output, param.toString(), delayMs);
2864
2865    // update stream volumes according to new device
2866    applyStreamVolumes(output, device, delayMs);
2867
2868    return muteWaitMs;
2869}
2870
2871AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2872                                                   uint32_t samplingRate,
2873                                                   audio_format_t format,
2874                                                   audio_channel_mask_t channelMask)
2875{
2876    // Choose an input profile based on the requested capture parameters: select the first available
2877    // profile supporting all requested parameters.
2878    for (size_t i = 0; i < mHwModules.size(); i++)
2879    {
2880        if (mHwModules[i]->mHandle == 0) {
2881            continue;
2882        }
2883        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2884        {
2885            IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2886            // profile->log();
2887            if (profile->isCompatibleProfile(device, samplingRate, format,
2888                                             channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2889                return profile;
2890            }
2891        }
2892    }
2893    return NULL;
2894}
2895
2896audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2897{
2898    uint32_t device = AUDIO_DEVICE_NONE;
2899
2900    switch (inputSource) {
2901    case AUDIO_SOURCE_VOICE_UPLINK:
2902      if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2903          device = AUDIO_DEVICE_IN_VOICE_CALL;
2904          break;
2905      }
2906      // FALL THROUGH
2907
2908    case AUDIO_SOURCE_DEFAULT:
2909    case AUDIO_SOURCE_MIC:
2910    if (mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
2911        device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
2912        break;
2913    }
2914    // FALL THROUGH
2915
2916    case AUDIO_SOURCE_VOICE_RECOGNITION:
2917    case AUDIO_SOURCE_HOTWORD:
2918    case AUDIO_SOURCE_VOICE_COMMUNICATION:
2919        if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2920            mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2921            device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2922        } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
2923            device = AUDIO_DEVICE_IN_WIRED_HEADSET;
2924        } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_USB_DEVICE) {
2925            device = AUDIO_DEVICE_IN_USB_DEVICE;
2926        } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2927            device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2928        }
2929        break;
2930    case AUDIO_SOURCE_CAMCORDER:
2931        if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
2932            device = AUDIO_DEVICE_IN_BACK_MIC;
2933        } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
2934            device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2935        }
2936        break;
2937    case AUDIO_SOURCE_VOICE_DOWNLINK:
2938    case AUDIO_SOURCE_VOICE_CALL:
2939        if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
2940            device = AUDIO_DEVICE_IN_VOICE_CALL;
2941        }
2942        break;
2943    case AUDIO_SOURCE_REMOTE_SUBMIX:
2944        if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
2945            device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2946        }
2947        break;
2948    default:
2949        ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2950        break;
2951    }
2952    ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2953    return device;
2954}
2955
2956bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
2957{
2958    if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2959        device &= ~AUDIO_DEVICE_BIT_IN;
2960        if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2961            return true;
2962    }
2963    return false;
2964}
2965
2966audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
2967{
2968    for (size_t i = 0; i < mInputs.size(); i++) {
2969        const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2970        if ((input_descriptor->mRefCount > 0)
2971                && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2972            return mInputs.keyAt(i);
2973        }
2974    }
2975    return 0;
2976}
2977
2978
2979audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2980{
2981    if (device == AUDIO_DEVICE_NONE) {
2982        // this happens when forcing a route update and no track is active on an output.
2983        // In this case the returned category is not important.
2984        device =  AUDIO_DEVICE_OUT_SPEAKER;
2985    } else if (AudioSystem::popCount(device) > 1) {
2986        // Multiple device selection is either:
2987        //  - speaker + one other device: give priority to speaker in this case.
2988        //  - one A2DP device + another device: happens with duplicated output. In this case
2989        // retain the device on the A2DP output as the other must not correspond to an active
2990        // selection if not the speaker.
2991        if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2992            device = AUDIO_DEVICE_OUT_SPEAKER;
2993        } else {
2994            device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2995        }
2996    }
2997
2998    ALOGW_IF(AudioSystem::popCount(device) != 1,
2999            "getDeviceForVolume() invalid device combination: %08x",
3000            device);
3001
3002    return device;
3003}
3004
3005AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
3006{
3007    switch(getDeviceForVolume(device)) {
3008        case AUDIO_DEVICE_OUT_EARPIECE:
3009            return DEVICE_CATEGORY_EARPIECE;
3010        case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3011        case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3012        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3013        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3014        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3015        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3016            return DEVICE_CATEGORY_HEADSET;
3017        case AUDIO_DEVICE_OUT_SPEAKER:
3018        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3019        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3020        case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3021        case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3022        case AUDIO_DEVICE_OUT_USB_DEVICE:
3023        case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3024        default:
3025            return DEVICE_CATEGORY_SPEAKER;
3026    }
3027}
3028
3029float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
3030        int indexInUi)
3031{
3032    device_category deviceCategory = getDeviceCategory(device);
3033    const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3034
3035    // the volume index in the UI is relative to the min and max volume indices for this stream type
3036    int nbSteps = 1 + curve[VOLMAX].mIndex -
3037            curve[VOLMIN].mIndex;
3038    int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3039            (streamDesc.mIndexMax - streamDesc.mIndexMin);
3040
3041    // find what part of the curve this index volume belongs to, or if it's out of bounds
3042    int segment = 0;
3043    if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
3044        return 0.0f;
3045    } else if (volIdx < curve[VOLKNEE1].mIndex) {
3046        segment = 0;
3047    } else if (volIdx < curve[VOLKNEE2].mIndex) {
3048        segment = 1;
3049    } else if (volIdx <= curve[VOLMAX].mIndex) {
3050        segment = 2;
3051    } else {                                                               // out of bounds
3052        return 1.0f;
3053    }
3054
3055    // linear interpolation in the attenuation table in dB
3056    float decibels = curve[segment].mDBAttenuation +
3057            ((float)(volIdx - curve[segment].mIndex)) *
3058                ( (curve[segment+1].mDBAttenuation -
3059                        curve[segment].mDBAttenuation) /
3060                    ((float)(curve[segment+1].mIndex -
3061                            curve[segment].mIndex)) );
3062
3063    float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3064
3065    ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3066            curve[segment].mIndex, volIdx,
3067            curve[segment+1].mIndex,
3068            curve[segment].mDBAttenuation,
3069            decibels,
3070            curve[segment+1].mDBAttenuation,
3071            amplification);
3072
3073    return amplification;
3074}
3075
3076const AudioPolicyManagerBase::VolumeCurvePoint
3077    AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3078    {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3079};
3080
3081const AudioPolicyManagerBase::VolumeCurvePoint
3082    AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3083    {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3084};
3085
3086const AudioPolicyManagerBase::VolumeCurvePoint
3087    AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3088    {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3089};
3090
3091const AudioPolicyManagerBase::VolumeCurvePoint
3092    AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3093    {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3094};
3095
3096const AudioPolicyManagerBase::VolumeCurvePoint
3097    AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3098    {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3099};
3100
3101// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3102// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3103// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3104// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3105
3106const AudioPolicyManagerBase::VolumeCurvePoint
3107    AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3108    {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3109};
3110
3111const AudioPolicyManagerBase::VolumeCurvePoint
3112    AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
3113    {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3114};
3115
3116const AudioPolicyManagerBase::VolumeCurvePoint
3117    AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3118    {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3119};
3120
3121const AudioPolicyManagerBase::VolumeCurvePoint
3122    AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3123    {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3124};
3125
3126const AudioPolicyManagerBase::VolumeCurvePoint
3127    AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
3128    {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3129};
3130
3131const AudioPolicyManagerBase::VolumeCurvePoint
3132            *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
3133                                                   [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
3134    { // AUDIO_STREAM_VOICE_CALL
3135        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3136        sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3137        sDefaultVoiceVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3138    },
3139    { // AUDIO_STREAM_SYSTEM
3140        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3141        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3142        sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3143    },
3144    { // AUDIO_STREAM_RING
3145        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3146        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3147        sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3148    },
3149    { // AUDIO_STREAM_MUSIC
3150        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3151        sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3152        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3153    },
3154    { // AUDIO_STREAM_ALARM
3155        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3156        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3157        sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3158    },
3159    { // AUDIO_STREAM_NOTIFICATION
3160        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3161        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3162        sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3163    },
3164    { // AUDIO_STREAM_BLUETOOTH_SCO
3165        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3166        sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3167        sDefaultVoiceVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3168    },
3169    { // AUDIO_STREAM_ENFORCED_AUDIBLE
3170        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3171        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3172        sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3173    },
3174    {  // AUDIO_STREAM_DTMF
3175        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3176        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3177        sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3178    },
3179    { // AUDIO_STREAM_TTS
3180        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3181        sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3182        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3183    },
3184};
3185
3186void AudioPolicyManagerBase::initializeVolumeCurves()
3187{
3188    for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3189        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3190            mStreams[i].mVolumeCurve[j] =
3191                    sVolumeProfiles[i][j];
3192        }
3193    }
3194
3195    // Check availability of DRC on speaker path: if available, override some of the speaker curves
3196    if (mSpeakerDrcEnabled) {
3197        mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3198                sDefaultSystemVolumeCurveDrc;
3199        mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3200                sSpeakerSonificationVolumeCurveDrc;
3201        mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3202                sSpeakerSonificationVolumeCurveDrc;
3203        mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3204                sSpeakerSonificationVolumeCurveDrc;
3205    }
3206}
3207
3208float AudioPolicyManagerBase::computeVolume(int stream,
3209                                            int index,
3210                                            audio_io_handle_t output,
3211                                            audio_devices_t device)
3212{
3213    float volume = 1.0;
3214    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3215    StreamDescriptor &streamDesc = mStreams[stream];
3216
3217    if (device == AUDIO_DEVICE_NONE) {
3218        device = outputDesc->device();
3219    }
3220
3221    // if volume is not 0 (not muted), force media volume to max on digital output
3222    if (stream == AudioSystem::MUSIC &&
3223        index != mStreams[stream].mIndexMin &&
3224        (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3225         device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3226         device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3227         device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3228        return 1.0;
3229    }
3230
3231    volume = volIndexToAmpl(device, streamDesc, index);
3232
3233    // if a headset is connected, apply the following rules to ring tones and notifications
3234    // to avoid sound level bursts in user's ears:
3235    // - always attenuate ring tones and notifications volume by 6dB
3236    // - if music is playing, always limit the volume to current music volume,
3237    // with a minimum threshold at -36dB so that notification is always perceived.
3238    const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3239    if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3240            AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3241            AUDIO_DEVICE_OUT_WIRED_HEADSET |
3242            AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3243        ((stream_strategy == STRATEGY_SONIFICATION)
3244                || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3245                || (stream == AudioSystem::SYSTEM)
3246                || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3247                    (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
3248        streamDesc.mCanBeMuted) {
3249        volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3250        // when the phone is ringing we must consider that music could have been paused just before
3251        // by the music application and behave as if music was active if the last music track was
3252        // just stopped
3253        if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3254                mLimitRingtoneVolume) {
3255            audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3256            float musicVol = computeVolume(AudioSystem::MUSIC,
3257                               mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
3258                               output,
3259                               musicDevice);
3260            float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3261                                musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3262            if (volume > minVol) {
3263                volume = minVol;
3264                ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3265            }
3266        }
3267    }
3268
3269    return volume;
3270}
3271
3272status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
3273                                                   int index,
3274                                                   audio_io_handle_t output,
3275                                                   audio_devices_t device,
3276                                                   int delayMs,
3277                                                   bool force)
3278{
3279
3280    // do not change actual stream volume if the stream is muted
3281    if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3282        ALOGVV("checkAndSetVolume() stream %d muted count %d",
3283              stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3284        return NO_ERROR;
3285    }
3286
3287    // do not change in call volume if bluetooth is connected and vice versa
3288    if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
3289        (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
3290        ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3291             stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
3292        return INVALID_OPERATION;
3293    }
3294
3295    float volume = computeVolume(stream, index, output, device);
3296    // We actually change the volume if:
3297    // - the float value returned by computeVolume() changed
3298    // - the force flag is set
3299    if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3300            force) {
3301        mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3302        ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3303        // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3304        // enabled
3305        if (stream == AudioSystem::BLUETOOTH_SCO) {
3306            mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
3307        }
3308        mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
3309    }
3310
3311    if (stream == AudioSystem::VOICE_CALL ||
3312        stream == AudioSystem::BLUETOOTH_SCO) {
3313        float voiceVolume;
3314        // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3315        if (stream == AudioSystem::VOICE_CALL) {
3316            voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3317        } else {
3318            voiceVolume = 1.0;
3319        }
3320
3321        if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3322            mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3323            mLastVoiceVolume = voiceVolume;
3324        }
3325    }
3326
3327    return NO_ERROR;
3328}
3329
3330void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
3331                                                audio_devices_t device,
3332                                                int delayMs,
3333                                                bool force)
3334{
3335    ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3336
3337    for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3338        checkAndSetVolume(stream,
3339                          mStreams[stream].getVolumeIndex(device),
3340                          output,
3341                          device,
3342                          delayMs,
3343                          force);
3344    }
3345}
3346
3347void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
3348                                             bool on,
3349                                             audio_io_handle_t output,
3350                                             int delayMs,
3351                                             audio_devices_t device)
3352{
3353    ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3354    for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
3355        if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
3356            setStreamMute(stream, on, output, delayMs, device);
3357        }
3358    }
3359}
3360
3361void AudioPolicyManagerBase::setStreamMute(int stream,
3362                                           bool on,
3363                                           audio_io_handle_t output,
3364                                           int delayMs,
3365                                           audio_devices_t device)
3366{
3367    StreamDescriptor &streamDesc = mStreams[stream];
3368    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3369    if (device == AUDIO_DEVICE_NONE) {
3370        device = outputDesc->device();
3371    }
3372
3373    ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3374          stream, on, output, outputDesc->mMuteCount[stream], device);
3375
3376    if (on) {
3377        if (outputDesc->mMuteCount[stream] == 0) {
3378            if (streamDesc.mCanBeMuted &&
3379                    ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
3380                     (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
3381                checkAndSetVolume(stream, 0, output, device, delayMs);
3382            }
3383        }
3384        // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3385        outputDesc->mMuteCount[stream]++;
3386    } else {
3387        if (outputDesc->mMuteCount[stream] == 0) {
3388            ALOGV("setStreamMute() unmuting non muted stream!");
3389            return;
3390        }
3391        if (--outputDesc->mMuteCount[stream] == 0) {
3392            checkAndSetVolume(stream,
3393                              streamDesc.getVolumeIndex(device),
3394                              output,
3395                              device,
3396                              delayMs);
3397        }
3398    }
3399}
3400
3401void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
3402{
3403    // if the stream pertains to sonification strategy and we are in call we must
3404    // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3405    // in the device used for phone strategy and play the tone if the selected device does not
3406    // interfere with the device used for phone strategy
3407    // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3408    // many times as there are active tracks on the output
3409    const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
3410    if ((stream_strategy == STRATEGY_SONIFICATION) ||
3411            ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3412        AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3413        ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3414                stream, starting, outputDesc->mDevice, stateChange);
3415        if (outputDesc->mRefCount[stream]) {
3416            int muteCount = 1;
3417            if (stateChange) {
3418                muteCount = outputDesc->mRefCount[stream];
3419            }
3420            if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
3421                ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3422                for (int i = 0; i < muteCount; i++) {
3423                    setStreamMute(stream, starting, mPrimaryOutput);
3424                }
3425            } else {
3426                ALOGV("handleIncallSonification() high visibility");
3427                if (outputDesc->device() &
3428                        getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3429                    ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3430                    for (int i = 0; i < muteCount; i++) {
3431                        setStreamMute(stream, starting, mPrimaryOutput);
3432                    }
3433                }
3434                if (starting) {
3435                    mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
3436                } else {
3437                    mpClientInterface->stopTone();
3438                }
3439            }
3440        }
3441    }
3442}
3443
3444bool AudioPolicyManagerBase::isInCall()
3445{
3446    return isStateInCall(mPhoneState);
3447}
3448
3449bool AudioPolicyManagerBase::isStateInCall(int state) {
3450    return ((state == AudioSystem::MODE_IN_CALL) ||
3451            (state == AudioSystem::MODE_IN_COMMUNICATION));
3452}
3453
3454uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
3455{
3456    return MAX_EFFECTS_CPU_LOAD;
3457}
3458
3459uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
3460{
3461    return MAX_EFFECTS_MEMORY;
3462}
3463
3464// --- AudioOutputDescriptor class implementation
3465
3466AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
3467        const IOProfile *profile)
3468    : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3469      mChannelMask(0), mLatency(0),
3470    mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3471    mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3472{
3473    // clear usage count for all stream types
3474    for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3475        mRefCount[i] = 0;
3476        mCurVolume[i] = -1.0;
3477        mMuteCount[i] = 0;
3478        mStopTime[i] = 0;
3479    }
3480    for (int i = 0; i < NUM_STRATEGIES; i++) {
3481        mStrategyMutedByDevice[i] = false;
3482    }
3483    if (profile != NULL) {
3484        mSamplingRate = profile->mSamplingRates[0];
3485        mFormat = profile->mFormats[0];
3486        mChannelMask = profile->mChannelMasks[0];
3487        mFlags = profile->mFlags;
3488    }
3489}
3490
3491audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
3492{
3493    if (isDuplicated()) {
3494        return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3495    } else {
3496        return mDevice;
3497    }
3498}
3499
3500uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
3501{
3502    if (isDuplicated()) {
3503        return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3504    } else {
3505        return mLatency;
3506    }
3507}
3508
3509bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
3510        const AudioOutputDescriptor *outputDesc)
3511{
3512    if (isDuplicated()) {
3513        return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3514    } else if (outputDesc->isDuplicated()){
3515        return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3516    } else {
3517        return (mProfile->mModule == outputDesc->mProfile->mModule);
3518    }
3519}
3520
3521void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
3522{
3523    // forward usage count change to attached outputs
3524    if (isDuplicated()) {
3525        mOutput1->changeRefCount(stream, delta);
3526        mOutput2->changeRefCount(stream, delta);
3527    }
3528    if ((delta + (int)mRefCount[stream]) < 0) {
3529        ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
3530        mRefCount[stream] = 0;
3531        return;
3532    }
3533    mRefCount[stream] += delta;
3534    ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3535}
3536
3537audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
3538{
3539    if (isDuplicated()) {
3540        return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3541    } else {
3542        return mProfile->mSupportedDevices ;
3543    }
3544}
3545
3546bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3547{
3548    return isStrategyActive(NUM_STRATEGIES, inPastMs);
3549}
3550
3551bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3552                                                                       uint32_t inPastMs,
3553                                                                       nsecs_t sysTime) const
3554{
3555    if ((sysTime == 0) && (inPastMs != 0)) {
3556        sysTime = systemTime();
3557    }
3558    for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3559        if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
3560                (NUM_STRATEGIES == strategy)) &&
3561                isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
3562            return true;
3563        }
3564    }
3565    return false;
3566}
3567
3568bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
3569                                                                       uint32_t inPastMs,
3570                                                                       nsecs_t sysTime) const
3571{
3572    if (mRefCount[stream] != 0) {
3573        return true;
3574    }
3575    if (inPastMs == 0) {
3576        return false;
3577    }
3578    if (sysTime == 0) {
3579        sysTime = systemTime();
3580    }
3581    if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3582        return true;
3583    }
3584    return false;
3585}
3586
3587
3588status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
3589{
3590    const size_t SIZE = 256;
3591    char buffer[SIZE];
3592    String8 result;
3593
3594    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3595    result.append(buffer);
3596    snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3597    result.append(buffer);
3598    snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3599    result.append(buffer);
3600    snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3601    result.append(buffer);
3602    snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3603    result.append(buffer);
3604    snprintf(buffer, SIZE, " Devices %08x\n", device());
3605    result.append(buffer);
3606    snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3607    result.append(buffer);
3608    for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
3609        snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3610        result.append(buffer);
3611    }
3612    write(fd, result.string(), result.size());
3613
3614    return NO_ERROR;
3615}
3616
3617// --- AudioInputDescriptor class implementation
3618
3619AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3620    :  mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3621      mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3622      mInputSource(0), mProfile(profile)
3623{
3624    if (profile != NULL) {
3625         mSamplingRate = profile->mSamplingRates[0];
3626         mFormat = profile->mFormats[0];
3627         mChannelMask = profile->mChannelMasks[0];
3628     }
3629}
3630
3631status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3632{
3633    const size_t SIZE = 256;
3634    char buffer[SIZE];
3635    String8 result;
3636
3637    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3638    result.append(buffer);
3639    snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3640    result.append(buffer);
3641    snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3642    result.append(buffer);
3643    snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3644    result.append(buffer);
3645    snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3646    result.append(buffer);
3647    write(fd, result.string(), result.size());
3648
3649    return NO_ERROR;
3650}
3651
3652// --- StreamDescriptor class implementation
3653
3654AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3655    :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3656{
3657    mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3658}
3659
3660int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3661{
3662    device = AudioPolicyManagerBase::getDeviceForVolume(device);
3663    // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3664    if (mIndexCur.indexOfKey(device) < 0) {
3665        device = AUDIO_DEVICE_OUT_DEFAULT;
3666    }
3667    return mIndexCur.valueFor(device);
3668}
3669
3670void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3671{
3672    const size_t SIZE = 256;
3673    char buffer[SIZE];
3674    String8 result;
3675
3676    snprintf(buffer, SIZE, "%s         %02d         %02d         ",
3677             mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3678    result.append(buffer);
3679    for (size_t i = 0; i < mIndexCur.size(); i++) {
3680        snprintf(buffer, SIZE, "%04x : %02d, ",
3681                 mIndexCur.keyAt(i),
3682                 mIndexCur.valueAt(i));
3683        result.append(buffer);
3684    }
3685    result.append("\n");
3686
3687    write(fd, result.string(), result.size());
3688}
3689
3690// --- EffectDescriptor class implementation
3691
3692status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3693{
3694    const size_t SIZE = 256;
3695    char buffer[SIZE];
3696    String8 result;
3697
3698    snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3699    result.append(buffer);
3700    snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3701    result.append(buffer);
3702    snprintf(buffer, SIZE, " Session: %d\n", mSession);
3703    result.append(buffer);
3704    snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
3705    result.append(buffer);
3706    snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
3707    result.append(buffer);
3708    write(fd, result.string(), result.size());
3709
3710    return NO_ERROR;
3711}
3712
3713// --- IOProfile class implementation
3714
3715AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3716    : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3717{
3718}
3719
3720AudioPolicyManagerBase::HwModule::~HwModule()
3721{
3722    for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3723         delete mOutputProfiles[i];
3724    }
3725    for (size_t i = 0; i < mInputProfiles.size(); i++) {
3726         delete mInputProfiles[i];
3727    }
3728    free((void *)mName);
3729}
3730
3731void AudioPolicyManagerBase::HwModule::dump(int fd)
3732{
3733    const size_t SIZE = 256;
3734    char buffer[SIZE];
3735    String8 result;
3736
3737    snprintf(buffer, SIZE, "  - name: %s\n", mName);
3738    result.append(buffer);
3739    snprintf(buffer, SIZE, "  - handle: %d\n", mHandle);
3740    result.append(buffer);
3741    write(fd, result.string(), result.size());
3742    if (mOutputProfiles.size()) {
3743        write(fd, "  - outputs:\n", strlen("  - outputs:\n"));
3744        for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3745            snprintf(buffer, SIZE, "    output %zu:\n", i);
3746            write(fd, buffer, strlen(buffer));
3747            mOutputProfiles[i]->dump(fd);
3748        }
3749    }
3750    if (mInputProfiles.size()) {
3751        write(fd, "  - inputs:\n", strlen("  - inputs:\n"));
3752        for (size_t i = 0; i < mInputProfiles.size(); i++) {
3753            snprintf(buffer, SIZE, "    input %zu:\n", i);
3754            write(fd, buffer, strlen(buffer));
3755            mInputProfiles[i]->dump(fd);
3756        }
3757    }
3758}
3759
3760AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3761    : mFlags((audio_output_flags_t)0), mModule(module)
3762{
3763}
3764
3765AudioPolicyManagerBase::IOProfile::~IOProfile()
3766{
3767}
3768
3769// checks if the IO profile is compatible with specified parameters.
3770// Sampling rate, format and channel mask must be specified in order to
3771// get a valid a match
3772bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3773                                                            uint32_t samplingRate,
3774                                                            audio_format_t format,
3775                                                            audio_channel_mask_t channelMask,
3776                                                            audio_output_flags_t flags) const
3777{
3778    if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3779         return false;
3780     }
3781
3782     if ((mSupportedDevices & device) != device) {
3783         return false;
3784     }
3785     if ((mFlags & flags) != flags) {
3786         return false;
3787     }
3788     size_t i;
3789     for (i = 0; i < mSamplingRates.size(); i++)
3790     {
3791         if (mSamplingRates[i] == samplingRate) {
3792             break;
3793         }
3794     }
3795     if (i == mSamplingRates.size()) {
3796         return false;
3797     }
3798     for (i = 0; i < mFormats.size(); i++)
3799     {
3800         if (mFormats[i] == format) {
3801             break;
3802         }
3803     }
3804     if (i == mFormats.size()) {
3805         return false;
3806     }
3807     for (i = 0; i < mChannelMasks.size(); i++)
3808     {
3809         if (mChannelMasks[i] == channelMask) {
3810             break;
3811         }
3812     }
3813     if (i == mChannelMasks.size()) {
3814         return false;
3815     }
3816     return true;
3817}
3818
3819void AudioPolicyManagerBase::IOProfile::dump(int fd)
3820{
3821    const size_t SIZE = 256;
3822    char buffer[SIZE];
3823    String8 result;
3824
3825    snprintf(buffer, SIZE, "    - sampling rates: ");
3826    result.append(buffer);
3827    for (size_t i = 0; i < mSamplingRates.size(); i++) {
3828        snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3829        result.append(buffer);
3830        result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3831    }
3832
3833    snprintf(buffer, SIZE, "    - channel masks: ");
3834    result.append(buffer);
3835    for (size_t i = 0; i < mChannelMasks.size(); i++) {
3836        snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3837        result.append(buffer);
3838        result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3839    }
3840
3841    snprintf(buffer, SIZE, "    - formats: ");
3842    result.append(buffer);
3843    for (size_t i = 0; i < mFormats.size(); i++) {
3844        snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3845        result.append(buffer);
3846        result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3847    }
3848
3849    snprintf(buffer, SIZE, "    - devices: 0x%04x\n", mSupportedDevices);
3850    result.append(buffer);
3851    snprintf(buffer, SIZE, "    - flags: 0x%04x\n", mFlags);
3852    result.append(buffer);
3853
3854    write(fd, result.string(), result.size());
3855}
3856
3857void AudioPolicyManagerBase::IOProfile::log()
3858{
3859    const size_t SIZE = 256;
3860    char buffer[SIZE];
3861    String8 result;
3862
3863    ALOGV("    - sampling rates: ");
3864    for (size_t i = 0; i < mSamplingRates.size(); i++) {
3865        ALOGV("  %d", mSamplingRates[i]);
3866    }
3867
3868    ALOGV("    - channel masks: ");
3869    for (size_t i = 0; i < mChannelMasks.size(); i++) {
3870        ALOGV("  0x%04x", mChannelMasks[i]);
3871    }
3872
3873    ALOGV("    - formats: ");
3874    for (size_t i = 0; i < mFormats.size(); i++) {
3875        ALOGV("  0x%08x", mFormats[i]);
3876    }
3877
3878    ALOGV("    - devices: 0x%04x\n", mSupportedDevices);
3879    ALOGV("    - flags: 0x%04x\n", mFlags);
3880}
3881
3882// --- audio_policy.conf file parsing
3883
3884struct StringToEnum {
3885    const char *name;
3886    uint32_t value;
3887};
3888
3889#define STRING_TO_ENUM(string) { #string, string }
3890#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3891
3892const struct StringToEnum sDeviceNameToEnumTable[] = {
3893    STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3894    STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3895    STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3896    STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3897    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3898    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3899    STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3900    STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3901    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3902    STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3903    STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3904    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3905    STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
3906    STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3907    STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3908    STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3909    STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3910    STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3911    STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3912    STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
3913    STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
3914    STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
3915    STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
3916    STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
3917    STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
3918};
3919
3920const struct StringToEnum sFlagNameToEnumTable[] = {
3921    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3922    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3923    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3924    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3925    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
3926    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
3927};
3928
3929const struct StringToEnum sFormatNameToEnumTable[] = {
3930    STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3931    STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3932    STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
3933    STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
3934    STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
3935    STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
3936    STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3937    STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3938    STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3939};
3940
3941const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3942    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3943    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3944    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3945    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3946};
3947
3948const struct StringToEnum sInChannelsNameToEnumTable[] = {
3949    STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3950    STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3951    STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
3952};
3953
3954
3955uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3956                                              size_t size,
3957                                              const char *name)
3958{
3959    for (size_t i = 0; i < size; i++) {
3960        if (strcmp(table[i].name, name) == 0) {
3961            ALOGV("stringToEnum() found %s", table[i].name);
3962            return table[i].value;
3963        }
3964    }
3965    return 0;
3966}
3967
3968bool AudioPolicyManagerBase::stringToBool(const char *value)
3969{
3970    return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
3971}
3972
3973audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3974{
3975    uint32_t flag = 0;
3976
3977    // it is OK to cast name to non const here as we are not going to use it after
3978    // strtok() modifies it
3979    char *flagName = strtok(name, "|");
3980    while (flagName != NULL) {
3981        if (strlen(flagName) != 0) {
3982            flag |= stringToEnum(sFlagNameToEnumTable,
3983                               ARRAY_SIZE(sFlagNameToEnumTable),
3984                               flagName);
3985        }
3986        flagName = strtok(NULL, "|");
3987    }
3988    //force direct flag if offload flag is set: offloading implies a direct output stream
3989    // and all common behaviors are driven by checking only the direct flag
3990    // this should normally be set appropriately in the policy configuration file
3991    if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3992        flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3993    }
3994
3995    return (audio_output_flags_t)flag;
3996}
3997
3998audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3999{
4000    uint32_t device = 0;
4001
4002    char *devName = strtok(name, "|");
4003    while (devName != NULL) {
4004        if (strlen(devName) != 0) {
4005            device |= stringToEnum(sDeviceNameToEnumTable,
4006                                 ARRAY_SIZE(sDeviceNameToEnumTable),
4007                                 devName);
4008        }
4009        devName = strtok(NULL, "|");
4010    }
4011    return device;
4012}
4013
4014void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
4015{
4016    char *str = strtok(name, "|");
4017
4018    // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4019    // rates should be read from the output stream after it is opened for the first time
4020    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4021        profile->mSamplingRates.add(0);
4022        return;
4023    }
4024
4025    while (str != NULL) {
4026        uint32_t rate = atoi(str);
4027        if (rate != 0) {
4028            ALOGV("loadSamplingRates() adding rate %d", rate);
4029            profile->mSamplingRates.add(rate);
4030        }
4031        str = strtok(NULL, "|");
4032    }
4033    return;
4034}
4035
4036void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
4037{
4038    char *str = strtok(name, "|");
4039
4040    // by convention, "0' in the first entry in mFormats indicates the supported formats
4041    // should be read from the output stream after it is opened for the first time
4042    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4043        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4044        return;
4045    }
4046
4047    while (str != NULL) {
4048        audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4049                                                             ARRAY_SIZE(sFormatNameToEnumTable),
4050                                                             str);
4051        if (format != AUDIO_FORMAT_DEFAULT) {
4052            profile->mFormats.add(format);
4053        }
4054        str = strtok(NULL, "|");
4055    }
4056    return;
4057}
4058
4059void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
4060{
4061    const char *str = strtok(name, "|");
4062
4063    ALOGV("loadInChannels() %s", name);
4064
4065    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4066        profile->mChannelMasks.add(0);
4067        return;
4068    }
4069
4070    while (str != NULL) {
4071        audio_channel_mask_t channelMask =
4072                (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4073                                                   ARRAY_SIZE(sInChannelsNameToEnumTable),
4074                                                   str);
4075        if (channelMask != 0) {
4076            ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4077            profile->mChannelMasks.add(channelMask);
4078        }
4079        str = strtok(NULL, "|");
4080    }
4081    return;
4082}
4083
4084void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
4085{
4086    const char *str = strtok(name, "|");
4087
4088    ALOGV("loadOutChannels() %s", name);
4089
4090    // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4091    // masks should be read from the output stream after it is opened for the first time
4092    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4093        profile->mChannelMasks.add(0);
4094        return;
4095    }
4096
4097    while (str != NULL) {
4098        audio_channel_mask_t channelMask =
4099                (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4100                                                   ARRAY_SIZE(sOutChannelsNameToEnumTable),
4101                                                   str);
4102        if (channelMask != 0) {
4103            profile->mChannelMasks.add(channelMask);
4104        }
4105        str = strtok(NULL, "|");
4106    }
4107    return;
4108}
4109
4110status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
4111{
4112    cnode *node = root->first_child;
4113
4114    IOProfile *profile = new IOProfile(module);
4115
4116    while (node) {
4117        if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4118            loadSamplingRates((char *)node->value, profile);
4119        } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4120            loadFormats((char *)node->value, profile);
4121        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4122            loadInChannels((char *)node->value, profile);
4123        } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4124            profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4125        }
4126        node = node->next;
4127    }
4128    ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4129            "loadInput() invalid supported devices");
4130    ALOGW_IF(profile->mChannelMasks.size() == 0,
4131            "loadInput() invalid supported channel masks");
4132    ALOGW_IF(profile->mSamplingRates.size() == 0,
4133            "loadInput() invalid supported sampling rates");
4134    ALOGW_IF(profile->mFormats.size() == 0,
4135            "loadInput() invalid supported formats");
4136    if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4137            (profile->mChannelMasks.size() != 0) &&
4138            (profile->mSamplingRates.size() != 0) &&
4139            (profile->mFormats.size() != 0)) {
4140
4141        ALOGV("loadInput() adding input mSupportedDevices 0x%X", profile->mSupportedDevices);
4142
4143        module->mInputProfiles.add(profile);
4144        return NO_ERROR;
4145    } else {
4146        delete profile;
4147        return BAD_VALUE;
4148    }
4149}
4150
4151status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
4152{
4153    cnode *node = root->first_child;
4154
4155    IOProfile *profile = new IOProfile(module);
4156
4157    while (node) {
4158        if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4159            loadSamplingRates((char *)node->value, profile);
4160        } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4161            loadFormats((char *)node->value, profile);
4162        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4163            loadOutChannels((char *)node->value, profile);
4164        } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4165            profile->mSupportedDevices = parseDeviceNames((char *)node->value);
4166        } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4167            profile->mFlags = parseFlagNames((char *)node->value);
4168        }
4169        node = node->next;
4170    }
4171    ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
4172            "loadOutput() invalid supported devices");
4173    ALOGW_IF(profile->mChannelMasks.size() == 0,
4174            "loadOutput() invalid supported channel masks");
4175    ALOGW_IF(profile->mSamplingRates.size() == 0,
4176            "loadOutput() invalid supported sampling rates");
4177    ALOGW_IF(profile->mFormats.size() == 0,
4178            "loadOutput() invalid supported formats");
4179    if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
4180            (profile->mChannelMasks.size() != 0) &&
4181            (profile->mSamplingRates.size() != 0) &&
4182            (profile->mFormats.size() != 0)) {
4183
4184        ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
4185              profile->mSupportedDevices, profile->mFlags);
4186
4187        module->mOutputProfiles.add(profile);
4188        return NO_ERROR;
4189    } else {
4190        delete profile;
4191        return BAD_VALUE;
4192    }
4193}
4194
4195void AudioPolicyManagerBase::loadHwModule(cnode *root)
4196{
4197    cnode *node = config_find(root, OUTPUTS_TAG);
4198    status_t status = NAME_NOT_FOUND;
4199
4200    HwModule *module = new HwModule(root->name);
4201
4202    if (node != NULL) {
4203        if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
4204            mHasA2dp = true;
4205        } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
4206            mHasUsb = true;
4207        } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
4208            mHasRemoteSubmix = true;
4209        }
4210
4211        node = node->first_child;
4212        while (node) {
4213            ALOGV("loadHwModule() loading output %s", node->name);
4214            status_t tmpStatus = loadOutput(node, module);
4215            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4216                status = tmpStatus;
4217            }
4218            node = node->next;
4219        }
4220    }
4221    node = config_find(root, INPUTS_TAG);
4222    if (node != NULL) {
4223        node = node->first_child;
4224        while (node) {
4225            ALOGV("loadHwModule() loading input %s", node->name);
4226            status_t tmpStatus = loadInput(node, module);
4227            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4228                status = tmpStatus;
4229            }
4230            node = node->next;
4231        }
4232    }
4233    if (status == NO_ERROR) {
4234        mHwModules.add(module);
4235    } else {
4236        delete module;
4237    }
4238}
4239
4240void AudioPolicyManagerBase::loadHwModules(cnode *root)
4241{
4242    cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4243    if (node == NULL) {
4244        return;
4245    }
4246
4247    node = node->first_child;
4248    while (node) {
4249        ALOGV("loadHwModules() loading module %s", node->name);
4250        loadHwModule(node);
4251        node = node->next;
4252    }
4253}
4254
4255void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
4256{
4257    cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4258    if (node == NULL) {
4259        return;
4260    }
4261    node = node->first_child;
4262    while (node) {
4263        if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4264            mAttachedOutputDevices = parseDeviceNames((char *)node->value);
4265            ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
4266                    "loadGlobalConfig() no attached output devices");
4267            ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
4268        } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4269            mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4270                                              ARRAY_SIZE(sDeviceNameToEnumTable),
4271                                              (char *)node->value);
4272            ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
4273                    "loadGlobalConfig() default device not specified");
4274            ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
4275        } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4276            mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
4277            ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
4278        } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4279            mSpeakerDrcEnabled = stringToBool((char *)node->value);
4280            ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4281        }
4282        node = node->next;
4283    }
4284}
4285
4286status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
4287{
4288    cnode *root;
4289    char *data;
4290
4291    data = (char *)load_file(path, NULL);
4292    if (data == NULL) {
4293        return -ENODEV;
4294    }
4295    root = config_node("", "");
4296    config_load(root, data);
4297
4298    loadGlobalConfig(root);
4299    loadHwModules(root);
4300
4301    config_free(root);
4302    free(root);
4303    free(data);
4304
4305    ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4306
4307    return NO_ERROR;
4308}
4309
4310void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
4311{
4312    HwModule *module;
4313    IOProfile *profile;
4314
4315    mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
4316    mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
4317    mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
4318
4319    module = new HwModule("primary");
4320
4321    profile = new IOProfile(module);
4322    profile->mSamplingRates.add(44100);
4323    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4324    profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4325    profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
4326    profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4327    module->mOutputProfiles.add(profile);
4328
4329    profile = new IOProfile(module);
4330    profile->mSamplingRates.add(8000);
4331    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4332    profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4333    profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
4334    module->mInputProfiles.add(profile);
4335
4336    mHwModules.add(module);
4337}
4338
4339}; // namespace android
4340