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