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