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