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