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