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