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