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