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