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