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