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