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