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