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