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