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