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