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