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