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