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