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