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