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