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