AudioPolicyManager.cpp revision 41b0e2421a0cf8dc22f224ea078678d7db651bda
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 <hardware_legacy/audio_policy_conf.h>
42#include <media/AudioParameter.h>
43#include "AudioPolicyManager.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};
105
106const StringToEnum sFlagNameToEnumTable[] = {
107    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
108    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
109    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
110    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
111    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
112    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
113};
114
115const StringToEnum sFormatNameToEnumTable[] = {
116    STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
117    STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
118    STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
119    STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
120    STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
121    STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
122    STRING_TO_ENUM(AUDIO_FORMAT_MP3),
123    STRING_TO_ENUM(AUDIO_FORMAT_AAC),
124    STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
125};
126
127const StringToEnum sOutChannelsNameToEnumTable[] = {
128    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
129    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
130    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
131    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
132};
133
134const StringToEnum sInChannelsNameToEnumTable[] = {
135    STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
136    STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
137    STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
138};
139
140
141uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
142                                              size_t size,
143                                              const char *name)
144{
145    for (size_t i = 0; i < size; i++) {
146        if (strcmp(table[i].name, name) == 0) {
147            ALOGV("stringToEnum() found %s", table[i].name);
148            return table[i].value;
149        }
150    }
151    return 0;
152}
153
154const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
155                                              size_t size,
156                                              uint32_t value)
157{
158    for (size_t i = 0; i < size; i++) {
159        if (table[i].value == value) {
160            return table[i].name;
161        }
162    }
163    return "";
164}
165
166bool AudioPolicyManager::stringToBool(const char *value)
167{
168    return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
169}
170
171
172// ----------------------------------------------------------------------------
173// AudioPolicyInterface implementation
174// ----------------------------------------------------------------------------
175
176
177status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
178                                                          audio_policy_dev_state_t state,
179                                                  const char *device_address)
180{
181    String8 address = String8(device_address);
182
183    ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
184
185    // connect/disconnect only 1 device at a time
186    if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
187
188    // handle output devices
189    if (audio_is_output_device(device)) {
190        SortedVector <audio_io_handle_t> outputs;
191
192        sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
193                                                            address,
194                                                            0);
195        ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
196
197        // save a copy of the opened output descriptors before any output is opened or closed
198        // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
199        mPreviousOutputs = mOutputs;
200        switch (state)
201        {
202        // handle output device connection
203        case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
204            if (index >= 0) {
205                ALOGW("setDeviceConnectionState() device already connected: %x", device);
206                return INVALID_OPERATION;
207            }
208            ALOGV("setDeviceConnectionState() connecting device %x", device);
209
210            if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
211                return INVALID_OPERATION;
212            }
213            ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
214                  outputs.size());
215            // register new device as available
216            index = mAvailableOutputDevices.add(devDesc);
217            if (index >= 0) {
218                mAvailableOutputDevices[index]->mId = nextUniqueId();
219            } else {
220                return NO_MEMORY;
221            }
222
223            break;
224        // handle output device disconnection
225        case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
226            if (index < 0) {
227                ALOGW("setDeviceConnectionState() device not connected: %x", device);
228                return INVALID_OPERATION;
229            }
230
231            ALOGV("setDeviceConnectionState() disconnecting device %x", device);
232            // remove device from available output devices
233            mAvailableOutputDevices.remove(devDesc);
234
235            checkOutputsForDevice(device, state, outputs, address);
236            // not currently handling multiple simultaneous submixes: ignoring remote submix
237            //   case and address
238            } break;
239
240        default:
241            ALOGE("setDeviceConnectionState() invalid state: %x", state);
242            return BAD_VALUE;
243        }
244
245        // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
246        // output is suspended before any tracks are moved to it
247        checkA2dpSuspend();
248        checkOutputForAllStrategies();
249        // outputs must be closed after checkOutputForAllStrategies() is executed
250        if (!outputs.isEmpty()) {
251            for (size_t i = 0; i < outputs.size(); i++) {
252                AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
253                // close unused outputs after device disconnection or direct outputs that have been
254                // opened by checkOutputsForDevice() to query dynamic parameters
255                if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
256                        (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
257                         (desc->mDirectOpenCount == 0))) {
258                    closeOutput(outputs[i]);
259                }
260            }
261            // check again after closing A2DP output to reset mA2dpSuspended if needed
262            checkA2dpSuspend();
263        }
264
265        updateDevicesAndOutputs();
266        for (size_t i = 0; i < mOutputs.size(); i++) {
267            // do not force device change on duplicated output because if device is 0, it will
268            // also force a device 0 for the two outputs it is duplicated to which may override
269            // a valid device selection on those outputs.
270            setOutputDevice(mOutputs.keyAt(i),
271                            getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
272                            !mOutputs.valueAt(i)->isDuplicated(),
273                            0);
274        }
275
276        if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
277            device = AUDIO_DEVICE_IN_WIRED_HEADSET;
278        } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
279                   device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
280                   device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
281            device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
282        } else {
283            return NO_ERROR;
284        }
285    }  // end if is output device
286
287    // handle input devices
288    if (audio_is_input_device(device)) {
289        SortedVector <audio_io_handle_t> inputs;
290
291        sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
292                                                            address,
293                                                            0);
294
295        ssize_t index = mAvailableInputDevices.indexOf(devDesc);
296        switch (state)
297        {
298        // handle input device connection
299        case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
300            if (index >= 0) {
301                ALOGW("setDeviceConnectionState() device already connected: %d", device);
302                return INVALID_OPERATION;
303            }
304            if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
305                return INVALID_OPERATION;
306            }
307
308            index = mAvailableInputDevices.add(devDesc);
309            if (index >= 0) {
310                mAvailableInputDevices[index]->mId = nextUniqueId();
311            } else {
312                return NO_MEMORY;
313            }
314        } break;
315
316        // handle input device disconnection
317        case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
318            if (index < 0) {
319                ALOGW("setDeviceConnectionState() device not connected: %d", device);
320                return INVALID_OPERATION;
321            }
322            checkInputsForDevice(device, state, inputs, address);
323            mAvailableInputDevices.remove(devDesc);
324        } break;
325
326        default:
327            ALOGE("setDeviceConnectionState() invalid state: %x", state);
328            return BAD_VALUE;
329        }
330
331        closeAllInputs();
332
333        return NO_ERROR;
334    } // end if is input device
335
336    ALOGW("setDeviceConnectionState() invalid device: %x", device);
337    return BAD_VALUE;
338}
339
340audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
341                                                  const char *device_address)
342{
343    audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
344    String8 address = String8(device_address);
345    sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
346                                                        String8(device_address),
347                                                        0);
348    ssize_t index;
349    DeviceVector *deviceVector;
350
351    if (audio_is_output_device(device)) {
352        deviceVector = &mAvailableOutputDevices;
353    } else if (audio_is_input_device(device)) {
354        deviceVector = &mAvailableInputDevices;
355    } else {
356        ALOGW("getDeviceConnectionState() invalid device type %08x", device);
357        return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
358    }
359
360    index = deviceVector->indexOf(devDesc);
361    if (index >= 0) {
362        return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
363    } else {
364        return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
365    }
366}
367
368void AudioPolicyManager::setPhoneState(audio_mode_t state)
369{
370    ALOGV("setPhoneState() state %d", state);
371    audio_devices_t newDevice = AUDIO_DEVICE_NONE;
372    if (state < 0 || state >= AUDIO_MODE_CNT) {
373        ALOGW("setPhoneState() invalid state %d", state);
374        return;
375    }
376
377    if (state == mPhoneState ) {
378        ALOGW("setPhoneState() setting same state %d", state);
379        return;
380    }
381
382    // if leaving call state, handle special case of active streams
383    // pertaining to sonification strategy see handleIncallSonification()
384    if (isInCall()) {
385        ALOGV("setPhoneState() in call state management: new state is %d", state);
386        for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
387            handleIncallSonification((audio_stream_type_t)stream, false, true);
388        }
389    }
390
391    // store previous phone state for management of sonification strategy below
392    int oldState = mPhoneState;
393    mPhoneState = state;
394    bool force = false;
395
396    // are we entering or starting a call
397    if (!isStateInCall(oldState) && isStateInCall(state)) {
398        ALOGV("  Entering call in setPhoneState()");
399        // force routing command to audio hardware when starting a call
400        // even if no device change is needed
401        force = true;
402        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
403            mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
404                    sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
405        }
406    } else if (isStateInCall(oldState) && !isStateInCall(state)) {
407        ALOGV("  Exiting call in setPhoneState()");
408        // force routing command to audio hardware when exiting a call
409        // even if no device change is needed
410        force = true;
411        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
412            mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
413                    sVolumeProfiles[AUDIO_STREAM_DTMF][j];
414        }
415    } else if (isStateInCall(state) && (state != oldState)) {
416        ALOGV("  Switching between telephony and VoIP in setPhoneState()");
417        // force routing command to audio hardware when switching between telephony and VoIP
418        // even if no device change is needed
419        force = true;
420    }
421
422    // check for device and output changes triggered by new phone state
423    newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
424    checkA2dpSuspend();
425    checkOutputForAllStrategies();
426    updateDevicesAndOutputs();
427
428    AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
429
430    // force routing command to audio hardware when ending call
431    // even if no device change is needed
432    if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
433        newDevice = hwOutputDesc->device();
434    }
435
436    int delayMs = 0;
437    if (isStateInCall(state)) {
438        nsecs_t sysTime = systemTime();
439        for (size_t i = 0; i < mOutputs.size(); i++) {
440            AudioOutputDescriptor *desc = mOutputs.valueAt(i);
441            // mute media and sonification strategies and delay device switch by the largest
442            // latency of any output where either strategy is active.
443            // This avoid sending the ring tone or music tail into the earpiece or headset.
444            if ((desc->isStrategyActive(STRATEGY_MEDIA,
445                                     SONIFICATION_HEADSET_MUSIC_DELAY,
446                                     sysTime) ||
447                    desc->isStrategyActive(STRATEGY_SONIFICATION,
448                                         SONIFICATION_HEADSET_MUSIC_DELAY,
449                                         sysTime)) &&
450                    (delayMs < (int)desc->mLatency*2)) {
451                delayMs = desc->mLatency*2;
452            }
453            setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
454            setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
455                getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
456            setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
457            setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
458                getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
459        }
460    }
461
462    // change routing is necessary
463    setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
464
465    // if entering in call state, handle special case of active streams
466    // pertaining to sonification strategy see handleIncallSonification()
467    if (isStateInCall(state)) {
468        ALOGV("setPhoneState() in call state management: new state is %d", state);
469        for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
470            handleIncallSonification((audio_stream_type_t)stream, true, true);
471        }
472    }
473
474    // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
475    if (state == AUDIO_MODE_RINGTONE &&
476        isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
477        mLimitRingtoneVolume = true;
478    } else {
479        mLimitRingtoneVolume = false;
480    }
481}
482
483void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
484                                         audio_policy_forced_cfg_t config)
485{
486    ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
487
488    bool forceVolumeReeval = false;
489    switch(usage) {
490    case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
491        if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
492            config != AUDIO_POLICY_FORCE_NONE) {
493            ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
494            return;
495        }
496        forceVolumeReeval = true;
497        mForceUse[usage] = config;
498        break;
499    case AUDIO_POLICY_FORCE_FOR_MEDIA:
500        if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
501            config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
502            config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
503            config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
504            config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
505            ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
506            return;
507        }
508        mForceUse[usage] = config;
509        break;
510    case AUDIO_POLICY_FORCE_FOR_RECORD:
511        if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
512            config != AUDIO_POLICY_FORCE_NONE) {
513            ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
514            return;
515        }
516        mForceUse[usage] = config;
517        break;
518    case AUDIO_POLICY_FORCE_FOR_DOCK:
519        if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
520            config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
521            config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
522            config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
523            config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
524            ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
525        }
526        forceVolumeReeval = true;
527        mForceUse[usage] = config;
528        break;
529    case AUDIO_POLICY_FORCE_FOR_SYSTEM:
530        if (config != AUDIO_POLICY_FORCE_NONE &&
531            config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
532            ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
533        }
534        forceVolumeReeval = true;
535        mForceUse[usage] = config;
536        break;
537    default:
538        ALOGW("setForceUse() invalid usage %d", usage);
539        break;
540    }
541
542    // check for device and output changes triggered by new force usage
543    checkA2dpSuspend();
544    checkOutputForAllStrategies();
545    updateDevicesAndOutputs();
546    for (size_t i = 0; i < mOutputs.size(); i++) {
547        audio_io_handle_t output = mOutputs.keyAt(i);
548        audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
549        setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
550        if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
551            applyStreamVolumes(output, newDevice, 0, true);
552        }
553    }
554
555    audio_io_handle_t activeInput = getActiveInput();
556    if (activeInput != 0) {
557        AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
558        audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
559        if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
560            ALOGV("setForceUse() changing device from %x to %x for input %d",
561                    inputDesc->mDevice, newDevice, activeInput);
562            inputDesc->mDevice = newDevice;
563            AudioParameter param = AudioParameter();
564            param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
565            mpClientInterface->setParameters(activeInput, param.toString());
566        }
567    }
568
569}
570
571audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
572{
573    return mForceUse[usage];
574}
575
576void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
577{
578    ALOGV("setSystemProperty() property %s, value %s", property, value);
579}
580
581// Find a direct output profile compatible with the parameters passed, even if the input flags do
582// not explicitly request a direct output
583AudioPolicyManager::IOProfile *AudioPolicyManager::getProfileForDirectOutput(
584                                                               audio_devices_t device,
585                                                               uint32_t samplingRate,
586                                                               audio_format_t format,
587                                                               audio_channel_mask_t channelMask,
588                                                               audio_output_flags_t flags)
589{
590    for (size_t i = 0; i < mHwModules.size(); i++) {
591        if (mHwModules[i]->mHandle == 0) {
592            continue;
593        }
594        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
595            IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
596            bool found = false;
597            if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
598                if (profile->isCompatibleProfile(device, samplingRate, format,
599                                           channelMask,
600                                           AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
601                    found = true;
602                }
603            } else {
604                if (profile->isCompatibleProfile(device, samplingRate, format,
605                                           channelMask,
606                                           AUDIO_OUTPUT_FLAG_DIRECT)) {
607                    found = true;
608                }
609            }
610            if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
611                return profile;
612            }
613        }
614    }
615    return 0;
616}
617
618audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
619                                    uint32_t samplingRate,
620                                    audio_format_t format,
621                                    audio_channel_mask_t channelMask,
622                                    audio_output_flags_t flags,
623                                    const audio_offload_info_t *offloadInfo)
624{
625    audio_io_handle_t output = 0;
626    uint32_t latency = 0;
627    routing_strategy strategy = getStrategy(stream);
628    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
629    ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
630          device, stream, samplingRate, format, channelMask, flags);
631
632#ifdef AUDIO_POLICY_TEST
633    if (mCurOutput != 0) {
634        ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
635                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
636
637        if (mTestOutputs[mCurOutput] == 0) {
638            ALOGV("getOutput() opening test output");
639            AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
640            outputDesc->mDevice = mTestDevice;
641            outputDesc->mSamplingRate = mTestSamplingRate;
642            outputDesc->mFormat = mTestFormat;
643            outputDesc->mChannelMask = mTestChannels;
644            outputDesc->mLatency = mTestLatencyMs;
645            outputDesc->mFlags =
646                    (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
647            outputDesc->mRefCount[stream] = 0;
648            mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
649                                            &outputDesc->mSamplingRate,
650                                            &outputDesc->mFormat,
651                                            &outputDesc->mChannelMask,
652                                            &outputDesc->mLatency,
653                                            outputDesc->mFlags,
654                                            offloadInfo);
655            if (mTestOutputs[mCurOutput]) {
656                AudioParameter outputCmd = AudioParameter();
657                outputCmd.addInt(String8("set_id"),mCurOutput);
658                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
659                addOutput(mTestOutputs[mCurOutput], outputDesc);
660            }
661        }
662        return mTestOutputs[mCurOutput];
663    }
664#endif //AUDIO_POLICY_TEST
665
666    // open a direct output if required by specified parameters
667    //force direct flag if offload flag is set: offloading implies a direct output stream
668    // and all common behaviors are driven by checking only the direct flag
669    // this should normally be set appropriately in the policy configuration file
670    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
671        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
672    }
673
674    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
675    // creating an offloaded track and tearing it down immediately after start when audioflinger
676    // detects there is an active non offloadable effect.
677    // FIXME: We should check the audio session here but we do not have it in this context.
678    // This may prevent offloading in rare situations where effects are left active by apps
679    // in the background.
680    IOProfile *profile = NULL;
681    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
682            !isNonOffloadableEffectEnabled()) {
683        profile = getProfileForDirectOutput(device,
684                                           samplingRate,
685                                           format,
686                                           channelMask,
687                                           (audio_output_flags_t)flags);
688    }
689
690    if (profile != NULL) {
691        AudioOutputDescriptor *outputDesc = NULL;
692
693        for (size_t i = 0; i < mOutputs.size(); i++) {
694            AudioOutputDescriptor *desc = mOutputs.valueAt(i);
695            if (!desc->isDuplicated() && (profile == desc->mProfile)) {
696                outputDesc = desc;
697                // reuse direct output if currently open and configured with same parameters
698                if ((samplingRate == outputDesc->mSamplingRate) &&
699                        (format == outputDesc->mFormat) &&
700                        (channelMask == outputDesc->mChannelMask)) {
701                    outputDesc->mDirectOpenCount++;
702                    ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
703                    return mOutputs.keyAt(i);
704                }
705            }
706        }
707        // close direct output if currently open and configured with different parameters
708        if (outputDesc != NULL) {
709            closeOutput(outputDesc->mId);
710        }
711        outputDesc = new AudioOutputDescriptor(profile);
712        outputDesc->mDevice = device;
713        outputDesc->mSamplingRate = samplingRate;
714        outputDesc->mFormat = format;
715        outputDesc->mChannelMask = channelMask;
716        outputDesc->mLatency = 0;
717        outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
718        outputDesc->mRefCount[stream] = 0;
719        outputDesc->mStopTime[stream] = 0;
720        outputDesc->mDirectOpenCount = 1;
721        output = mpClientInterface->openOutput(profile->mModule->mHandle,
722                                        &outputDesc->mDevice,
723                                        &outputDesc->mSamplingRate,
724                                        &outputDesc->mFormat,
725                                        &outputDesc->mChannelMask,
726                                        &outputDesc->mLatency,
727                                        outputDesc->mFlags,
728                                        offloadInfo);
729
730        // only accept an output with the requested parameters
731        if (output == 0 ||
732            (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
733            (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
734            (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
735            ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
736                    "format %d %d, channelMask %04x %04x", output, samplingRate,
737                    outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
738                    outputDesc->mChannelMask);
739            if (output != 0) {
740                mpClientInterface->closeOutput(output);
741            }
742            delete outputDesc;
743            return 0;
744        }
745        audio_io_handle_t srcOutput = getOutputForEffect();
746        addOutput(output, outputDesc);
747        audio_io_handle_t dstOutput = getOutputForEffect();
748        if (dstOutput == output) {
749            mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
750        }
751        mPreviousOutputs = mOutputs;
752        ALOGV("getOutput() returns new direct output %d", output);
753        return output;
754    }
755
756    // ignoring channel mask due to downmix capability in mixer
757
758    // open a non direct output
759
760    // for non direct outputs, only PCM is supported
761    if (audio_is_linear_pcm(format)) {
762        // get which output is suitable for the specified stream. The actual
763        // routing change will happen when startOutput() will be called
764        SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
765
766        output = selectOutput(outputs, flags);
767    }
768    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
769            "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
770
771    ALOGV("getOutput() returns output %d", output);
772
773    return output;
774}
775
776audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
777                                                       audio_output_flags_t flags)
778{
779    // select one output among several that provide a path to a particular device or set of
780    // devices (the list was previously build by getOutputsForDevice()).
781    // The priority is as follows:
782    // 1: the output with the highest number of requested policy flags
783    // 2: the primary output
784    // 3: the first output in the list
785
786    if (outputs.size() == 0) {
787        return 0;
788    }
789    if (outputs.size() == 1) {
790        return outputs[0];
791    }
792
793    int maxCommonFlags = 0;
794    audio_io_handle_t outputFlags = 0;
795    audio_io_handle_t outputPrimary = 0;
796
797    for (size_t i = 0; i < outputs.size(); i++) {
798        AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
799        if (!outputDesc->isDuplicated()) {
800            int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
801            if (commonFlags > maxCommonFlags) {
802                outputFlags = outputs[i];
803                maxCommonFlags = commonFlags;
804                ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
805            }
806            if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
807                outputPrimary = outputs[i];
808            }
809        }
810    }
811
812    if (outputFlags != 0) {
813        return outputFlags;
814    }
815    if (outputPrimary != 0) {
816        return outputPrimary;
817    }
818
819    return outputs[0];
820}
821
822status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
823                                             audio_stream_type_t stream,
824                                             int session)
825{
826    ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
827    ssize_t index = mOutputs.indexOfKey(output);
828    if (index < 0) {
829        ALOGW("startOutput() unknown output %d", output);
830        return BAD_VALUE;
831    }
832
833    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
834
835    // increment usage count for this stream on the requested output:
836    // NOTE that the usage count is the same for duplicated output and hardware output which is
837    // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
838    outputDesc->changeRefCount(stream, 1);
839
840    if (outputDesc->mRefCount[stream] == 1) {
841        audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
842        routing_strategy strategy = getStrategy(stream);
843        bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
844                            (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
845        uint32_t waitMs = 0;
846        bool force = false;
847        for (size_t i = 0; i < mOutputs.size(); i++) {
848            AudioOutputDescriptor *desc = mOutputs.valueAt(i);
849            if (desc != outputDesc) {
850                // force a device change if any other output is managed by the same hw
851                // module and has a current device selection that differs from selected device.
852                // In this case, the audio HAL must receive the new device selection so that it can
853                // change the device currently selected by the other active output.
854                if (outputDesc->sharesHwModuleWith(desc) &&
855                    desc->device() != newDevice) {
856                    force = true;
857                }
858                // wait for audio on other active outputs to be presented when starting
859                // a notification so that audio focus effect can propagate.
860                uint32_t latency = desc->latency();
861                if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
862                    waitMs = latency;
863                }
864            }
865        }
866        uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
867
868        // handle special case for sonification while in call
869        if (isInCall()) {
870            handleIncallSonification(stream, true, false);
871        }
872
873        // apply volume rules for current stream and device if necessary
874        checkAndSetVolume(stream,
875                          mStreams[stream].getVolumeIndex(newDevice),
876                          output,
877                          newDevice);
878
879        // update the outputs if starting an output with a stream that can affect notification
880        // routing
881        handleNotificationRoutingForStream(stream);
882        if (waitMs > muteWaitMs) {
883            usleep((waitMs - muteWaitMs) * 2 * 1000);
884        }
885    }
886    return NO_ERROR;
887}
888
889
890status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
891                                            audio_stream_type_t stream,
892                                            int session)
893{
894    ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
895    ssize_t index = mOutputs.indexOfKey(output);
896    if (index < 0) {
897        ALOGW("stopOutput() unknown output %d", output);
898        return BAD_VALUE;
899    }
900
901    AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
902
903    // handle special case for sonification while in call
904    if (isInCall()) {
905        handleIncallSonification(stream, false, false);
906    }
907
908    if (outputDesc->mRefCount[stream] > 0) {
909        // decrement usage count of this stream on the output
910        outputDesc->changeRefCount(stream, -1);
911        // store time at which the stream was stopped - see isStreamActive()
912        if (outputDesc->mRefCount[stream] == 0) {
913            outputDesc->mStopTime[stream] = systemTime();
914            audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
915            // delay the device switch by twice the latency because stopOutput() is executed when
916            // the track stop() command is received and at that time the audio track buffer can
917            // still contain data that needs to be drained. The latency only covers the audio HAL
918            // and kernel buffers. Also the latency does not always include additional delay in the
919            // audio path (audio DSP, CODEC ...)
920            setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
921
922            // force restoring the device selection on other active outputs if it differs from the
923            // one being selected for this output
924            for (size_t i = 0; i < mOutputs.size(); i++) {
925                audio_io_handle_t curOutput = mOutputs.keyAt(i);
926                AudioOutputDescriptor *desc = mOutputs.valueAt(i);
927                if (curOutput != output &&
928                        desc->isActive() &&
929                        outputDesc->sharesHwModuleWith(desc) &&
930                        (newDevice != desc->device())) {
931                    setOutputDevice(curOutput,
932                                    getNewDevice(curOutput, false /*fromCache*/),
933                                    true,
934                                    outputDesc->mLatency*2);
935                }
936            }
937            // update the outputs if stopping one with a stream that can affect notification routing
938            handleNotificationRoutingForStream(stream);
939        }
940        return NO_ERROR;
941    } else {
942        ALOGW("stopOutput() refcount is already 0 for output %d", output);
943        return INVALID_OPERATION;
944    }
945}
946
947void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
948{
949    ALOGV("releaseOutput() %d", output);
950    ssize_t index = mOutputs.indexOfKey(output);
951    if (index < 0) {
952        ALOGW("releaseOutput() releasing unknown output %d", output);
953        return;
954    }
955
956#ifdef AUDIO_POLICY_TEST
957    int testIndex = testOutputIndex(output);
958    if (testIndex != 0) {
959        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
960        if (outputDesc->isActive()) {
961            mpClientInterface->closeOutput(output);
962            delete mOutputs.valueAt(index);
963            mOutputs.removeItem(output);
964            mTestOutputs[testIndex] = 0;
965        }
966        return;
967    }
968#endif //AUDIO_POLICY_TEST
969
970    AudioOutputDescriptor *desc = mOutputs.valueAt(index);
971    if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
972        if (desc->mDirectOpenCount <= 0) {
973            ALOGW("releaseOutput() invalid open count %d for output %d",
974                                                              desc->mDirectOpenCount, output);
975            return;
976        }
977        if (--desc->mDirectOpenCount == 0) {
978            closeOutput(output);
979            // If effects where present on the output, audioflinger moved them to the primary
980            // output by default: move them back to the appropriate output.
981            audio_io_handle_t dstOutput = getOutputForEffect();
982            if (dstOutput != mPrimaryOutput) {
983                mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
984            }
985        }
986    }
987}
988
989
990audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
991                                    uint32_t samplingRate,
992                                    audio_format_t format,
993                                    audio_channel_mask_t channelMask,
994                                    audio_in_acoustics_t acoustics)
995{
996    audio_io_handle_t input = 0;
997    audio_devices_t device = getDeviceForInputSource(inputSource);
998
999    ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1000          inputSource, samplingRate, format, channelMask, acoustics);
1001
1002    if (device == AUDIO_DEVICE_NONE) {
1003        ALOGW("getInput() could not find device for inputSource %d", inputSource);
1004        return 0;
1005    }
1006
1007    // adapt channel selection to input source
1008    switch(inputSource) {
1009    case AUDIO_SOURCE_VOICE_UPLINK:
1010        channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1011        break;
1012    case AUDIO_SOURCE_VOICE_DOWNLINK:
1013        channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1014        break;
1015    case AUDIO_SOURCE_VOICE_CALL:
1016        channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1017        break;
1018    default:
1019        break;
1020    }
1021
1022    IOProfile *profile = getInputProfile(device,
1023                                         samplingRate,
1024                                         format,
1025                                         channelMask);
1026    if (profile == NULL) {
1027        ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1028                "channelMask %04x",
1029                device, samplingRate, format, channelMask);
1030        return 0;
1031    }
1032
1033    if (profile->mModule->mHandle == 0) {
1034        ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1035        return 0;
1036    }
1037
1038    AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1039
1040    inputDesc->mInputSource = inputSource;
1041    inputDesc->mDevice = device;
1042    inputDesc->mSamplingRate = samplingRate;
1043    inputDesc->mFormat = format;
1044    inputDesc->mChannelMask = channelMask;
1045    inputDesc->mRefCount = 0;
1046    input = mpClientInterface->openInput(profile->mModule->mHandle,
1047                                    &inputDesc->mDevice,
1048                                    &inputDesc->mSamplingRate,
1049                                    &inputDesc->mFormat,
1050                                    &inputDesc->mChannelMask);
1051
1052    // only accept input with the exact requested set of parameters
1053    if (input == 0 ||
1054        (samplingRate != inputDesc->mSamplingRate) ||
1055        (format != inputDesc->mFormat) ||
1056        (channelMask != inputDesc->mChannelMask)) {
1057        ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1058                samplingRate, format, channelMask);
1059        if (input != 0) {
1060            mpClientInterface->closeInput(input);
1061        }
1062        delete inputDesc;
1063        return 0;
1064    }
1065    addInput(input, inputDesc);
1066    return input;
1067}
1068
1069status_t AudioPolicyManager::startInput(audio_io_handle_t input)
1070{
1071    ALOGV("startInput() input %d", input);
1072    ssize_t index = mInputs.indexOfKey(input);
1073    if (index < 0) {
1074        ALOGW("startInput() unknown input %d", input);
1075        return BAD_VALUE;
1076    }
1077    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1078
1079#ifdef AUDIO_POLICY_TEST
1080    if (mTestInput == 0)
1081#endif //AUDIO_POLICY_TEST
1082    {
1083        // refuse 2 active AudioRecord clients at the same time except if the active input
1084        // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1085        audio_io_handle_t activeInput = getActiveInput();
1086        if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1087            AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1088            if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1089                ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1090                stopInput(activeInput);
1091                releaseInput(activeInput);
1092            } else {
1093                ALOGW("startInput() input %d failed: other input already started", input);
1094                return INVALID_OPERATION;
1095            }
1096        }
1097    }
1098
1099    audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1100    if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1101        inputDesc->mDevice = newDevice;
1102    }
1103
1104    // automatically enable the remote submix output when input is started
1105    if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1106        setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1107                AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1108    }
1109
1110    AudioParameter param = AudioParameter();
1111    param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1112
1113    int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1114                                        AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1115
1116    param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1117    ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1118
1119    mpClientInterface->setParameters(input, param.toString());
1120
1121    inputDesc->mRefCount = 1;
1122    return NO_ERROR;
1123}
1124
1125status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
1126{
1127    ALOGV("stopInput() input %d", input);
1128    ssize_t index = mInputs.indexOfKey(input);
1129    if (index < 0) {
1130        ALOGW("stopInput() unknown input %d", input);
1131        return BAD_VALUE;
1132    }
1133    AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1134
1135    if (inputDesc->mRefCount == 0) {
1136        ALOGW("stopInput() input %d already stopped", input);
1137        return INVALID_OPERATION;
1138    } else {
1139        // automatically disable the remote submix output when input is stopped
1140        if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1141            setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1142                    AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1143        }
1144
1145        AudioParameter param = AudioParameter();
1146        param.addInt(String8(AudioParameter::keyRouting), 0);
1147        mpClientInterface->setParameters(input, param.toString());
1148        inputDesc->mRefCount = 0;
1149        return NO_ERROR;
1150    }
1151}
1152
1153void AudioPolicyManager::releaseInput(audio_io_handle_t input)
1154{
1155    ALOGV("releaseInput() %d", input);
1156    ssize_t index = mInputs.indexOfKey(input);
1157    if (index < 0) {
1158        ALOGW("releaseInput() releasing unknown input %d", input);
1159        return;
1160    }
1161    mpClientInterface->closeInput(input);
1162    delete mInputs.valueAt(index);
1163    mInputs.removeItem(input);
1164    ALOGV("releaseInput() exit");
1165}
1166
1167void AudioPolicyManager::closeAllInputs() {
1168    for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1169        mpClientInterface->closeInput(mInputs.keyAt(input_index));
1170    }
1171    mInputs.clear();
1172}
1173
1174void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
1175                                            int indexMin,
1176                                            int indexMax)
1177{
1178    ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1179    if (indexMin < 0 || indexMin >= indexMax) {
1180        ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1181        return;
1182    }
1183    mStreams[stream].mIndexMin = indexMin;
1184    mStreams[stream].mIndexMax = indexMax;
1185}
1186
1187status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
1188                                                      int index,
1189                                                      audio_devices_t device)
1190{
1191
1192    if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1193        return BAD_VALUE;
1194    }
1195    if (!audio_is_output_device(device)) {
1196        return BAD_VALUE;
1197    }
1198
1199    // Force max volume if stream cannot be muted
1200    if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1201
1202    ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1203          stream, device, index);
1204
1205    // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1206    // clear all device specific values
1207    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1208        mStreams[stream].mIndexCur.clear();
1209    }
1210    mStreams[stream].mIndexCur.add(device, index);
1211
1212    // compute and apply stream volume on all outputs according to connected device
1213    status_t status = NO_ERROR;
1214    for (size_t i = 0; i < mOutputs.size(); i++) {
1215        audio_devices_t curDevice =
1216                getDeviceForVolume(mOutputs.valueAt(i)->device());
1217        if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1218            status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1219            if (volStatus != NO_ERROR) {
1220                status = volStatus;
1221            }
1222        }
1223    }
1224    return status;
1225}
1226
1227status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
1228                                                      int *index,
1229                                                      audio_devices_t device)
1230{
1231    if (index == NULL) {
1232        return BAD_VALUE;
1233    }
1234    if (!audio_is_output_device(device)) {
1235        return BAD_VALUE;
1236    }
1237    // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1238    // the strategy the stream belongs to.
1239    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1240        device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1241    }
1242    device = getDeviceForVolume(device);
1243
1244    *index =  mStreams[stream].getVolumeIndex(device);
1245    ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1246    return NO_ERROR;
1247}
1248
1249audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
1250                                            const SortedVector<audio_io_handle_t>& outputs)
1251{
1252    // select one output among several suitable for global effects.
1253    // The priority is as follows:
1254    // 1: An offloaded output. If the effect ends up not being offloadable,
1255    //    AudioFlinger will invalidate the track and the offloaded output
1256    //    will be closed causing the effect to be moved to a PCM output.
1257    // 2: A deep buffer output
1258    // 3: the first output in the list
1259
1260    if (outputs.size() == 0) {
1261        return 0;
1262    }
1263
1264    audio_io_handle_t outputOffloaded = 0;
1265    audio_io_handle_t outputDeepBuffer = 0;
1266
1267    for (size_t i = 0; i < outputs.size(); i++) {
1268        AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1269        ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1270        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1271            outputOffloaded = outputs[i];
1272        }
1273        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1274            outputDeepBuffer = outputs[i];
1275        }
1276    }
1277
1278    ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1279          outputOffloaded, outputDeepBuffer);
1280    if (outputOffloaded != 0) {
1281        return outputOffloaded;
1282    }
1283    if (outputDeepBuffer != 0) {
1284        return outputDeepBuffer;
1285    }
1286
1287    return outputs[0];
1288}
1289
1290audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
1291{
1292    // apply simple rule where global effects are attached to the same output as MUSIC streams
1293
1294    routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
1295    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1296    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1297
1298    audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1299    ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1300          output, (desc == NULL) ? "unspecified" : desc->name,  (desc == NULL) ? 0 : desc->flags);
1301
1302    return output;
1303}
1304
1305status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
1306                                audio_io_handle_t io,
1307                                uint32_t strategy,
1308                                int session,
1309                                int id)
1310{
1311    ssize_t index = mOutputs.indexOfKey(io);
1312    if (index < 0) {
1313        index = mInputs.indexOfKey(io);
1314        if (index < 0) {
1315            ALOGW("registerEffect() unknown io %d", io);
1316            return INVALID_OPERATION;
1317        }
1318    }
1319
1320    if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1321        ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1322                desc->name, desc->memoryUsage);
1323        return INVALID_OPERATION;
1324    }
1325    mTotalEffectsMemory += desc->memoryUsage;
1326    ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1327            desc->name, io, strategy, session, id);
1328    ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1329
1330    EffectDescriptor *pDesc = new EffectDescriptor();
1331    memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1332    pDesc->mIo = io;
1333    pDesc->mStrategy = (routing_strategy)strategy;
1334    pDesc->mSession = session;
1335    pDesc->mEnabled = false;
1336
1337    mEffects.add(id, pDesc);
1338
1339    return NO_ERROR;
1340}
1341
1342status_t AudioPolicyManager::unregisterEffect(int id)
1343{
1344    ssize_t index = mEffects.indexOfKey(id);
1345    if (index < 0) {
1346        ALOGW("unregisterEffect() unknown effect ID %d", id);
1347        return INVALID_OPERATION;
1348    }
1349
1350    EffectDescriptor *pDesc = mEffects.valueAt(index);
1351
1352    setEffectEnabled(pDesc, false);
1353
1354    if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1355        ALOGW("unregisterEffect() memory %d too big for total %d",
1356                pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1357        pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1358    }
1359    mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1360    ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1361            pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1362
1363    mEffects.removeItem(id);
1364    delete pDesc;
1365
1366    return NO_ERROR;
1367}
1368
1369status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
1370{
1371    ssize_t index = mEffects.indexOfKey(id);
1372    if (index < 0) {
1373        ALOGW("unregisterEffect() unknown effect ID %d", id);
1374        return INVALID_OPERATION;
1375    }
1376
1377    return setEffectEnabled(mEffects.valueAt(index), enabled);
1378}
1379
1380status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1381{
1382    if (enabled == pDesc->mEnabled) {
1383        ALOGV("setEffectEnabled(%s) effect already %s",
1384             enabled?"true":"false", enabled?"enabled":"disabled");
1385        return INVALID_OPERATION;
1386    }
1387
1388    if (enabled) {
1389        if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1390            ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1391                 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1392            return INVALID_OPERATION;
1393        }
1394        mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1395        ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1396    } else {
1397        if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1398            ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1399                    pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1400            pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1401        }
1402        mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1403        ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1404    }
1405    pDesc->mEnabled = enabled;
1406    return NO_ERROR;
1407}
1408
1409bool AudioPolicyManager::isNonOffloadableEffectEnabled()
1410{
1411    for (size_t i = 0; i < mEffects.size(); i++) {
1412        const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1413        if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1414                ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1415            ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1416                  pDesc->mDesc.name, pDesc->mSession);
1417            return true;
1418        }
1419    }
1420    return false;
1421}
1422
1423bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1424{
1425    nsecs_t sysTime = systemTime();
1426    for (size_t i = 0; i < mOutputs.size(); i++) {
1427        const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1428        if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
1429            return true;
1430        }
1431    }
1432    return false;
1433}
1434
1435bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
1436                                                    uint32_t inPastMs) const
1437{
1438    nsecs_t sysTime = systemTime();
1439    for (size_t i = 0; i < mOutputs.size(); i++) {
1440        const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1441        if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1442                outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
1443            return true;
1444        }
1445    }
1446    return false;
1447}
1448
1449bool AudioPolicyManager::isSourceActive(audio_source_t source) const
1450{
1451    for (size_t i = 0; i < mInputs.size(); i++) {
1452        const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1453        if ((inputDescriptor->mInputSource == (int)source ||
1454                (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
1455                 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1456             && (inputDescriptor->mRefCount > 0)) {
1457            return true;
1458        }
1459    }
1460    return false;
1461}
1462
1463
1464status_t AudioPolicyManager::dump(int fd)
1465{
1466    const size_t SIZE = 256;
1467    char buffer[SIZE];
1468    String8 result;
1469
1470    snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1471    result.append(buffer);
1472
1473    snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1474    result.append(buffer);
1475    snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1476    result.append(buffer);
1477    snprintf(buffer, SIZE, " Force use for communications %d\n",
1478             mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
1479    result.append(buffer);
1480    snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
1481    result.append(buffer);
1482    snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
1483    result.append(buffer);
1484    snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
1485    result.append(buffer);
1486    snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
1487    result.append(buffer);
1488
1489    snprintf(buffer, SIZE, " Available output devices:\n");
1490    result.append(buffer);
1491    write(fd, result.string(), result.size());
1492    DeviceDescriptor::dumpHeader(fd, 2);
1493    for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1494        mAvailableOutputDevices[i]->dump(fd, 2);
1495    }
1496    snprintf(buffer, SIZE, "\n Available input devices:\n");
1497    write(fd, buffer, strlen(buffer));
1498    DeviceDescriptor::dumpHeader(fd, 2);
1499    for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1500        mAvailableInputDevices[i]->dump(fd, 2);
1501    }
1502
1503    snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1504    write(fd, buffer, strlen(buffer));
1505    for (size_t i = 0; i < mHwModules.size(); i++) {
1506        snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1507        write(fd, buffer, strlen(buffer));
1508        mHwModules[i]->dump(fd);
1509    }
1510
1511    snprintf(buffer, SIZE, "\nOutputs dump:\n");
1512    write(fd, buffer, strlen(buffer));
1513    for (size_t i = 0; i < mOutputs.size(); i++) {
1514        snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1515        write(fd, buffer, strlen(buffer));
1516        mOutputs.valueAt(i)->dump(fd);
1517    }
1518
1519    snprintf(buffer, SIZE, "\nInputs dump:\n");
1520    write(fd, buffer, strlen(buffer));
1521    for (size_t i = 0; i < mInputs.size(); i++) {
1522        snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1523        write(fd, buffer, strlen(buffer));
1524        mInputs.valueAt(i)->dump(fd);
1525    }
1526
1527    snprintf(buffer, SIZE, "\nStreams dump:\n");
1528    write(fd, buffer, strlen(buffer));
1529    snprintf(buffer, SIZE,
1530             " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
1531    write(fd, buffer, strlen(buffer));
1532    for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
1533        snprintf(buffer, SIZE, " %02zu      ", i);
1534        write(fd, buffer, strlen(buffer));
1535        mStreams[i].dump(fd);
1536    }
1537
1538    snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1539            (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1540    write(fd, buffer, strlen(buffer));
1541
1542    snprintf(buffer, SIZE, "Registered effects:\n");
1543    write(fd, buffer, strlen(buffer));
1544    for (size_t i = 0; i < mEffects.size(); i++) {
1545        snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1546        write(fd, buffer, strlen(buffer));
1547        mEffects.valueAt(i)->dump(fd);
1548    }
1549
1550
1551    return NO_ERROR;
1552}
1553
1554// This function checks for the parameters which can be offloaded.
1555// This can be enhanced depending on the capability of the DSP and policy
1556// of the system.
1557bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1558{
1559    ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1560     " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1561     offloadInfo.sample_rate, offloadInfo.channel_mask,
1562     offloadInfo.format,
1563     offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1564     offloadInfo.has_video);
1565
1566    // Check if offload has been disabled
1567    char propValue[PROPERTY_VALUE_MAX];
1568    if (property_get("audio.offload.disable", propValue, "0")) {
1569        if (atoi(propValue) != 0) {
1570            ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1571            return false;
1572        }
1573    }
1574
1575    // Check if stream type is music, then only allow offload as of now.
1576    if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1577    {
1578        ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1579        return false;
1580    }
1581
1582    //TODO: enable audio offloading with video when ready
1583    if (offloadInfo.has_video)
1584    {
1585        ALOGV("isOffloadSupported: has_video == true, returning false");
1586        return false;
1587    }
1588
1589    //If duration is less than minimum value defined in property, return false
1590    if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1591        if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1592            ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1593            return false;
1594        }
1595    } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1596        ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1597        return false;
1598    }
1599
1600    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1601    // creating an offloaded track and tearing it down immediately after start when audioflinger
1602    // detects there is an active non offloadable effect.
1603    // FIXME: We should check the audio session here but we do not have it in this context.
1604    // This may prevent offloading in rare situations where effects are left active by apps
1605    // in the background.
1606    if (isNonOffloadableEffectEnabled()) {
1607        return false;
1608    }
1609
1610    // See if there is a profile to support this.
1611    // AUDIO_DEVICE_NONE
1612    IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1613                                            offloadInfo.sample_rate,
1614                                            offloadInfo.format,
1615                                            offloadInfo.channel_mask,
1616                                            AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1617    ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1618    return (profile != NULL);
1619}
1620
1621// ----------------------------------------------------------------------------
1622// AudioPolicyManager
1623// ----------------------------------------------------------------------------
1624
1625uint32_t AudioPolicyManager::nextUniqueId()
1626{
1627    return android_atomic_inc(&mNextUniqueId);
1628}
1629
1630AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
1631    :
1632#ifdef AUDIO_POLICY_TEST
1633    Thread(false),
1634#endif //AUDIO_POLICY_TEST
1635    mPrimaryOutput((audio_io_handle_t)0),
1636    mPhoneState(AUDIO_MODE_NORMAL),
1637    mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1638    mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1639    mA2dpSuspended(false),
1640    mSpeakerDrcEnabled(false), mNextUniqueId(0)
1641{
1642    mpClientInterface = clientInterface;
1643
1644    for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
1645        mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
1646    }
1647
1648    mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
1649    if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1650        if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1651            ALOGE("could not load audio policy configuration file, setting defaults");
1652            defaultAudioPolicyConfig();
1653        }
1654    }
1655    // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
1656
1657    // must be done after reading the policy
1658    initializeVolumeCurves();
1659
1660    // open all output streams needed to access attached devices
1661    audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
1662    audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
1663    for (size_t i = 0; i < mHwModules.size(); i++) {
1664        mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1665        if (mHwModules[i]->mHandle == 0) {
1666            ALOGW("could not open HW module %s", mHwModules[i]->mName);
1667            continue;
1668        }
1669        // open all output streams needed to access attached devices
1670        // except for direct output streams that are only opened when they are actually
1671        // required by an app.
1672        // This also validates mAvailableOutputDevices list
1673        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1674        {
1675            const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1676
1677            if (outProfile->mSupportedDevices.isEmpty()) {
1678                ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
1679                continue;
1680            }
1681
1682            audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
1683            if ((profileTypes & outputDeviceTypes) &&
1684                    ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1685                AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1686
1687                outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mType & profileTypes);
1688                audio_io_handle_t output = mpClientInterface->openOutput(
1689                                                outProfile->mModule->mHandle,
1690                                                &outputDesc->mDevice,
1691                                                &outputDesc->mSamplingRate,
1692                                                &outputDesc->mFormat,
1693                                                &outputDesc->mChannelMask,
1694                                                &outputDesc->mLatency,
1695                                                outputDesc->mFlags);
1696                if (output == 0) {
1697                    ALOGW("Cannot open output stream for device %08x on hw module %s",
1698                          outputDesc->mDevice,
1699                          mHwModules[i]->mName);
1700                    delete outputDesc;
1701                } else {
1702                    for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
1703                        audio_devices_t type = outProfile->mSupportedDevices[k]->mType;
1704                        ssize_t index =
1705                                mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
1706                        // give a valid ID to an attached device once confirmed it is reachable
1707                        if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
1708                            mAvailableOutputDevices[index]->mId = nextUniqueId();
1709                        }
1710                    }
1711                    if (mPrimaryOutput == 0 &&
1712                            outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1713                        mPrimaryOutput = output;
1714                    }
1715                    addOutput(output, outputDesc);
1716                    setOutputDevice(output,
1717                                    outputDesc->mDevice,
1718                                    true);
1719                }
1720            }
1721        }
1722        // open input streams needed to access attached devices to validate
1723        // mAvailableInputDevices list
1724        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
1725        {
1726            const IOProfile *inProfile = mHwModules[i]->mInputProfiles[j];
1727
1728            if (inProfile->mSupportedDevices.isEmpty()) {
1729                ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
1730                continue;
1731            }
1732
1733            audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
1734            if (profileTypes & inputDeviceTypes) {
1735                AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
1736
1737                inputDesc->mInputSource = AUDIO_SOURCE_MIC;
1738                inputDesc->mDevice = inProfile->mSupportedDevices[0]->mType;
1739                audio_io_handle_t input = mpClientInterface->openInput(
1740                                                    inProfile->mModule->mHandle,
1741                                                    &inputDesc->mDevice,
1742                                                    &inputDesc->mSamplingRate,
1743                                                    &inputDesc->mFormat,
1744                                                    &inputDesc->mChannelMask);
1745
1746                if (input != 0) {
1747                    for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
1748                        audio_devices_t type = inProfile->mSupportedDevices[k]->mType;
1749                        ssize_t index =
1750                                mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
1751                        // give a valid ID to an attached device once confirmed it is reachable
1752                        if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
1753                            mAvailableInputDevices[index]->mId = nextUniqueId();
1754                        }
1755                    }
1756                    mpClientInterface->closeInput(input);
1757                } else {
1758                    ALOGW("Cannot open input stream for device %08x on hw module %s",
1759                          inputDesc->mDevice,
1760                          mHwModules[i]->mName);
1761                }
1762                delete inputDesc;
1763            }
1764        }
1765    }
1766    // make sure all attached devices have been allocated a unique ID
1767    for (size_t i = 0; i  < mAvailableOutputDevices.size();) {
1768        if (mAvailableOutputDevices[i]->mId == 0) {
1769            ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mType);
1770            mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
1771            continue;
1772        }
1773        i++;
1774    }
1775    for (size_t i = 0; i  < mAvailableInputDevices.size();) {
1776        if (mAvailableInputDevices[i]->mId == 0) {
1777            ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mType);
1778            mAvailableInputDevices.remove(mAvailableInputDevices[i]);
1779            continue;
1780        }
1781        i++;
1782    }
1783    // make sure default device is reachable
1784    if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
1785        ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mType);
1786    }
1787
1788    ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1789
1790    updateDevicesAndOutputs();
1791
1792#ifdef AUDIO_POLICY_TEST
1793    if (mPrimaryOutput != 0) {
1794        AudioParameter outputCmd = AudioParameter();
1795        outputCmd.addInt(String8("set_id"), 0);
1796        mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1797
1798        mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1799        mTestSamplingRate = 44100;
1800        mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
1801        mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
1802        mTestLatencyMs = 0;
1803        mCurOutput = 0;
1804        mDirectOutput = false;
1805        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1806            mTestOutputs[i] = 0;
1807        }
1808
1809        const size_t SIZE = 256;
1810        char buffer[SIZE];
1811        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1812        run(buffer, ANDROID_PRIORITY_AUDIO);
1813    }
1814#endif //AUDIO_POLICY_TEST
1815}
1816
1817AudioPolicyManager::~AudioPolicyManager()
1818{
1819#ifdef AUDIO_POLICY_TEST
1820    exit();
1821#endif //AUDIO_POLICY_TEST
1822   for (size_t i = 0; i < mOutputs.size(); i++) {
1823        mpClientInterface->closeOutput(mOutputs.keyAt(i));
1824        delete mOutputs.valueAt(i);
1825   }
1826   for (size_t i = 0; i < mInputs.size(); i++) {
1827        mpClientInterface->closeInput(mInputs.keyAt(i));
1828        delete mInputs.valueAt(i);
1829   }
1830   for (size_t i = 0; i < mHwModules.size(); i++) {
1831        delete mHwModules[i];
1832   }
1833   mAvailableOutputDevices.clear();
1834   mAvailableInputDevices.clear();
1835}
1836
1837status_t AudioPolicyManager::initCheck()
1838{
1839    return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1840}
1841
1842#ifdef AUDIO_POLICY_TEST
1843bool AudioPolicyManager::threadLoop()
1844{
1845    ALOGV("entering threadLoop()");
1846    while (!exitPending())
1847    {
1848        String8 command;
1849        int valueInt;
1850        String8 value;
1851
1852        Mutex::Autolock _l(mLock);
1853        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1854
1855        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1856        AudioParameter param = AudioParameter(command);
1857
1858        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1859            valueInt != 0) {
1860            ALOGV("Test command %s received", command.string());
1861            String8 target;
1862            if (param.get(String8("target"), target) != NO_ERROR) {
1863                target = "Manager";
1864            }
1865            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1866                param.remove(String8("test_cmd_policy_output"));
1867                mCurOutput = valueInt;
1868            }
1869            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1870                param.remove(String8("test_cmd_policy_direct"));
1871                if (value == "false") {
1872                    mDirectOutput = false;
1873                } else if (value == "true") {
1874                    mDirectOutput = true;
1875                }
1876            }
1877            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1878                param.remove(String8("test_cmd_policy_input"));
1879                mTestInput = valueInt;
1880            }
1881
1882            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1883                param.remove(String8("test_cmd_policy_format"));
1884                int format = AUDIO_FORMAT_INVALID;
1885                if (value == "PCM 16 bits") {
1886                    format = AUDIO_FORMAT_PCM_16_BIT;
1887                } else if (value == "PCM 8 bits") {
1888                    format = AUDIO_FORMAT_PCM_8_BIT;
1889                } else if (value == "Compressed MP3") {
1890                    format = AUDIO_FORMAT_MP3;
1891                }
1892                if (format != AUDIO_FORMAT_INVALID) {
1893                    if (target == "Manager") {
1894                        mTestFormat = format;
1895                    } else if (mTestOutputs[mCurOutput] != 0) {
1896                        AudioParameter outputParam = AudioParameter();
1897                        outputParam.addInt(String8("format"), format);
1898                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1899                    }
1900                }
1901            }
1902            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1903                param.remove(String8("test_cmd_policy_channels"));
1904                int channels = 0;
1905
1906                if (value == "Channels Stereo") {
1907                    channels =  AUDIO_CHANNEL_OUT_STEREO;
1908                } else if (value == "Channels Mono") {
1909                    channels =  AUDIO_CHANNEL_OUT_MONO;
1910                }
1911                if (channels != 0) {
1912                    if (target == "Manager") {
1913                        mTestChannels = channels;
1914                    } else if (mTestOutputs[mCurOutput] != 0) {
1915                        AudioParameter outputParam = AudioParameter();
1916                        outputParam.addInt(String8("channels"), channels);
1917                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1918                    }
1919                }
1920            }
1921            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1922                param.remove(String8("test_cmd_policy_sampleRate"));
1923                if (valueInt >= 0 && valueInt <= 96000) {
1924                    int samplingRate = valueInt;
1925                    if (target == "Manager") {
1926                        mTestSamplingRate = samplingRate;
1927                    } else if (mTestOutputs[mCurOutput] != 0) {
1928                        AudioParameter outputParam = AudioParameter();
1929                        outputParam.addInt(String8("sampling_rate"), samplingRate);
1930                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1931                    }
1932                }
1933            }
1934
1935            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1936                param.remove(String8("test_cmd_policy_reopen"));
1937
1938                AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1939                mpClientInterface->closeOutput(mPrimaryOutput);
1940
1941                audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1942
1943                delete mOutputs.valueFor(mPrimaryOutput);
1944                mOutputs.removeItem(mPrimaryOutput);
1945
1946                AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1947                outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1948                mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1949                                                &outputDesc->mDevice,
1950                                                &outputDesc->mSamplingRate,
1951                                                &outputDesc->mFormat,
1952                                                &outputDesc->mChannelMask,
1953                                                &outputDesc->mLatency,
1954                                                outputDesc->mFlags);
1955                if (mPrimaryOutput == 0) {
1956                    ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1957                            outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1958                } else {
1959                    AudioParameter outputCmd = AudioParameter();
1960                    outputCmd.addInt(String8("set_id"), 0);
1961                    mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1962                    addOutput(mPrimaryOutput, outputDesc);
1963                }
1964            }
1965
1966
1967            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1968        }
1969    }
1970    return false;
1971}
1972
1973void AudioPolicyManager::exit()
1974{
1975    {
1976        AutoMutex _l(mLock);
1977        requestExit();
1978        mWaitWorkCV.signal();
1979    }
1980    requestExitAndWait();
1981}
1982
1983int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
1984{
1985    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1986        if (output == mTestOutputs[i]) return i;
1987    }
1988    return 0;
1989}
1990#endif //AUDIO_POLICY_TEST
1991
1992// ---
1993
1994void AudioPolicyManager::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1995{
1996    outputDesc->mId = id;
1997    mOutputs.add(id, outputDesc);
1998}
1999
2000void AudioPolicyManager::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
2001{
2002    inputDesc->mId = id;
2003    mInputs.add(id, inputDesc);
2004}
2005
2006String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2007{
2008    if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2009        return String8("a2dp_sink_address=")+address;
2010    }
2011    return address;
2012}
2013
2014status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
2015                                                       audio_policy_dev_state_t state,
2016                                                       SortedVector<audio_io_handle_t>& outputs,
2017                                                       const String8 address)
2018{
2019    AudioOutputDescriptor *desc;
2020
2021    if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2022        // first list already open outputs that can be routed to this device
2023        for (size_t i = 0; i < mOutputs.size(); i++) {
2024            desc = mOutputs.valueAt(i);
2025            if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
2026                ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2027                outputs.add(mOutputs.keyAt(i));
2028            }
2029        }
2030        // then look for output profiles that can be routed to this device
2031        SortedVector<IOProfile *> profiles;
2032        for (size_t i = 0; i < mHwModules.size(); i++)
2033        {
2034            if (mHwModules[i]->mHandle == 0) {
2035                continue;
2036            }
2037            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2038            {
2039                if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2040                    ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
2041                    profiles.add(mHwModules[i]->mOutputProfiles[j]);
2042                }
2043            }
2044        }
2045
2046        if (profiles.isEmpty() && outputs.isEmpty()) {
2047            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2048            return BAD_VALUE;
2049        }
2050
2051        // open outputs for matching profiles if needed. Direct outputs are also opened to
2052        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2053        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2054            IOProfile *profile = profiles[profile_index];
2055
2056            // nothing to do if one output is already opened for this profile
2057            size_t j;
2058            for (j = 0; j < mOutputs.size(); j++) {
2059                desc = mOutputs.valueAt(j);
2060                if (!desc->isDuplicated() && desc->mProfile == profile) {
2061                    break;
2062                }
2063            }
2064            if (j != mOutputs.size()) {
2065                continue;
2066            }
2067
2068            ALOGV("opening output for device %08x with params %s", device, address.string());
2069            desc = new AudioOutputDescriptor(profile);
2070            desc->mDevice = device;
2071            audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2072            offloadInfo.sample_rate = desc->mSamplingRate;
2073            offloadInfo.format = desc->mFormat;
2074            offloadInfo.channel_mask = desc->mChannelMask;
2075
2076            audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2077                                                                       &desc->mDevice,
2078                                                                       &desc->mSamplingRate,
2079                                                                       &desc->mFormat,
2080                                                                       &desc->mChannelMask,
2081                                                                       &desc->mLatency,
2082                                                                       desc->mFlags,
2083                                                                       &offloadInfo);
2084            if (output != 0) {
2085                // Here is where the out_set_parameters() for card & device gets called
2086                if (!address.isEmpty()) {
2087                    mpClientInterface->setParameters(output, addressToParameter(device, address));
2088                }
2089
2090                // Here is where we step through and resolve any "dynamic" fields
2091                String8 reply;
2092                char *value;
2093                if (profile->mSamplingRates[0] == 0) {
2094                    reply = mpClientInterface->getParameters(output,
2095                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2096                    ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2097                              reply.string());
2098                    value = strpbrk((char *)reply.string(), "=");
2099                    if (value != NULL) {
2100                        loadSamplingRates(value + 1, profile);
2101                    }
2102                }
2103                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2104                    reply = mpClientInterface->getParameters(output,
2105                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2106                    ALOGV("checkOutputsForDevice() direct output sup formats %s",
2107                              reply.string());
2108                    value = strpbrk((char *)reply.string(), "=");
2109                    if (value != NULL) {
2110                        loadFormats(value + 1, profile);
2111                    }
2112                }
2113                if (profile->mChannelMasks[0] == 0) {
2114                    reply = mpClientInterface->getParameters(output,
2115                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2116                    ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2117                              reply.string());
2118                    value = strpbrk((char *)reply.string(), "=");
2119                    if (value != NULL) {
2120                        loadOutChannels(value + 1, profile);
2121                    }
2122                }
2123                if (((profile->mSamplingRates[0] == 0) &&
2124                         (profile->mSamplingRates.size() < 2)) ||
2125                     ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2126                         (profile->mFormats.size() < 2)) ||
2127                     ((profile->mChannelMasks[0] == 0) &&
2128                         (profile->mChannelMasks.size() < 2))) {
2129                    ALOGW("checkOutputsForDevice() direct output missing param");
2130                    mpClientInterface->closeOutput(output);
2131                    output = 0;
2132                } else if (profile->mSamplingRates[0] == 0) {
2133                    mpClientInterface->closeOutput(output);
2134                    desc->mSamplingRate = profile->mSamplingRates[1];
2135                    offloadInfo.sample_rate = desc->mSamplingRate;
2136                    output = mpClientInterface->openOutput(
2137                                                    profile->mModule->mHandle,
2138                                                    &desc->mDevice,
2139                                                    &desc->mSamplingRate,
2140                                                    &desc->mFormat,
2141                                                    &desc->mChannelMask,
2142                                                    &desc->mLatency,
2143                                                    desc->mFlags,
2144                                                    &offloadInfo);
2145                }
2146
2147                if (output != 0) {
2148                    addOutput(output, desc);
2149                    if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2150                        audio_io_handle_t duplicatedOutput = 0;
2151
2152                        // set initial stream volume for device
2153                        applyStreamVolumes(output, device, 0, true);
2154
2155                        //TODO: configure audio effect output stage here
2156
2157                        // open a duplicating output thread for the new output and the primary output
2158                        duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2159                                                                                  mPrimaryOutput);
2160                        if (duplicatedOutput != 0) {
2161                            // add duplicated output descriptor
2162                            AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2163                            dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2164                            dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2165                            dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2166                            dupOutputDesc->mFormat = desc->mFormat;
2167                            dupOutputDesc->mChannelMask = desc->mChannelMask;
2168                            dupOutputDesc->mLatency = desc->mLatency;
2169                            addOutput(duplicatedOutput, dupOutputDesc);
2170                            applyStreamVolumes(duplicatedOutput, device, 0, true);
2171                        } else {
2172                            ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2173                                    mPrimaryOutput, output);
2174                            mpClientInterface->closeOutput(output);
2175                            mOutputs.removeItem(output);
2176                            output = 0;
2177                        }
2178                    }
2179                }
2180            }
2181            if (output == 0) {
2182                ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2183                delete desc;
2184                profiles.removeAt(profile_index);
2185                profile_index--;
2186            } else {
2187                outputs.add(output);
2188                ALOGV("checkOutputsForDevice(): adding output %d", output);
2189            }
2190        }
2191
2192        if (profiles.isEmpty()) {
2193            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2194            return BAD_VALUE;
2195        }
2196    } else { // Disconnect
2197        // check if one opened output is not needed any more after disconnecting one device
2198        for (size_t i = 0; i < mOutputs.size(); i++) {
2199            desc = mOutputs.valueAt(i);
2200            if (!desc->isDuplicated() &&
2201                    !(desc->mProfile->mSupportedDevices.types() &
2202                            mAvailableOutputDevices.types())) {
2203                ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2204                outputs.add(mOutputs.keyAt(i));
2205            }
2206        }
2207        // Clear any profiles associated with the disconnected device.
2208        for (size_t i = 0; i < mHwModules.size(); i++)
2209        {
2210            if (mHwModules[i]->mHandle == 0) {
2211                continue;
2212            }
2213            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2214            {
2215                IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
2216                if (profile->mSupportedDevices.types() & device) {
2217                    ALOGV("checkOutputsForDevice(): "
2218                            "clearing direct output profile %zu on module %zu", j, i);
2219                    if (profile->mSamplingRates[0] == 0) {
2220                        profile->mSamplingRates.clear();
2221                        profile->mSamplingRates.add(0);
2222                    }
2223                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2224                        profile->mFormats.clear();
2225                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2226                    }
2227                    if (profile->mChannelMasks[0] == 0) {
2228                        profile->mChannelMasks.clear();
2229                        profile->mChannelMasks.add(0);
2230                    }
2231                }
2232            }
2233        }
2234    }
2235    return NO_ERROR;
2236}
2237
2238status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2239                                                      audio_policy_dev_state_t state,
2240                                                      SortedVector<audio_io_handle_t>& inputs,
2241                                                      const String8 address)
2242{
2243    AudioInputDescriptor *desc;
2244    if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2245        // first list already open inputs that can be routed to this device
2246        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2247            desc = mInputs.valueAt(input_index);
2248            if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2249                ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2250               inputs.add(mInputs.keyAt(input_index));
2251            }
2252        }
2253
2254        // then look for input profiles that can be routed to this device
2255        SortedVector<IOProfile *> profiles;
2256        for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2257        {
2258            if (mHwModules[module_idx]->mHandle == 0) {
2259                continue;
2260            }
2261            for (size_t profile_index = 0;
2262                 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2263                 profile_index++)
2264            {
2265                if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2266                        & (device & ~AUDIO_DEVICE_BIT_IN)) {
2267                    ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2268                          profile_index, module_idx);
2269                    profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2270                }
2271            }
2272        }
2273
2274        if (profiles.isEmpty() && inputs.isEmpty()) {
2275            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2276            return BAD_VALUE;
2277        }
2278
2279        // open inputs for matching profiles if needed. Direct inputs are also opened to
2280        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2281        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2282
2283            IOProfile *profile = profiles[profile_index];
2284            // nothing to do if one input is already opened for this profile
2285            size_t input_index;
2286            for (input_index = 0; input_index < mInputs.size(); input_index++) {
2287                desc = mInputs.valueAt(input_index);
2288                if (desc->mProfile == profile) {
2289                    break;
2290                }
2291            }
2292            if (input_index != mInputs.size()) {
2293                continue;
2294            }
2295
2296            ALOGV("opening input for device 0x%X with params %s", device, address.string());
2297            desc = new AudioInputDescriptor(profile);
2298            desc->mDevice = device;
2299
2300            audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2301                                            &desc->mDevice,
2302                                            &desc->mSamplingRate,
2303                                            &desc->mFormat,
2304                                            &desc->mChannelMask);
2305
2306            if (input != 0) {
2307                if (!address.isEmpty()) {
2308                    mpClientInterface->setParameters(input, addressToParameter(device, address));
2309                }
2310
2311                // Here is where we step through and resolve any "dynamic" fields
2312                String8 reply;
2313                char *value;
2314                if (profile->mSamplingRates[0] == 0) {
2315                    reply = mpClientInterface->getParameters(input,
2316                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2317                    ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2318                              reply.string());
2319                    value = strpbrk((char *)reply.string(), "=");
2320                    if (value != NULL) {
2321                        loadSamplingRates(value + 1, profile);
2322                    }
2323                }
2324                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2325                    reply = mpClientInterface->getParameters(input,
2326                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2327                    ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2328                    value = strpbrk((char *)reply.string(), "=");
2329                    if (value != NULL) {
2330                        loadFormats(value + 1, profile);
2331                    }
2332                }
2333                if (profile->mChannelMasks[0] == 0) {
2334                    reply = mpClientInterface->getParameters(input,
2335                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2336                    ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2337                              reply.string());
2338                    value = strpbrk((char *)reply.string(), "=");
2339                    if (value != NULL) {
2340                        loadInChannels(value + 1, profile);
2341                    }
2342                }
2343                if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2344                     ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2345                     ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2346                    ALOGW("checkInputsForDevice() direct input missing param");
2347                    mpClientInterface->closeInput(input);
2348                    input = 0;
2349                }
2350
2351                if (input != 0) {
2352                    addInput(input, desc);
2353                }
2354            } // endif input != 0
2355
2356            if (input == 0) {
2357                ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2358                delete desc;
2359                profiles.removeAt(profile_index);
2360                profile_index--;
2361            } else {
2362                inputs.add(input);
2363                ALOGV("checkInputsForDevice(): adding input %d", input);
2364            }
2365        } // end scan profiles
2366
2367        if (profiles.isEmpty()) {
2368            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2369            return BAD_VALUE;
2370        }
2371    } else {
2372        // Disconnect
2373        // check if one opened input is not needed any more after disconnecting one device
2374        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2375            desc = mInputs.valueAt(input_index);
2376            if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2377                ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2378                      mInputs.keyAt(input_index));
2379                inputs.add(mInputs.keyAt(input_index));
2380            }
2381        }
2382        // Clear any profiles associated with the disconnected device.
2383        for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2384            if (mHwModules[module_index]->mHandle == 0) {
2385                continue;
2386            }
2387            for (size_t profile_index = 0;
2388                 profile_index < mHwModules[module_index]->mInputProfiles.size();
2389                 profile_index++) {
2390                IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
2391                if (profile->mSupportedDevices.types() & device) {
2392                    ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2393                          profile_index, module_index);
2394                    if (profile->mSamplingRates[0] == 0) {
2395                        profile->mSamplingRates.clear();
2396                        profile->mSamplingRates.add(0);
2397                    }
2398                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2399                        profile->mFormats.clear();
2400                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2401                    }
2402                    if (profile->mChannelMasks[0] == 0) {
2403                        profile->mChannelMasks.clear();
2404                        profile->mChannelMasks.add(0);
2405                    }
2406                }
2407            }
2408        }
2409    } // end disconnect
2410
2411    return NO_ERROR;
2412}
2413
2414
2415void AudioPolicyManager::closeOutput(audio_io_handle_t output)
2416{
2417    ALOGV("closeOutput(%d)", output);
2418
2419    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2420    if (outputDesc == NULL) {
2421        ALOGW("closeOutput() unknown output %d", output);
2422        return;
2423    }
2424
2425    // look for duplicated outputs connected to the output being removed.
2426    for (size_t i = 0; i < mOutputs.size(); i++) {
2427        AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2428        if (dupOutputDesc->isDuplicated() &&
2429                (dupOutputDesc->mOutput1 == outputDesc ||
2430                dupOutputDesc->mOutput2 == outputDesc)) {
2431            AudioOutputDescriptor *outputDesc2;
2432            if (dupOutputDesc->mOutput1 == outputDesc) {
2433                outputDesc2 = dupOutputDesc->mOutput2;
2434            } else {
2435                outputDesc2 = dupOutputDesc->mOutput1;
2436            }
2437            // As all active tracks on duplicated output will be deleted,
2438            // and as they were also referenced on the other output, the reference
2439            // count for their stream type must be adjusted accordingly on
2440            // the other output.
2441            for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
2442                int refCount = dupOutputDesc->mRefCount[j];
2443                outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
2444            }
2445            audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2446            ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2447
2448            mpClientInterface->closeOutput(duplicatedOutput);
2449            delete mOutputs.valueFor(duplicatedOutput);
2450            mOutputs.removeItem(duplicatedOutput);
2451        }
2452    }
2453
2454    AudioParameter param;
2455    param.add(String8("closing"), String8("true"));
2456    mpClientInterface->setParameters(output, param.toString());
2457
2458    mpClientInterface->closeOutput(output);
2459    delete outputDesc;
2460    mOutputs.removeItem(output);
2461    mPreviousOutputs = mOutputs;
2462}
2463
2464SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
2465                        DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2466{
2467    SortedVector<audio_io_handle_t> outputs;
2468
2469    ALOGVV("getOutputsForDevice() device %04x", device);
2470    for (size_t i = 0; i < openOutputs.size(); i++) {
2471        ALOGVV("output %d isDuplicated=%d device=%04x",
2472                i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2473        if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2474            ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2475            outputs.add(openOutputs.keyAt(i));
2476        }
2477    }
2478    return outputs;
2479}
2480
2481bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
2482                                   SortedVector<audio_io_handle_t>& outputs2)
2483{
2484    if (outputs1.size() != outputs2.size()) {
2485        return false;
2486    }
2487    for (size_t i = 0; i < outputs1.size(); i++) {
2488        if (outputs1[i] != outputs2[i]) {
2489            return false;
2490        }
2491    }
2492    return true;
2493}
2494
2495void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
2496{
2497    audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2498    audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2499    SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2500    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2501
2502    if (!vectorsEqual(srcOutputs,dstOutputs)) {
2503        ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2504              strategy, srcOutputs[0], dstOutputs[0]);
2505        // mute strategy while moving tracks from one output to another
2506        for (size_t i = 0; i < srcOutputs.size(); i++) {
2507            AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2508            if (desc->isStrategyActive(strategy)) {
2509                setStrategyMute(strategy, true, srcOutputs[i]);
2510                setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2511            }
2512        }
2513
2514        // Move effects associated to this strategy from previous output to new output
2515        if (strategy == STRATEGY_MEDIA) {
2516            audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2517            SortedVector<audio_io_handle_t> moved;
2518            for (size_t i = 0; i < mEffects.size(); i++) {
2519                EffectDescriptor *desc = mEffects.valueAt(i);
2520                if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2521                        desc->mIo != fxOutput) {
2522                    if (moved.indexOf(desc->mIo) < 0) {
2523                        ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2524                              mEffects.keyAt(i), fxOutput);
2525                        mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2526                                                       fxOutput);
2527                        moved.add(desc->mIo);
2528                    }
2529                    desc->mIo = fxOutput;
2530                }
2531            }
2532        }
2533        // Move tracks associated to this strategy from previous output to new output
2534        for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2535            if (getStrategy((audio_stream_type_t)i) == strategy) {
2536                mpClientInterface->invalidateStream((audio_stream_type_t)i);
2537            }
2538        }
2539    }
2540}
2541
2542void AudioPolicyManager::checkOutputForAllStrategies()
2543{
2544    checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2545    checkOutputForStrategy(STRATEGY_PHONE);
2546    checkOutputForStrategy(STRATEGY_SONIFICATION);
2547    checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2548    checkOutputForStrategy(STRATEGY_MEDIA);
2549    checkOutputForStrategy(STRATEGY_DTMF);
2550}
2551
2552audio_io_handle_t AudioPolicyManager::getA2dpOutput()
2553{
2554    for (size_t i = 0; i < mOutputs.size(); i++) {
2555        AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2556        if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2557            return mOutputs.keyAt(i);
2558        }
2559    }
2560
2561    return 0;
2562}
2563
2564void AudioPolicyManager::checkA2dpSuspend()
2565{
2566    audio_io_handle_t a2dpOutput = getA2dpOutput();
2567    if (a2dpOutput == 0) {
2568        mA2dpSuspended = false;
2569        return;
2570    }
2571
2572    bool isScoConnected =
2573            (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
2574    // suspend A2DP output if:
2575    //      (NOT already suspended) &&
2576    //      ((SCO device is connected &&
2577    //       (forced usage for communication || for record is SCO))) ||
2578    //      (phone state is ringing || in call)
2579    //
2580    // restore A2DP output if:
2581    //      (Already suspended) &&
2582    //      ((SCO device is NOT connected ||
2583    //       (forced usage NOT for communication && NOT for record is SCO))) &&
2584    //      (phone state is NOT ringing && NOT in call)
2585    //
2586    if (mA2dpSuspended) {
2587        if ((!isScoConnected ||
2588             ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
2589              (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
2590             ((mPhoneState != AUDIO_MODE_IN_CALL) &&
2591              (mPhoneState != AUDIO_MODE_RINGTONE))) {
2592
2593            mpClientInterface->restoreOutput(a2dpOutput);
2594            mA2dpSuspended = false;
2595        }
2596    } else {
2597        if ((isScoConnected &&
2598             ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
2599              (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
2600             ((mPhoneState == AUDIO_MODE_IN_CALL) ||
2601              (mPhoneState == AUDIO_MODE_RINGTONE))) {
2602
2603            mpClientInterface->suspendOutput(a2dpOutput);
2604            mA2dpSuspended = true;
2605        }
2606    }
2607}
2608
2609audio_devices_t AudioPolicyManager::getNewDevice(audio_io_handle_t output, bool fromCache)
2610{
2611    audio_devices_t device = AUDIO_DEVICE_NONE;
2612
2613    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2614    // check the following by order of priority to request a routing change if necessary:
2615    // 1: the strategy enforced audible is active on the output:
2616    //      use device for strategy enforced audible
2617    // 2: we are in call or the strategy phone is active on the output:
2618    //      use device for strategy phone
2619    // 3: the strategy sonification is active on the output:
2620    //      use device for strategy sonification
2621    // 4: the strategy "respectful" sonification is active on the output:
2622    //      use device for strategy "respectful" sonification
2623    // 5: the strategy media is active on the output:
2624    //      use device for strategy media
2625    // 6: the strategy DTMF is active on the output:
2626    //      use device for strategy DTMF
2627    if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2628        device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2629    } else if (isInCall() ||
2630                    outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2631        device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2632    } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2633        device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2634    } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2635        device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2636    } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2637        device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2638    } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2639        device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2640    }
2641
2642    ALOGV("getNewDevice() selected device %x", device);
2643    return device;
2644}
2645
2646uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
2647    return (uint32_t)getStrategy(stream);
2648}
2649
2650audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
2651    audio_devices_t devices;
2652    // By checking the range of stream before calling getStrategy, we avoid
2653    // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
2654    // and then return STRATEGY_MEDIA, but we want to return the empty set.
2655    if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
2656        devices = AUDIO_DEVICE_NONE;
2657    } else {
2658        AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
2659        devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2660    }
2661    return devices;
2662}
2663
2664AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
2665        audio_stream_type_t stream) {
2666    // stream to strategy mapping
2667    switch (stream) {
2668    case AUDIO_STREAM_VOICE_CALL:
2669    case AUDIO_STREAM_BLUETOOTH_SCO:
2670        return STRATEGY_PHONE;
2671    case AUDIO_STREAM_RING:
2672    case AUDIO_STREAM_ALARM:
2673        return STRATEGY_SONIFICATION;
2674    case AUDIO_STREAM_NOTIFICATION:
2675        return STRATEGY_SONIFICATION_RESPECTFUL;
2676    case AUDIO_STREAM_DTMF:
2677        return STRATEGY_DTMF;
2678    default:
2679        ALOGE("unknown stream type");
2680    case AUDIO_STREAM_SYSTEM:
2681        // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2682        // while key clicks are played produces a poor result
2683    case AUDIO_STREAM_TTS:
2684    case AUDIO_STREAM_MUSIC:
2685        return STRATEGY_MEDIA;
2686    case AUDIO_STREAM_ENFORCED_AUDIBLE:
2687        return STRATEGY_ENFORCED_AUDIBLE;
2688    }
2689}
2690
2691void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
2692    switch(stream) {
2693    case AUDIO_STREAM_MUSIC:
2694        checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2695        updateDevicesAndOutputs();
2696        break;
2697    default:
2698        break;
2699    }
2700}
2701
2702audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
2703                                                             bool fromCache)
2704{
2705    uint32_t device = AUDIO_DEVICE_NONE;
2706
2707    if (fromCache) {
2708        ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2709              strategy, mDeviceForStrategy[strategy]);
2710        return mDeviceForStrategy[strategy];
2711    }
2712    audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
2713    switch (strategy) {
2714
2715    case STRATEGY_SONIFICATION_RESPECTFUL:
2716        if (isInCall()) {
2717            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2718        } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
2719                SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2720            // while media is playing on a remote device, use the the sonification behavior.
2721            // Note that we test this usecase before testing if media is playing because
2722            //   the isStreamActive() method only informs about the activity of a stream, not
2723            //   if it's for local playback. Note also that we use the same delay between both tests
2724            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2725        } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2726            // while media is playing (or has recently played), use the same device
2727            device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2728        } else {
2729            // when media is not playing anymore, fall back on the sonification behavior
2730            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2731        }
2732
2733        break;
2734
2735    case STRATEGY_DTMF:
2736        if (!isInCall()) {
2737            // when off call, DTMF strategy follows the same rules as MEDIA strategy
2738            device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2739            break;
2740        }
2741        // when in call, DTMF and PHONE strategies follow the same rules
2742        // FALL THROUGH
2743
2744    case STRATEGY_PHONE:
2745        // for phone strategy, we first consider the forced use and then the available devices by order
2746        // of priority
2747        switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
2748        case AUDIO_POLICY_FORCE_BT_SCO:
2749            if (!isInCall() || strategy != STRATEGY_DTMF) {
2750                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2751                if (device) break;
2752            }
2753            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2754            if (device) break;
2755            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
2756            if (device) break;
2757            // if SCO device is requested but no SCO device is available, fall back to default case
2758            // FALL THROUGH
2759
2760        default:    // FORCE_NONE
2761            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2762            if (!isInCall() &&
2763                    (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
2764                    (getA2dpOutput() != 0) && !mA2dpSuspended) {
2765                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2766                if (device) break;
2767                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2768                if (device) break;
2769            }
2770            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2771            if (device) break;
2772            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2773            if (device) break;
2774            if (mPhoneState != AUDIO_MODE_IN_CALL) {
2775                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2776                if (device) break;
2777                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
2778                if (device) break;
2779                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2780                if (device) break;
2781                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2782                if (device) break;
2783                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2784                if (device) break;
2785            }
2786            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
2787            if (device) break;
2788            device = mDefaultOutputDevice->mType;
2789            if (device == AUDIO_DEVICE_NONE) {
2790                ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2791            }
2792            break;
2793
2794        case AUDIO_POLICY_FORCE_SPEAKER:
2795            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2796            // A2DP speaker when forcing to speaker output
2797            if (!isInCall() &&
2798                    (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
2799                    (getA2dpOutput() != 0) && !mA2dpSuspended) {
2800                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2801                if (device) break;
2802            }
2803            if (mPhoneState != AUDIO_MODE_IN_CALL) {
2804                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2805                if (device) break;
2806                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
2807                if (device) break;
2808                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2809                if (device) break;
2810                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2811                if (device) break;
2812                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2813                if (device) break;
2814            }
2815            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
2816            if (device) break;
2817            device = mDefaultOutputDevice->mType;
2818            if (device == AUDIO_DEVICE_NONE) {
2819                ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2820            }
2821            break;
2822        }
2823    break;
2824
2825    case STRATEGY_SONIFICATION:
2826
2827        // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2828        // handleIncallSonification().
2829        if (isInCall()) {
2830            device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2831            break;
2832        }
2833        // FALL THROUGH
2834
2835    case STRATEGY_ENFORCED_AUDIBLE:
2836        // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2837        // except:
2838        //   - when in call where it doesn't default to STRATEGY_PHONE behavior
2839        //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
2840
2841        if ((strategy == STRATEGY_SONIFICATION) ||
2842                (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
2843            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
2844            if (device == AUDIO_DEVICE_NONE) {
2845                ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2846            }
2847        }
2848        // The second device used for sonification is the same as the device used by media strategy
2849        // FALL THROUGH
2850
2851    case STRATEGY_MEDIA: {
2852        uint32_t device2 = AUDIO_DEVICE_NONE;
2853        if (strategy != STRATEGY_SONIFICATION) {
2854            // no sonification on remote submix (e.g. WFD)
2855            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2856        }
2857        if ((device2 == AUDIO_DEVICE_NONE) &&
2858                (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
2859                (getA2dpOutput() != 0) && !mA2dpSuspended) {
2860            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
2861            if (device2 == AUDIO_DEVICE_NONE) {
2862                device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2863            }
2864            if (device2 == AUDIO_DEVICE_NONE) {
2865                device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2866            }
2867        }
2868        if (device2 == AUDIO_DEVICE_NONE) {
2869            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
2870        }
2871        if (device2 == AUDIO_DEVICE_NONE) {
2872            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
2873        }
2874        if (device2 == AUDIO_DEVICE_NONE) {
2875            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2876        }
2877        if (device2 == AUDIO_DEVICE_NONE) {
2878            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
2879        }
2880        if (device2 == AUDIO_DEVICE_NONE) {
2881            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
2882        }
2883        if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2884            // no sonification on aux digital (e.g. HDMI)
2885            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
2886        }
2887        if ((device2 == AUDIO_DEVICE_NONE) &&
2888                (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
2889            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
2890        }
2891        if (device2 == AUDIO_DEVICE_NONE) {
2892            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
2893        }
2894
2895        // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2896        // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2897        device |= device2;
2898        if (device) break;
2899        device = mDefaultOutputDevice->mType;
2900        if (device == AUDIO_DEVICE_NONE) {
2901            ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2902        }
2903        } break;
2904
2905    default:
2906        ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2907        break;
2908    }
2909
2910    ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2911    return device;
2912}
2913
2914void AudioPolicyManager::updateDevicesAndOutputs()
2915{
2916    for (int i = 0; i < NUM_STRATEGIES; i++) {
2917        mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2918    }
2919    mPreviousOutputs = mOutputs;
2920}
2921
2922uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2923                                                       audio_devices_t prevDevice,
2924                                                       uint32_t delayMs)
2925{
2926    // mute/unmute strategies using an incompatible device combination
2927    // if muting, wait for the audio in pcm buffer to be drained before proceeding
2928    // if unmuting, unmute only after the specified delay
2929    if (outputDesc->isDuplicated()) {
2930        return 0;
2931    }
2932
2933    uint32_t muteWaitMs = 0;
2934    audio_devices_t device = outputDesc->device();
2935    bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
2936
2937    for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2938        audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2939        bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2940        bool doMute = false;
2941
2942        if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2943            doMute = true;
2944            outputDesc->mStrategyMutedByDevice[i] = true;
2945        } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2946            doMute = true;
2947            outputDesc->mStrategyMutedByDevice[i] = false;
2948        }
2949        if (doMute) {
2950            for (size_t j = 0; j < mOutputs.size(); j++) {
2951                AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2952                // skip output if it does not share any device with current output
2953                if ((desc->supportedDevices() & outputDesc->supportedDevices())
2954                        == AUDIO_DEVICE_NONE) {
2955                    continue;
2956                }
2957                audio_io_handle_t curOutput = mOutputs.keyAt(j);
2958                ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2959                      mute ? "muting" : "unmuting", i, curDevice, curOutput);
2960                setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2961                if (desc->isStrategyActive((routing_strategy)i)) {
2962                    if (mute) {
2963                        // FIXME: should not need to double latency if volume could be applied
2964                        // immediately by the audioflinger mixer. We must account for the delay
2965                        // between now and the next time the audioflinger thread for this output
2966                        // will process a buffer (which corresponds to one buffer size,
2967                        // usually 1/2 or 1/4 of the latency).
2968                        if (muteWaitMs < desc->latency() * 2) {
2969                            muteWaitMs = desc->latency() * 2;
2970                        }
2971                    }
2972                }
2973            }
2974        }
2975    }
2976
2977    // temporary mute output if device selection changes to avoid volume bursts due to
2978    // different per device volumes
2979    if (outputDesc->isActive() && (device != prevDevice)) {
2980        if (muteWaitMs < outputDesc->latency() * 2) {
2981            muteWaitMs = outputDesc->latency() * 2;
2982        }
2983        for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2984            if (outputDesc->isStrategyActive((routing_strategy)i)) {
2985                setStrategyMute((routing_strategy)i, true, outputDesc->mId);
2986                // do tempMute unmute after twice the mute wait time
2987                setStrategyMute((routing_strategy)i, false, outputDesc->mId,
2988                                muteWaitMs *2, device);
2989            }
2990        }
2991    }
2992
2993    // wait for the PCM output buffers to empty before proceeding with the rest of the command
2994    if (muteWaitMs > delayMs) {
2995        muteWaitMs -= delayMs;
2996        usleep(muteWaitMs * 1000);
2997        return muteWaitMs;
2998    }
2999    return 0;
3000}
3001
3002uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
3003                                             audio_devices_t device,
3004                                             bool force,
3005                                             int delayMs)
3006{
3007    ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
3008    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3009    AudioParameter param;
3010    uint32_t muteWaitMs;
3011
3012    if (outputDesc->isDuplicated()) {
3013        muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
3014        muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
3015        return muteWaitMs;
3016    }
3017    // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3018    // output profile
3019    if ((device != AUDIO_DEVICE_NONE) &&
3020            ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
3021        return 0;
3022    }
3023
3024    // filter devices according to output selected
3025    device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
3026
3027    audio_devices_t prevDevice = outputDesc->mDevice;
3028
3029    ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3030
3031    if (device != AUDIO_DEVICE_NONE) {
3032        outputDesc->mDevice = device;
3033    }
3034    muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3035
3036    // Do not change the routing if:
3037    //  - the requested device is AUDIO_DEVICE_NONE
3038    //  - the requested device is the same as current device and force is not specified.
3039    // Doing this check here allows the caller to call setOutputDevice() without conditions
3040    if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3041        ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3042        return muteWaitMs;
3043    }
3044
3045    ALOGV("setOutputDevice() changing device");
3046    // do the routing
3047    param.addInt(String8(AudioParameter::keyRouting), (int)device);
3048    mpClientInterface->setParameters(output, param.toString(), delayMs);
3049
3050    // update stream volumes according to new device
3051    applyStreamVolumes(output, device, delayMs);
3052
3053    return muteWaitMs;
3054}
3055
3056AudioPolicyManager::IOProfile *AudioPolicyManager::getInputProfile(audio_devices_t device,
3057                                                   uint32_t samplingRate,
3058                                                   audio_format_t format,
3059                                                   audio_channel_mask_t channelMask)
3060{
3061    // Choose an input profile based on the requested capture parameters: select the first available
3062    // profile supporting all requested parameters.
3063
3064    for (size_t i = 0; i < mHwModules.size(); i++)
3065    {
3066        if (mHwModules[i]->mHandle == 0) {
3067            continue;
3068        }
3069        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3070        {
3071            IOProfile *profile = mHwModules[i]->mInputProfiles[j];
3072            // profile->log();
3073            if (profile->isCompatibleProfile(device, samplingRate, format,
3074                                             channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3075                return profile;
3076            }
3077        }
3078    }
3079    return NULL;
3080}
3081
3082audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
3083{
3084    uint32_t device = AUDIO_DEVICE_NONE;
3085    audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3086                                            ~AUDIO_DEVICE_BIT_IN;
3087    switch (inputSource) {
3088    case AUDIO_SOURCE_VOICE_UPLINK:
3089      if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
3090          device = AUDIO_DEVICE_IN_VOICE_CALL;
3091          break;
3092      }
3093      // FALL THROUGH
3094
3095    case AUDIO_SOURCE_DEFAULT:
3096    case AUDIO_SOURCE_MIC:
3097    if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3098        device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3099        break;
3100    }
3101    // FALL THROUGH
3102
3103    case AUDIO_SOURCE_VOICE_RECOGNITION:
3104    case AUDIO_SOURCE_HOTWORD:
3105    case AUDIO_SOURCE_VOICE_COMMUNICATION:
3106        if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
3107                availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
3108            device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
3109        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
3110            device = AUDIO_DEVICE_IN_WIRED_HEADSET;
3111        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3112            device = AUDIO_DEVICE_IN_USB_DEVICE;
3113        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
3114            device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3115        }
3116        break;
3117    case AUDIO_SOURCE_CAMCORDER:
3118        if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
3119            device = AUDIO_DEVICE_IN_BACK_MIC;
3120        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
3121            device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3122        }
3123        break;
3124    case AUDIO_SOURCE_VOICE_DOWNLINK:
3125    case AUDIO_SOURCE_VOICE_CALL:
3126        if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
3127            device = AUDIO_DEVICE_IN_VOICE_CALL;
3128        }
3129        break;
3130    case AUDIO_SOURCE_REMOTE_SUBMIX:
3131        if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
3132            device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3133        }
3134        break;
3135    default:
3136        ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3137        break;
3138    }
3139    ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3140    return device;
3141}
3142
3143bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
3144{
3145    if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3146        device &= ~AUDIO_DEVICE_BIT_IN;
3147        if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3148            return true;
3149    }
3150    return false;
3151}
3152
3153audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
3154{
3155    for (size_t i = 0; i < mInputs.size(); i++) {
3156        const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
3157        if ((input_descriptor->mRefCount > 0)
3158                && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3159            return mInputs.keyAt(i);
3160        }
3161    }
3162    return 0;
3163}
3164
3165
3166audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
3167{
3168    if (device == AUDIO_DEVICE_NONE) {
3169        // this happens when forcing a route update and no track is active on an output.
3170        // In this case the returned category is not important.
3171        device =  AUDIO_DEVICE_OUT_SPEAKER;
3172    } else if (popcount(device) > 1) {
3173        // Multiple device selection is either:
3174        //  - speaker + one other device: give priority to speaker in this case.
3175        //  - one A2DP device + another device: happens with duplicated output. In this case
3176        // retain the device on the A2DP output as the other must not correspond to an active
3177        // selection if not the speaker.
3178        if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3179            device = AUDIO_DEVICE_OUT_SPEAKER;
3180        } else {
3181            device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3182        }
3183    }
3184
3185    ALOGW_IF(popcount(device) != 1,
3186            "getDeviceForVolume() invalid device combination: %08x",
3187            device);
3188
3189    return device;
3190}
3191
3192AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
3193{
3194    switch(getDeviceForVolume(device)) {
3195        case AUDIO_DEVICE_OUT_EARPIECE:
3196            return DEVICE_CATEGORY_EARPIECE;
3197        case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3198        case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3199        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3200        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3201        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3202        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3203            return DEVICE_CATEGORY_HEADSET;
3204        case AUDIO_DEVICE_OUT_SPEAKER:
3205        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3206        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3207        case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3208        case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3209        case AUDIO_DEVICE_OUT_USB_DEVICE:
3210        case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3211        default:
3212            return DEVICE_CATEGORY_SPEAKER;
3213    }
3214}
3215
3216float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
3217        int indexInUi)
3218{
3219    device_category deviceCategory = getDeviceCategory(device);
3220    const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3221
3222    // the volume index in the UI is relative to the min and max volume indices for this stream type
3223    int nbSteps = 1 + curve[VOLMAX].mIndex -
3224            curve[VOLMIN].mIndex;
3225    int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3226            (streamDesc.mIndexMax - streamDesc.mIndexMin);
3227
3228    // find what part of the curve this index volume belongs to, or if it's out of bounds
3229    int segment = 0;
3230    if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
3231        return 0.0f;
3232    } else if (volIdx < curve[VOLKNEE1].mIndex) {
3233        segment = 0;
3234    } else if (volIdx < curve[VOLKNEE2].mIndex) {
3235        segment = 1;
3236    } else if (volIdx <= curve[VOLMAX].mIndex) {
3237        segment = 2;
3238    } else {                                                               // out of bounds
3239        return 1.0f;
3240    }
3241
3242    // linear interpolation in the attenuation table in dB
3243    float decibels = curve[segment].mDBAttenuation +
3244            ((float)(volIdx - curve[segment].mIndex)) *
3245                ( (curve[segment+1].mDBAttenuation -
3246                        curve[segment].mDBAttenuation) /
3247                    ((float)(curve[segment+1].mIndex -
3248                            curve[segment].mIndex)) );
3249
3250    float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3251
3252    ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3253            curve[segment].mIndex, volIdx,
3254            curve[segment+1].mIndex,
3255            curve[segment].mDBAttenuation,
3256            decibels,
3257            curve[segment+1].mDBAttenuation,
3258            amplification);
3259
3260    return amplification;
3261}
3262
3263const AudioPolicyManager::VolumeCurvePoint
3264    AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
3265    {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3266};
3267
3268const AudioPolicyManager::VolumeCurvePoint
3269    AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
3270    {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3271};
3272
3273const AudioPolicyManager::VolumeCurvePoint
3274    AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
3275    {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3276};
3277
3278const AudioPolicyManager::VolumeCurvePoint
3279    AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
3280    {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3281};
3282
3283const AudioPolicyManager::VolumeCurvePoint
3284    AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
3285    {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3286};
3287
3288// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3289// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3290// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3291// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3292
3293const AudioPolicyManager::VolumeCurvePoint
3294    AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
3295    {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3296};
3297
3298const AudioPolicyManager::VolumeCurvePoint
3299    AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
3300    {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3301};
3302
3303const AudioPolicyManager::VolumeCurvePoint
3304    AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
3305    {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3306};
3307
3308const AudioPolicyManager::VolumeCurvePoint
3309    AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
3310    {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3311};
3312
3313const AudioPolicyManager::VolumeCurvePoint
3314    AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
3315    {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3316};
3317
3318const AudioPolicyManager::VolumeCurvePoint
3319            *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
3320                                                   [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
3321    { // AUDIO_STREAM_VOICE_CALL
3322        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3323        sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3324        sDefaultVoiceVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3325    },
3326    { // AUDIO_STREAM_SYSTEM
3327        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3328        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3329        sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3330    },
3331    { // AUDIO_STREAM_RING
3332        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3333        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3334        sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3335    },
3336    { // AUDIO_STREAM_MUSIC
3337        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3338        sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3339        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3340    },
3341    { // AUDIO_STREAM_ALARM
3342        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3343        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3344        sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3345    },
3346    { // AUDIO_STREAM_NOTIFICATION
3347        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3348        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3349        sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3350    },
3351    { // AUDIO_STREAM_BLUETOOTH_SCO
3352        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3353        sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3354        sDefaultVoiceVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3355    },
3356    { // AUDIO_STREAM_ENFORCED_AUDIBLE
3357        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3358        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3359        sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3360    },
3361    {  // AUDIO_STREAM_DTMF
3362        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3363        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3364        sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3365    },
3366    { // AUDIO_STREAM_TTS
3367        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3368        sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3369        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
3370    },
3371};
3372
3373void AudioPolicyManager::initializeVolumeCurves()
3374{
3375    for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3376        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3377            mStreams[i].mVolumeCurve[j] =
3378                    sVolumeProfiles[i][j];
3379        }
3380    }
3381
3382    // Check availability of DRC on speaker path: if available, override some of the speaker curves
3383    if (mSpeakerDrcEnabled) {
3384        mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3385                sDefaultSystemVolumeCurveDrc;
3386        mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3387                sSpeakerSonificationVolumeCurveDrc;
3388        mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3389                sSpeakerSonificationVolumeCurveDrc;
3390        mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3391                sSpeakerSonificationVolumeCurveDrc;
3392    }
3393}
3394
3395float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
3396                                            int index,
3397                                            audio_io_handle_t output,
3398                                            audio_devices_t device)
3399{
3400    float volume = 1.0;
3401    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3402    StreamDescriptor &streamDesc = mStreams[stream];
3403
3404    if (device == AUDIO_DEVICE_NONE) {
3405        device = outputDesc->device();
3406    }
3407
3408    // if volume is not 0 (not muted), force media volume to max on digital output
3409    if (stream == AUDIO_STREAM_MUSIC &&
3410        index != mStreams[stream].mIndexMin &&
3411        (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3412         device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3413         device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3414         device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3415        return 1.0;
3416    }
3417
3418    volume = volIndexToAmpl(device, streamDesc, index);
3419
3420    // if a headset is connected, apply the following rules to ring tones and notifications
3421    // to avoid sound level bursts in user's ears:
3422    // - always attenuate ring tones and notifications volume by 6dB
3423    // - if music is playing, always limit the volume to current music volume,
3424    // with a minimum threshold at -36dB so that notification is always perceived.
3425    const routing_strategy stream_strategy = getStrategy(stream);
3426    if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3427            AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3428            AUDIO_DEVICE_OUT_WIRED_HEADSET |
3429            AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3430        ((stream_strategy == STRATEGY_SONIFICATION)
3431                || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
3432                || (stream == AUDIO_STREAM_SYSTEM)
3433                || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
3434                    (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
3435        streamDesc.mCanBeMuted) {
3436        volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3437        // when the phone is ringing we must consider that music could have been paused just before
3438        // by the music application and behave as if music was active if the last music track was
3439        // just stopped
3440        if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
3441                mLimitRingtoneVolume) {
3442            audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
3443            float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
3444                               mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
3445                               output,
3446                               musicDevice);
3447            float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3448                                musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3449            if (volume > minVol) {
3450                volume = minVol;
3451                ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3452            }
3453        }
3454    }
3455
3456    return volume;
3457}
3458
3459status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
3460                                                   int index,
3461                                                   audio_io_handle_t output,
3462                                                   audio_devices_t device,
3463                                                   int delayMs,
3464                                                   bool force)
3465{
3466
3467    // do not change actual stream volume if the stream is muted
3468    if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3469        ALOGVV("checkAndSetVolume() stream %d muted count %d",
3470              stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3471        return NO_ERROR;
3472    }
3473
3474    // do not change in call volume if bluetooth is connected and vice versa
3475    if ((stream == AUDIO_STREAM_VOICE_CALL &&
3476            mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3477        (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
3478                mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
3479        ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
3480             stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
3481        return INVALID_OPERATION;
3482    }
3483
3484    float volume = computeVolume(stream, index, output, device);
3485    // We actually change the volume if:
3486    // - the float value returned by computeVolume() changed
3487    // - the force flag is set
3488    if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3489            force) {
3490        mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3491        ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3492        // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3493        // enabled
3494        if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
3495            mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
3496        }
3497        mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
3498    }
3499
3500    if (stream == AUDIO_STREAM_VOICE_CALL ||
3501        stream == AUDIO_STREAM_BLUETOOTH_SCO) {
3502        float voiceVolume;
3503        // Force voice volume to max for bluetooth SCO as volume is managed by the headset
3504        if (stream == AUDIO_STREAM_VOICE_CALL) {
3505            voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3506        } else {
3507            voiceVolume = 1.0;
3508        }
3509
3510        if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3511            mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3512            mLastVoiceVolume = voiceVolume;
3513        }
3514    }
3515
3516    return NO_ERROR;
3517}
3518
3519void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
3520                                                audio_devices_t device,
3521                                                int delayMs,
3522                                                bool force)
3523{
3524    ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3525
3526    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
3527        checkAndSetVolume((audio_stream_type_t)stream,
3528                          mStreams[stream].getVolumeIndex(device),
3529                          output,
3530                          device,
3531                          delayMs,
3532                          force);
3533    }
3534}
3535
3536void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
3537                                             bool on,
3538                                             audio_io_handle_t output,
3539                                             int delayMs,
3540                                             audio_devices_t device)
3541{
3542    ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
3543    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
3544        if (getStrategy((audio_stream_type_t)stream) == strategy) {
3545            setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
3546        }
3547    }
3548}
3549
3550void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
3551                                           bool on,
3552                                           audio_io_handle_t output,
3553                                           int delayMs,
3554                                           audio_devices_t device)
3555{
3556    StreamDescriptor &streamDesc = mStreams[stream];
3557    AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3558    if (device == AUDIO_DEVICE_NONE) {
3559        device = outputDesc->device();
3560    }
3561
3562    ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3563          stream, on, output, outputDesc->mMuteCount[stream], device);
3564
3565    if (on) {
3566        if (outputDesc->mMuteCount[stream] == 0) {
3567            if (streamDesc.mCanBeMuted &&
3568                    ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
3569                     (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
3570                checkAndSetVolume(stream, 0, output, device, delayMs);
3571            }
3572        }
3573        // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3574        outputDesc->mMuteCount[stream]++;
3575    } else {
3576        if (outputDesc->mMuteCount[stream] == 0) {
3577            ALOGV("setStreamMute() unmuting non muted stream!");
3578            return;
3579        }
3580        if (--outputDesc->mMuteCount[stream] == 0) {
3581            checkAndSetVolume(stream,
3582                              streamDesc.getVolumeIndex(device),
3583                              output,
3584                              device,
3585                              delayMs);
3586        }
3587    }
3588}
3589
3590void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
3591                                                      bool starting, bool stateChange)
3592{
3593    // if the stream pertains to sonification strategy and we are in call we must
3594    // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3595    // in the device used for phone strategy and play the tone if the selected device does not
3596    // interfere with the device used for phone strategy
3597    // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3598    // many times as there are active tracks on the output
3599    const routing_strategy stream_strategy = getStrategy(stream);
3600    if ((stream_strategy == STRATEGY_SONIFICATION) ||
3601            ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3602        AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3603        ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3604                stream, starting, outputDesc->mDevice, stateChange);
3605        if (outputDesc->mRefCount[stream]) {
3606            int muteCount = 1;
3607            if (stateChange) {
3608                muteCount = outputDesc->mRefCount[stream];
3609            }
3610            if (audio_is_low_visibility(stream)) {
3611                ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3612                for (int i = 0; i < muteCount; i++) {
3613                    setStreamMute(stream, starting, mPrimaryOutput);
3614                }
3615            } else {
3616                ALOGV("handleIncallSonification() high visibility");
3617                if (outputDesc->device() &
3618                        getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3619                    ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3620                    for (int i = 0; i < muteCount; i++) {
3621                        setStreamMute(stream, starting, mPrimaryOutput);
3622                    }
3623                }
3624                if (starting) {
3625                    mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
3626                                                 AUDIO_STREAM_VOICE_CALL);
3627                } else {
3628                    mpClientInterface->stopTone();
3629                }
3630            }
3631        }
3632    }
3633}
3634
3635bool AudioPolicyManager::isInCall()
3636{
3637    return isStateInCall(mPhoneState);
3638}
3639
3640bool AudioPolicyManager::isStateInCall(int state) {
3641    return ((state == AUDIO_MODE_IN_CALL) ||
3642            (state == AUDIO_MODE_IN_COMMUNICATION));
3643}
3644
3645uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
3646{
3647    return MAX_EFFECTS_CPU_LOAD;
3648}
3649
3650uint32_t AudioPolicyManager::getMaxEffectsMemory()
3651{
3652    return MAX_EFFECTS_MEMORY;
3653}
3654
3655// --- AudioOutputDescriptor class implementation
3656
3657AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
3658        const IOProfile *profile)
3659    : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3660      mChannelMask(0), mLatency(0),
3661    mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3662    mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3663{
3664    // clear usage count for all stream types
3665    for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3666        mRefCount[i] = 0;
3667        mCurVolume[i] = -1.0;
3668        mMuteCount[i] = 0;
3669        mStopTime[i] = 0;
3670    }
3671    for (int i = 0; i < NUM_STRATEGIES; i++) {
3672        mStrategyMutedByDevice[i] = false;
3673    }
3674    if (profile != NULL) {
3675        mSamplingRate = profile->mSamplingRates[0];
3676        mFormat = profile->mFormats[0];
3677        mChannelMask = profile->mChannelMasks[0];
3678        mFlags = profile->mFlags;
3679    }
3680}
3681
3682audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
3683{
3684    if (isDuplicated()) {
3685        return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3686    } else {
3687        return mDevice;
3688    }
3689}
3690
3691uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
3692{
3693    if (isDuplicated()) {
3694        return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3695    } else {
3696        return mLatency;
3697    }
3698}
3699
3700bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
3701        const AudioOutputDescriptor *outputDesc)
3702{
3703    if (isDuplicated()) {
3704        return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3705    } else if (outputDesc->isDuplicated()){
3706        return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3707    } else {
3708        return (mProfile->mModule == outputDesc->mProfile->mModule);
3709    }
3710}
3711
3712void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
3713                                                                   int delta)
3714{
3715    // forward usage count change to attached outputs
3716    if (isDuplicated()) {
3717        mOutput1->changeRefCount(stream, delta);
3718        mOutput2->changeRefCount(stream, delta);
3719    }
3720    if ((delta + (int)mRefCount[stream]) < 0) {
3721        ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
3722              delta, stream, mRefCount[stream]);
3723        mRefCount[stream] = 0;
3724        return;
3725    }
3726    mRefCount[stream] += delta;
3727    ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3728}
3729
3730audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
3731{
3732    if (isDuplicated()) {
3733        return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3734    } else {
3735        return mProfile->mSupportedDevices.types() ;
3736    }
3737}
3738
3739bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
3740{
3741    return isStrategyActive(NUM_STRATEGIES, inPastMs);
3742}
3743
3744bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
3745                                                                       uint32_t inPastMs,
3746                                                                       nsecs_t sysTime) const
3747{
3748    if ((sysTime == 0) && (inPastMs != 0)) {
3749        sysTime = systemTime();
3750    }
3751    for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
3752        if (((getStrategy((audio_stream_type_t)i) == strategy) ||
3753                (NUM_STRATEGIES == strategy)) &&
3754                isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
3755            return true;
3756        }
3757    }
3758    return false;
3759}
3760
3761bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
3762                                                                       uint32_t inPastMs,
3763                                                                       nsecs_t sysTime) const
3764{
3765    if (mRefCount[stream] != 0) {
3766        return true;
3767    }
3768    if (inPastMs == 0) {
3769        return false;
3770    }
3771    if (sysTime == 0) {
3772        sysTime = systemTime();
3773    }
3774    if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3775        return true;
3776    }
3777    return false;
3778}
3779
3780
3781status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
3782{
3783    const size_t SIZE = 256;
3784    char buffer[SIZE];
3785    String8 result;
3786
3787    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3788    result.append(buffer);
3789    snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3790    result.append(buffer);
3791    snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3792    result.append(buffer);
3793    snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3794    result.append(buffer);
3795    snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3796    result.append(buffer);
3797    snprintf(buffer, SIZE, " Devices %08x\n", device());
3798    result.append(buffer);
3799    snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3800    result.append(buffer);
3801    for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
3802        snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n",
3803                 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
3804        result.append(buffer);
3805    }
3806    write(fd, result.string(), result.size());
3807
3808    return NO_ERROR;
3809}
3810
3811// --- AudioInputDescriptor class implementation
3812
3813AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3814    : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3815      mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
3816      mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
3817{
3818    if (profile != NULL) {
3819        mSamplingRate = profile->mSamplingRates[0];
3820        mFormat = profile->mFormats[0];
3821        mChannelMask = profile->mChannelMasks[0];
3822    }
3823}
3824
3825status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
3826{
3827    const size_t SIZE = 256;
3828    char buffer[SIZE];
3829    String8 result;
3830
3831    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3832    result.append(buffer);
3833    snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3834    result.append(buffer);
3835    snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3836    result.append(buffer);
3837    snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3838    result.append(buffer);
3839    snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3840    result.append(buffer);
3841    write(fd, result.string(), result.size());
3842
3843    return NO_ERROR;
3844}
3845
3846// --- StreamDescriptor class implementation
3847
3848AudioPolicyManager::StreamDescriptor::StreamDescriptor()
3849    :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3850{
3851    mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3852}
3853
3854int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3855{
3856    device = AudioPolicyManager::getDeviceForVolume(device);
3857    // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3858    if (mIndexCur.indexOfKey(device) < 0) {
3859        device = AUDIO_DEVICE_OUT_DEFAULT;
3860    }
3861    return mIndexCur.valueFor(device);
3862}
3863
3864void AudioPolicyManager::StreamDescriptor::dump(int fd)
3865{
3866    const size_t SIZE = 256;
3867    char buffer[SIZE];
3868    String8 result;
3869
3870    snprintf(buffer, SIZE, "%s         %02d         %02d         ",
3871             mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3872    result.append(buffer);
3873    for (size_t i = 0; i < mIndexCur.size(); i++) {
3874        snprintf(buffer, SIZE, "%04x : %02d, ",
3875                 mIndexCur.keyAt(i),
3876                 mIndexCur.valueAt(i));
3877        result.append(buffer);
3878    }
3879    result.append("\n");
3880
3881    write(fd, result.string(), result.size());
3882}
3883
3884// --- EffectDescriptor class implementation
3885
3886status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
3887{
3888    const size_t SIZE = 256;
3889    char buffer[SIZE];
3890    String8 result;
3891
3892    snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3893    result.append(buffer);
3894    snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3895    result.append(buffer);
3896    snprintf(buffer, SIZE, " Session: %d\n", mSession);
3897    result.append(buffer);
3898    snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
3899    result.append(buffer);
3900    snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
3901    result.append(buffer);
3902    write(fd, result.string(), result.size());
3903
3904    return NO_ERROR;
3905}
3906
3907// --- IOProfile class implementation
3908
3909AudioPolicyManager::HwModule::HwModule(const char *name)
3910    : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3911{
3912}
3913
3914AudioPolicyManager::HwModule::~HwModule()
3915{
3916    for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3917        mOutputProfiles[i]->mSupportedDevices.clear();
3918        delete mOutputProfiles[i];
3919    }
3920    for (size_t i = 0; i < mInputProfiles.size(); i++) {
3921        mInputProfiles[i]->mSupportedDevices.clear();
3922        delete mInputProfiles[i];
3923    }
3924    free((void *)mName);
3925}
3926
3927void AudioPolicyManager::HwModule::dump(int fd)
3928{
3929    const size_t SIZE = 256;
3930    char buffer[SIZE];
3931    String8 result;
3932
3933    snprintf(buffer, SIZE, "  - name: %s\n", mName);
3934    result.append(buffer);
3935    snprintf(buffer, SIZE, "  - handle: %d\n", mHandle);
3936    result.append(buffer);
3937    write(fd, result.string(), result.size());
3938    if (mOutputProfiles.size()) {
3939        write(fd, "  - outputs:\n", strlen("  - outputs:\n"));
3940        for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3941            snprintf(buffer, SIZE, "    output %zu:\n", i);
3942            write(fd, buffer, strlen(buffer));
3943            mOutputProfiles[i]->dump(fd);
3944        }
3945    }
3946    if (mInputProfiles.size()) {
3947        write(fd, "  - inputs:\n", strlen("  - inputs:\n"));
3948        for (size_t i = 0; i < mInputProfiles.size(); i++) {
3949            snprintf(buffer, SIZE, "    input %zu:\n", i);
3950            write(fd, buffer, strlen(buffer));
3951            mInputProfiles[i]->dump(fd);
3952        }
3953    }
3954}
3955
3956AudioPolicyManager::IOProfile::IOProfile(HwModule *module)
3957    : mFlags((audio_output_flags_t)0), mModule(module)
3958{
3959}
3960
3961AudioPolicyManager::IOProfile::~IOProfile()
3962{
3963}
3964
3965// checks if the IO profile is compatible with specified parameters.
3966// Sampling rate, format and channel mask must be specified in order to
3967// get a valid a match
3968bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
3969                                                            uint32_t samplingRate,
3970                                                            audio_format_t format,
3971                                                            audio_channel_mask_t channelMask,
3972                                                            audio_output_flags_t flags) const
3973{
3974    if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3975         return false;
3976     }
3977
3978     if ((mSupportedDevices.types() & device) != device) {
3979         return false;
3980     }
3981     if ((mFlags & flags) != flags) {
3982         return false;
3983     }
3984     size_t i;
3985     for (i = 0; i < mSamplingRates.size(); i++)
3986     {
3987         if (mSamplingRates[i] == samplingRate) {
3988             break;
3989         }
3990     }
3991     if (i == mSamplingRates.size()) {
3992         return false;
3993     }
3994     for (i = 0; i < mFormats.size(); i++)
3995     {
3996         if (mFormats[i] == format) {
3997             break;
3998         }
3999     }
4000     if (i == mFormats.size()) {
4001         return false;
4002     }
4003     for (i = 0; i < mChannelMasks.size(); i++)
4004     {
4005         if (mChannelMasks[i] == channelMask) {
4006             break;
4007         }
4008     }
4009     if (i == mChannelMasks.size()) {
4010         return false;
4011     }
4012     return true;
4013}
4014
4015void AudioPolicyManager::IOProfile::dump(int fd)
4016{
4017    const size_t SIZE = 256;
4018    char buffer[SIZE];
4019    String8 result;
4020
4021    snprintf(buffer, SIZE, "    - sampling rates: ");
4022    result.append(buffer);
4023    for (size_t i = 0; i < mSamplingRates.size(); i++) {
4024        snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
4025        result.append(buffer);
4026        result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
4027    }
4028
4029    snprintf(buffer, SIZE, "    - channel masks: ");
4030    result.append(buffer);
4031    for (size_t i = 0; i < mChannelMasks.size(); i++) {
4032        snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
4033        result.append(buffer);
4034        result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
4035    }
4036
4037    snprintf(buffer, SIZE, "    - formats: ");
4038    result.append(buffer);
4039    for (size_t i = 0; i < mFormats.size(); i++) {
4040        snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
4041        result.append(buffer);
4042        result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
4043    }
4044
4045    snprintf(buffer, SIZE, "    - devices:\n");
4046    result.append(buffer);
4047    write(fd, result.string(), result.size());
4048    DeviceDescriptor::dumpHeader(fd, 6);
4049    for (size_t i = 0; i < mSupportedDevices.size(); i++) {
4050        mSupportedDevices[i]->dump(fd, 6);
4051    }
4052
4053    snprintf(buffer, SIZE, "    - flags: 0x%04x\n", mFlags);
4054    result.append(buffer);
4055
4056    write(fd, result.string(), result.size());
4057}
4058
4059void AudioPolicyManager::IOProfile::log()
4060{
4061    const size_t SIZE = 256;
4062    char buffer[SIZE];
4063    String8 result;
4064
4065    ALOGV("    - sampling rates: ");
4066    for (size_t i = 0; i < mSamplingRates.size(); i++) {
4067        ALOGV("  %d", mSamplingRates[i]);
4068    }
4069
4070    ALOGV("    - channel masks: ");
4071    for (size_t i = 0; i < mChannelMasks.size(); i++) {
4072        ALOGV("  0x%04x", mChannelMasks[i]);
4073    }
4074
4075    ALOGV("    - formats: ");
4076    for (size_t i = 0; i < mFormats.size(); i++) {
4077        ALOGV("  0x%08x", mFormats[i]);
4078    }
4079
4080    ALOGV("    - devices: 0x%04x\n", mSupportedDevices.types());
4081    ALOGV("    - flags: 0x%04x\n", mFlags);
4082}
4083
4084
4085// --- DeviceDescriptor implementation
4086
4087bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
4088{
4089    // Devices are considered equal if they:
4090    // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
4091    // - have the same address or one device does not specify the address
4092    // - have the same channel mask or one device does not specify the channel mask
4093    return (mType == other->mType) &&
4094           (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
4095           (mChannelMask == 0 || other->mChannelMask == 0 ||
4096                mChannelMask == other->mChannelMask);
4097}
4098
4099void AudioPolicyManager::DeviceVector::refreshTypes()
4100{
4101    mTypes = AUDIO_DEVICE_NONE;
4102    for(size_t i = 0; i < size(); i++) {
4103        mTypes |= itemAt(i)->mType;
4104    }
4105    ALOGV("DeviceVector::refreshTypes() mTypes %08x", mTypes);
4106}
4107
4108ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
4109{
4110    for(size_t i = 0; i < size(); i++) {
4111        if (item->equals(itemAt(i))) {
4112            return i;
4113        }
4114    }
4115    return -1;
4116}
4117
4118ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
4119{
4120    ssize_t ret = indexOf(item);
4121
4122    if (ret < 0) {
4123        ret = SortedVector::add(item);
4124        if (ret >= 0) {
4125            refreshTypes();
4126        }
4127    } else {
4128        ALOGW("DeviceVector::add device %08x already in", item->mType);
4129        ret = -1;
4130    }
4131    return ret;
4132}
4133
4134ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
4135{
4136    size_t i;
4137    ssize_t ret = indexOf(item);
4138
4139    if (ret < 0) {
4140        ALOGW("DeviceVector::remove device %08x not in", item->mType);
4141    } else {
4142        ret = SortedVector::removeAt(ret);
4143        if (ret >= 0) {
4144            refreshTypes();
4145        }
4146    }
4147    return ret;
4148}
4149
4150void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
4151{
4152    DeviceVector deviceList;
4153
4154    uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
4155    types &= ~role_bit;
4156
4157    while (types) {
4158        uint32_t i = 31 - __builtin_clz(types);
4159        uint32_t type = 1 << i;
4160        types &= ~type;
4161        add(new DeviceDescriptor(type | role_bit));
4162    }
4163}
4164
4165void AudioPolicyManager::DeviceDescriptor::dumpHeader(int fd, int spaces)
4166{
4167    const size_t SIZE = 256;
4168    char buffer[SIZE];
4169
4170    snprintf(buffer, SIZE, "%*s%-48s %-2s %-8s %-32s \n",
4171                         spaces, "", "Type", "ID", "Cnl Mask", "Address");
4172    write(fd, buffer, strlen(buffer));
4173}
4174
4175status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces) const
4176{
4177    const size_t SIZE = 256;
4178    char buffer[SIZE];
4179
4180    snprintf(buffer, SIZE, "%*s%-48s %2d %08x %-32s \n",
4181                         spaces, "",
4182                         enumToString(sDeviceNameToEnumTable,
4183                                      ARRAY_SIZE(sDeviceNameToEnumTable),
4184                                      mType),
4185                         mId, mChannelMask, mAddress.string());
4186    write(fd, buffer, strlen(buffer));
4187
4188    return NO_ERROR;
4189}
4190
4191
4192// --- audio_policy.conf file parsing
4193
4194audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
4195{
4196    uint32_t flag = 0;
4197
4198    // it is OK to cast name to non const here as we are not going to use it after
4199    // strtok() modifies it
4200    char *flagName = strtok(name, "|");
4201    while (flagName != NULL) {
4202        if (strlen(flagName) != 0) {
4203            flag |= stringToEnum(sFlagNameToEnumTable,
4204                               ARRAY_SIZE(sFlagNameToEnumTable),
4205                               flagName);
4206        }
4207        flagName = strtok(NULL, "|");
4208    }
4209    //force direct flag if offload flag is set: offloading implies a direct output stream
4210    // and all common behaviors are driven by checking only the direct flag
4211    // this should normally be set appropriately in the policy configuration file
4212    if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
4213        flag |= AUDIO_OUTPUT_FLAG_DIRECT;
4214    }
4215
4216    return (audio_output_flags_t)flag;
4217}
4218
4219audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
4220{
4221    uint32_t device = 0;
4222
4223    char *devName = strtok(name, "|");
4224    while (devName != NULL) {
4225        if (strlen(devName) != 0) {
4226            device |= stringToEnum(sDeviceNameToEnumTable,
4227                                 ARRAY_SIZE(sDeviceNameToEnumTable),
4228                                 devName);
4229         }
4230        devName = strtok(NULL, "|");
4231     }
4232    return device;
4233}
4234
4235void AudioPolicyManager::loadSamplingRates(char *name, IOProfile *profile)
4236{
4237    char *str = strtok(name, "|");
4238
4239    // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4240    // rates should be read from the output stream after it is opened for the first time
4241    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4242        profile->mSamplingRates.add(0);
4243        return;
4244    }
4245
4246    while (str != NULL) {
4247        uint32_t rate = atoi(str);
4248        if (rate != 0) {
4249            ALOGV("loadSamplingRates() adding rate %d", rate);
4250            profile->mSamplingRates.add(rate);
4251        }
4252        str = strtok(NULL, "|");
4253    }
4254    return;
4255}
4256
4257void AudioPolicyManager::loadFormats(char *name, IOProfile *profile)
4258{
4259    char *str = strtok(name, "|");
4260
4261    // by convention, "0' in the first entry in mFormats indicates the supported formats
4262    // should be read from the output stream after it is opened for the first time
4263    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4264        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4265        return;
4266    }
4267
4268    while (str != NULL) {
4269        audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4270                                                             ARRAY_SIZE(sFormatNameToEnumTable),
4271                                                             str);
4272        if (format != AUDIO_FORMAT_DEFAULT) {
4273            profile->mFormats.add(format);
4274        }
4275        str = strtok(NULL, "|");
4276    }
4277    return;
4278}
4279
4280void AudioPolicyManager::loadInChannels(char *name, IOProfile *profile)
4281{
4282    const char *str = strtok(name, "|");
4283
4284    ALOGV("loadInChannels() %s", name);
4285
4286    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4287        profile->mChannelMasks.add(0);
4288        return;
4289    }
4290
4291    while (str != NULL) {
4292        audio_channel_mask_t channelMask =
4293                (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4294                                                   ARRAY_SIZE(sInChannelsNameToEnumTable),
4295                                                   str);
4296        if (channelMask != 0) {
4297            ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4298            profile->mChannelMasks.add(channelMask);
4299        }
4300        str = strtok(NULL, "|");
4301    }
4302    return;
4303}
4304
4305void AudioPolicyManager::loadOutChannels(char *name, IOProfile *profile)
4306{
4307    const char *str = strtok(name, "|");
4308
4309    ALOGV("loadOutChannels() %s", name);
4310
4311    // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4312    // masks should be read from the output stream after it is opened for the first time
4313    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4314        profile->mChannelMasks.add(0);
4315        return;
4316    }
4317
4318    while (str != NULL) {
4319        audio_channel_mask_t channelMask =
4320                (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4321                                                   ARRAY_SIZE(sOutChannelsNameToEnumTable),
4322                                                   str);
4323        if (channelMask != 0) {
4324            profile->mChannelMasks.add(channelMask);
4325        }
4326        str = strtok(NULL, "|");
4327    }
4328    return;
4329}
4330
4331status_t AudioPolicyManager::loadInput(cnode *root, HwModule *module)
4332{
4333    cnode *node = root->first_child;
4334
4335    IOProfile *profile = new IOProfile(module);
4336
4337    while (node) {
4338        if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4339            loadSamplingRates((char *)node->value, profile);
4340        } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4341            loadFormats((char *)node->value, profile);
4342        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4343            loadInChannels((char *)node->value, profile);
4344        } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4345            profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4346        }
4347        node = node->next;
4348    }
4349    ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4350            "loadInput() invalid supported devices");
4351    ALOGW_IF(profile->mChannelMasks.size() == 0,
4352            "loadInput() invalid supported channel masks");
4353    ALOGW_IF(profile->mSamplingRates.size() == 0,
4354            "loadInput() invalid supported sampling rates");
4355    ALOGW_IF(profile->mFormats.size() == 0,
4356            "loadInput() invalid supported formats");
4357    if (!profile->mSupportedDevices.isEmpty() &&
4358            (profile->mChannelMasks.size() != 0) &&
4359            (profile->mSamplingRates.size() != 0) &&
4360            (profile->mFormats.size() != 0)) {
4361
4362        ALOGV("loadInput() adding input Supported Devices %04x",
4363              profile->mSupportedDevices.types());
4364
4365        module->mInputProfiles.add(profile);
4366        return NO_ERROR;
4367    } else {
4368        delete profile;
4369        return BAD_VALUE;
4370    }
4371}
4372
4373status_t AudioPolicyManager::loadOutput(cnode *root, HwModule *module)
4374{
4375    cnode *node = root->first_child;
4376
4377    IOProfile *profile = new IOProfile(module);
4378
4379    while (node) {
4380        if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4381            loadSamplingRates((char *)node->value, profile);
4382        } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4383            loadFormats((char *)node->value, profile);
4384        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4385            loadOutChannels((char *)node->value, profile);
4386        } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4387            profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4388        } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4389            profile->mFlags = parseFlagNames((char *)node->value);
4390        }
4391        node = node->next;
4392    }
4393    ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4394            "loadOutput() invalid supported devices");
4395    ALOGW_IF(profile->mChannelMasks.size() == 0,
4396            "loadOutput() invalid supported channel masks");
4397    ALOGW_IF(profile->mSamplingRates.size() == 0,
4398            "loadOutput() invalid supported sampling rates");
4399    ALOGW_IF(profile->mFormats.size() == 0,
4400            "loadOutput() invalid supported formats");
4401    if (!profile->mSupportedDevices.isEmpty() &&
4402            (profile->mChannelMasks.size() != 0) &&
4403            (profile->mSamplingRates.size() != 0) &&
4404            (profile->mFormats.size() != 0)) {
4405
4406        ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4407              profile->mSupportedDevices.types(), profile->mFlags);
4408
4409        module->mOutputProfiles.add(profile);
4410        return NO_ERROR;
4411    } else {
4412        delete profile;
4413        return BAD_VALUE;
4414    }
4415}
4416
4417void AudioPolicyManager::loadHwModule(cnode *root)
4418{
4419    cnode *node = config_find(root, OUTPUTS_TAG);
4420    status_t status = NAME_NOT_FOUND;
4421
4422    HwModule *module = new HwModule(root->name);
4423
4424    if (node != NULL) {
4425        node = node->first_child;
4426        while (node) {
4427            ALOGV("loadHwModule() loading output %s", node->name);
4428            status_t tmpStatus = loadOutput(node, module);
4429            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4430                status = tmpStatus;
4431            }
4432            node = node->next;
4433        }
4434    }
4435    node = config_find(root, INPUTS_TAG);
4436    if (node != NULL) {
4437        node = node->first_child;
4438        while (node) {
4439            ALOGV("loadHwModule() loading input %s", node->name);
4440            status_t tmpStatus = loadInput(node, module);
4441            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4442                status = tmpStatus;
4443            }
4444            node = node->next;
4445        }
4446    }
4447    if (status == NO_ERROR) {
4448        mHwModules.add(module);
4449    } else {
4450        delete module;
4451    }
4452}
4453
4454void AudioPolicyManager::loadHwModules(cnode *root)
4455{
4456    cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4457    if (node == NULL) {
4458        return;
4459    }
4460
4461    node = node->first_child;
4462    while (node) {
4463        ALOGV("loadHwModules() loading module %s", node->name);
4464        loadHwModule(node);
4465        node = node->next;
4466    }
4467}
4468
4469void AudioPolicyManager::loadGlobalConfig(cnode *root)
4470{
4471    cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4472    if (node == NULL) {
4473        return;
4474    }
4475    node = node->first_child;
4476    while (node) {
4477        if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
4478            mAvailableOutputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4479            ALOGV("loadGlobalConfig() Attached Output Devices %08x",
4480                  mAvailableOutputDevices.types());
4481        } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
4482            audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
4483                                              ARRAY_SIZE(sDeviceNameToEnumTable),
4484                                              (char *)node->value);
4485            if (device != AUDIO_DEVICE_NONE) {
4486                mDefaultOutputDevice = new DeviceDescriptor(device);
4487            } else {
4488                ALOGW("loadGlobalConfig() default device not specified");
4489            }
4490            ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mType);
4491        } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
4492            mAvailableInputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4493            ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
4494        } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4495            mSpeakerDrcEnabled = stringToBool((char *)node->value);
4496            ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4497        }
4498        node = node->next;
4499    }
4500}
4501
4502status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
4503{
4504    cnode *root;
4505    char *data;
4506
4507    data = (char *)load_file(path, NULL);
4508    if (data == NULL) {
4509        return -ENODEV;
4510    }
4511    root = config_node("", "");
4512    config_load(root, data);
4513
4514    loadGlobalConfig(root);
4515    loadHwModules(root);
4516
4517    config_free(root);
4518    free(root);
4519    free(data);
4520
4521    ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4522
4523    return NO_ERROR;
4524}
4525
4526void AudioPolicyManager::defaultAudioPolicyConfig(void)
4527{
4528    HwModule *module;
4529    IOProfile *profile;
4530    sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
4531    mAvailableOutputDevices.add(mDefaultOutputDevice);
4532    mAvailableInputDevices.add(defaultInputDevice);
4533
4534    module = new HwModule("primary");
4535
4536    profile = new IOProfile(module);
4537    profile->mSamplingRates.add(44100);
4538    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4539    profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4540    profile->mSupportedDevices.add(mDefaultOutputDevice);
4541    profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4542    module->mOutputProfiles.add(profile);
4543
4544    profile = new IOProfile(module);
4545    profile->mSamplingRates.add(8000);
4546    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4547    profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4548    profile->mSupportedDevices.add(defaultInputDevice);
4549    module->mInputProfiles.add(profile);
4550
4551    mHwModules.add(module);
4552}
4553
4554}; // namespace android
4555