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