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