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 "APM::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#include <inttypes.h>
28#include <math.h>
29
30#include <AudioPolicyManagerInterface.h>
31#include <AudioPolicyEngineInstance.h>
32#include <cutils/properties.h>
33#include <utils/Log.h>
34#include <hardware/audio.h>
35#include <hardware/audio_effect.h>
36#include <media/AudioParameter.h>
37#include <media/AudioPolicyHelper.h>
38#include <soundtrigger/SoundTrigger.h>
39#include "AudioPolicyManager.h"
40#include "audio_policy_conf.h"
41#include <ConfigParsingUtils.h>
42#include <policy.h>
43
44namespace android {
45
46// ----------------------------------------------------------------------------
47// AudioPolicyInterface implementation
48// ----------------------------------------------------------------------------
49
50status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
51                                                      audio_policy_dev_state_t state,
52                                                      const char *device_address,
53                                                      const char *device_name)
54{
55    return setDeviceConnectionStateInt(device, state, device_address, device_name);
56}
57
58status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
59                                                         audio_policy_dev_state_t state,
60                                                         const char *device_address,
61                                                         const char *device_name)
62{
63    ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
64-            device, state, device_address, device_name);
65
66    // connect/disconnect only 1 device at a time
67    if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
68
69    sp<DeviceDescriptor> devDesc =
70            mHwModules.getDeviceDescriptor(device, device_address, device_name);
71
72    // handle output devices
73    if (audio_is_output_device(device)) {
74        SortedVector <audio_io_handle_t> outputs;
75
76        ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
77
78        // save a copy of the opened output descriptors before any output is opened or closed
79        // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
80        mPreviousOutputs = mOutputs;
81        switch (state)
82        {
83        // handle output device connection
84        case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
85            if (index >= 0) {
86                ALOGW("setDeviceConnectionState() device already connected: %x", device);
87                return INVALID_OPERATION;
88            }
89            ALOGV("setDeviceConnectionState() connecting device %x", device);
90
91            // register new device as available
92            index = mAvailableOutputDevices.add(devDesc);
93            if (index >= 0) {
94                sp<HwModule> module = mHwModules.getModuleForDevice(device);
95                if (module == 0) {
96                    ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
97                          device);
98                    mAvailableOutputDevices.remove(devDesc);
99                    return INVALID_OPERATION;
100                }
101                mAvailableOutputDevices[index]->attach(module);
102            } else {
103                return NO_MEMORY;
104            }
105
106            if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
107                mAvailableOutputDevices.remove(devDesc);
108                return INVALID_OPERATION;
109            }
110            // Propagate device availability to Engine
111            mEngine->setDeviceConnectionState(devDesc, state);
112
113            // outputs should never be empty here
114            ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
115                    "checkOutputsForDevice() returned no outputs but status OK");
116            ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
117                  outputs.size());
118
119            // Send connect to HALs
120            AudioParameter param = AudioParameter(devDesc->mAddress);
121            param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
122            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
123
124            } break;
125        // handle output device disconnection
126        case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
127            if (index < 0) {
128                ALOGW("setDeviceConnectionState() device not connected: %x", device);
129                return INVALID_OPERATION;
130            }
131
132            ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
133
134            // Send Disconnect to HALs
135            AudioParameter param = AudioParameter(devDesc->mAddress);
136            param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
137            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
138
139            // remove device from available output devices
140            mAvailableOutputDevices.remove(devDesc);
141
142            checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
143
144            // Propagate device availability to Engine
145            mEngine->setDeviceConnectionState(devDesc, state);
146            } break;
147
148        default:
149            ALOGE("setDeviceConnectionState() invalid state: %x", state);
150            return BAD_VALUE;
151        }
152
153        // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
154        // output is suspended before any tracks are moved to it
155        checkA2dpSuspend();
156        checkOutputForAllStrategies();
157        // outputs must be closed after checkOutputForAllStrategies() is executed
158        if (!outputs.isEmpty()) {
159            for (size_t i = 0; i < outputs.size(); i++) {
160                sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
161                // close unused outputs after device disconnection or direct outputs that have been
162                // opened by checkOutputsForDevice() to query dynamic parameters
163                if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
164                        (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
165                         (desc->mDirectOpenCount == 0))) {
166                    closeOutput(outputs[i]);
167                }
168            }
169            // check again after closing A2DP output to reset mA2dpSuspended if needed
170            checkA2dpSuspend();
171        }
172
173        updateDevicesAndOutputs();
174        if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
175            audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
176            updateCallRouting(newDevice);
177        }
178        for (size_t i = 0; i < mOutputs.size(); i++) {
179            sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
180            if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
181                audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
182                // do not force device change on duplicated output because if device is 0, it will
183                // also force a device 0 for the two outputs it is duplicated to which may override
184                // a valid device selection on those outputs.
185                bool force = !desc->isDuplicated()
186                        && (!device_distinguishes_on_address(device)
187                                // always force when disconnecting (a non-duplicated device)
188                                || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
189                setOutputDevice(desc, newDevice, force, 0);
190            }
191        }
192
193        mpClientInterface->onAudioPortListUpdate();
194        return NO_ERROR;
195    }  // end if is output device
196
197    // handle input devices
198    if (audio_is_input_device(device)) {
199        SortedVector <audio_io_handle_t> inputs;
200
201        ssize_t index = mAvailableInputDevices.indexOf(devDesc);
202        switch (state)
203        {
204        // handle input device connection
205        case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
206            if (index >= 0) {
207                ALOGW("setDeviceConnectionState() device already connected: %d", device);
208                return INVALID_OPERATION;
209            }
210            sp<HwModule> module = mHwModules.getModuleForDevice(device);
211            if (module == NULL) {
212                ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
213                      device);
214                return INVALID_OPERATION;
215            }
216            if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
217                return INVALID_OPERATION;
218            }
219
220            index = mAvailableInputDevices.add(devDesc);
221            if (index >= 0) {
222                mAvailableInputDevices[index]->attach(module);
223            } else {
224                return NO_MEMORY;
225            }
226
227            // Set connect to HALs
228            AudioParameter param = AudioParameter(devDesc->mAddress);
229            param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
230            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
231
232            // Propagate device availability to Engine
233            mEngine->setDeviceConnectionState(devDesc, state);
234        } break;
235
236        // handle input device disconnection
237        case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
238            if (index < 0) {
239                ALOGW("setDeviceConnectionState() device not connected: %d", device);
240                return INVALID_OPERATION;
241            }
242
243            ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
244
245            // Set Disconnect to HALs
246            AudioParameter param = AudioParameter(devDesc->mAddress);
247            param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
248            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
249
250            checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
251            mAvailableInputDevices.remove(devDesc);
252
253            // Propagate device availability to Engine
254            mEngine->setDeviceConnectionState(devDesc, state);
255        } break;
256
257        default:
258            ALOGE("setDeviceConnectionState() invalid state: %x", state);
259            return BAD_VALUE;
260        }
261
262        closeAllInputs();
263
264        if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
265            audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
266            updateCallRouting(newDevice);
267        }
268
269        mpClientInterface->onAudioPortListUpdate();
270        return NO_ERROR;
271    } // end if is input device
272
273    ALOGW("setDeviceConnectionState() invalid device: %x", device);
274    return BAD_VALUE;
275}
276
277audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
278                                                                      const char *device_address)
279{
280    sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, "");
281
282    DeviceVector *deviceVector;
283
284    if (audio_is_output_device(device)) {
285        deviceVector = &mAvailableOutputDevices;
286    } else if (audio_is_input_device(device)) {
287        deviceVector = &mAvailableInputDevices;
288    } else {
289        ALOGW("getDeviceConnectionState() invalid device type %08x", device);
290        return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
291    }
292    return deviceVector->getDeviceConnectionState(devDesc);
293}
294
295void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
296{
297    bool createTxPatch = false;
298    struct audio_patch patch;
299    patch.num_sources = 1;
300    patch.num_sinks = 1;
301    status_t status;
302    audio_patch_handle_t afPatchHandle;
303    DeviceVector deviceList;
304
305    if(!hasPrimaryOutput()) {
306        return;
307    }
308    audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
309    ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
310
311    // release existing RX patch if any
312    if (mCallRxPatch != 0) {
313        mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
314        mCallRxPatch.clear();
315    }
316    // release TX patch if any
317    if (mCallTxPatch != 0) {
318        mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
319        mCallTxPatch.clear();
320    }
321
322    // If the RX device is on the primary HW module, then use legacy routing method for voice calls
323    // via setOutputDevice() on primary output.
324    // Otherwise, create two audio patches for TX and RX path.
325    if (availablePrimaryOutputDevices() & rxDevice) {
326        setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
327        // If the TX device is also on the primary HW module, setOutputDevice() will take care
328        // of it due to legacy implementation. If not, create a patch.
329        if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
330                == AUDIO_DEVICE_NONE) {
331            createTxPatch = true;
332        }
333    } else {
334        // create RX path audio patch
335        deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
336        ALOG_ASSERT(!deviceList.isEmpty(),
337                    "updateCallRouting() selected device not in output device list");
338        sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
339        deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
340        ALOG_ASSERT(!deviceList.isEmpty(),
341                    "updateCallRouting() no telephony RX device");
342        sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
343
344        rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
345        rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
346
347        // request to reuse existing output stream if one is already opened to reach the RX device
348        SortedVector<audio_io_handle_t> outputs =
349                                getOutputsForDevice(rxDevice, mOutputs);
350        audio_io_handle_t output = selectOutput(outputs,
351                                                AUDIO_OUTPUT_FLAG_NONE,
352                                                AUDIO_FORMAT_INVALID);
353        if (output != AUDIO_IO_HANDLE_NONE) {
354            sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
355            ALOG_ASSERT(!outputDesc->isDuplicated(),
356                        "updateCallRouting() RX device output is duplicated");
357            outputDesc->toAudioPortConfig(&patch.sources[1]);
358            patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
359            patch.num_sources = 2;
360        }
361
362        afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
363        status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
364        ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
365                                               status);
366        if (status == NO_ERROR) {
367            mCallRxPatch = new AudioPatch(&patch, mUidCached);
368            mCallRxPatch->mAfPatchHandle = afPatchHandle;
369            mCallRxPatch->mUid = mUidCached;
370        }
371        createTxPatch = true;
372    }
373    if (createTxPatch) {
374
375        struct audio_patch patch;
376        patch.num_sources = 1;
377        patch.num_sinks = 1;
378        deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
379        ALOG_ASSERT(!deviceList.isEmpty(),
380                    "updateCallRouting() selected device not in input device list");
381        sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
382        txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
383        deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
384        ALOG_ASSERT(!deviceList.isEmpty(),
385                    "updateCallRouting() no telephony TX device");
386        sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
387        txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
388
389        SortedVector<audio_io_handle_t> outputs =
390                                getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
391        audio_io_handle_t output = selectOutput(outputs,
392                                                AUDIO_OUTPUT_FLAG_NONE,
393                                                AUDIO_FORMAT_INVALID);
394        // request to reuse existing output stream if one is already opened to reach the TX
395        // path output device
396        if (output != AUDIO_IO_HANDLE_NONE) {
397            sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
398            ALOG_ASSERT(!outputDesc->isDuplicated(),
399                        "updateCallRouting() RX device output is duplicated");
400            outputDesc->toAudioPortConfig(&patch.sources[1]);
401            patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
402            patch.num_sources = 2;
403        }
404
405        // terminate active capture if on the same HW module as the call TX source device
406        // FIXME: would be better to refine to only inputs whose profile connects to the
407        // call TX device but this information is not in the audio patch and logic here must be
408        // symmetric to the one in startInput()
409        audio_io_handle_t activeInput = mInputs.getActiveInput();
410        if (activeInput != 0) {
411            sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
412            if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
413                audio_session_t activeSession = activeDesc->mSessions.itemAt(0);
414                stopInput(activeInput, activeSession);
415                releaseInput(activeInput, activeSession);
416            }
417        }
418
419        afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
420        status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
421        ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
422                                               status);
423        if (status == NO_ERROR) {
424            mCallTxPatch = new AudioPatch(&patch, mUidCached);
425            mCallTxPatch->mAfPatchHandle = afPatchHandle;
426            mCallTxPatch->mUid = mUidCached;
427        }
428    }
429}
430
431void AudioPolicyManager::setPhoneState(audio_mode_t state)
432{
433    ALOGV("setPhoneState() state %d", state);
434    // store previous phone state for management of sonification strategy below
435    int oldState = mEngine->getPhoneState();
436
437    if (mEngine->setPhoneState(state) != NO_ERROR) {
438        ALOGW("setPhoneState() invalid or same state %d", state);
439        return;
440    }
441    /// Opens: can these line be executed after the switch of volume curves???
442    // if leaving call state, handle special case of active streams
443    // pertaining to sonification strategy see handleIncallSonification()
444    if (isStateInCall(oldState)) {
445        ALOGV("setPhoneState() in call state management: new state is %d", state);
446        for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
447            if (stream == AUDIO_STREAM_PATCH) {
448                continue;
449            }
450            handleIncallSonification((audio_stream_type_t)stream, false, true);
451        }
452
453        // force reevaluating accessibility routing when call stops
454        mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
455    }
456
457    /**
458     * Switching to or from incall state or switching between telephony and VoIP lead to force
459     * routing command.
460     */
461    bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
462                  || (is_state_in_call(state) && (state != oldState)));
463
464    // check for device and output changes triggered by new phone state
465    checkA2dpSuspend();
466    checkOutputForAllStrategies();
467    updateDevicesAndOutputs();
468
469    int delayMs = 0;
470    if (isStateInCall(state)) {
471        nsecs_t sysTime = systemTime();
472        for (size_t i = 0; i < mOutputs.size(); i++) {
473            sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
474            // mute media and sonification strategies and delay device switch by the largest
475            // latency of any output where either strategy is active.
476            // This avoid sending the ring tone or music tail into the earpiece or headset.
477            if ((isStrategyActive(desc, STRATEGY_MEDIA,
478                                  SONIFICATION_HEADSET_MUSIC_DELAY,
479                                  sysTime) ||
480                 isStrategyActive(desc, STRATEGY_SONIFICATION,
481                                  SONIFICATION_HEADSET_MUSIC_DELAY,
482                                  sysTime)) &&
483                    (delayMs < (int)desc->latency()*2)) {
484                delayMs = desc->latency()*2;
485            }
486            setStrategyMute(STRATEGY_MEDIA, true, desc);
487            setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
488                getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
489            setStrategyMute(STRATEGY_SONIFICATION, true, desc);
490            setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
491                getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
492        }
493    }
494
495    if (hasPrimaryOutput()) {
496        // Note that despite the fact that getNewOutputDevice() is called on the primary output,
497        // the device returned is not necessarily reachable via this output
498        audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
499        // force routing command to audio hardware when ending call
500        // even if no device change is needed
501        if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
502            rxDevice = mPrimaryOutput->device();
503        }
504
505        if (state == AUDIO_MODE_IN_CALL) {
506            updateCallRouting(rxDevice, delayMs);
507        } else if (oldState == AUDIO_MODE_IN_CALL) {
508            if (mCallRxPatch != 0) {
509                mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
510                mCallRxPatch.clear();
511            }
512            if (mCallTxPatch != 0) {
513                mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
514                mCallTxPatch.clear();
515            }
516            setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
517        } else {
518            setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
519        }
520    }
521    // if entering in call state, handle special case of active streams
522    // pertaining to sonification strategy see handleIncallSonification()
523    if (isStateInCall(state)) {
524        ALOGV("setPhoneState() in call state management: new state is %d", state);
525        for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
526            if (stream == AUDIO_STREAM_PATCH) {
527                continue;
528            }
529            handleIncallSonification((audio_stream_type_t)stream, true, true);
530        }
531
532        // force reevaluating accessibility routing when call starts
533        mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
534    }
535
536    // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
537    if (state == AUDIO_MODE_RINGTONE &&
538        isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
539        mLimitRingtoneVolume = true;
540    } else {
541        mLimitRingtoneVolume = false;
542    }
543}
544
545audio_mode_t AudioPolicyManager::getPhoneState() {
546    return mEngine->getPhoneState();
547}
548
549void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
550                                         audio_policy_forced_cfg_t config)
551{
552    ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
553
554    if (mEngine->setForceUse(usage, config) != NO_ERROR) {
555        ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
556        return;
557    }
558    bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
559            (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
560            (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
561
562    // check for device and output changes triggered by new force usage
563    checkA2dpSuspend();
564    checkOutputForAllStrategies();
565    updateDevicesAndOutputs();
566    if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
567        audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
568        updateCallRouting(newDevice);
569    }
570    for (size_t i = 0; i < mOutputs.size(); i++) {
571        sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
572        audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
573        if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
574            setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
575        }
576        if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
577            applyStreamVolumes(outputDesc, newDevice, 0, true);
578        }
579    }
580
581    audio_io_handle_t activeInput = mInputs.getActiveInput();
582    if (activeInput != 0) {
583        sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
584        audio_devices_t newDevice = getNewInputDevice(activeInput);
585        // Force new input selection if the new device can not be reached via current input
586        if (activeDesc->mProfile->mSupportedDevices.types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
587            setInputDevice(activeInput, newDevice);
588        } else {
589            closeInput(activeInput);
590        }
591    }
592}
593
594void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
595{
596    ALOGV("setSystemProperty() property %s, value %s", property, value);
597}
598
599// Find a direct output profile compatible with the parameters passed, even if the input flags do
600// not explicitly request a direct output
601sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
602                                                               audio_devices_t device,
603                                                               uint32_t samplingRate,
604                                                               audio_format_t format,
605                                                               audio_channel_mask_t channelMask,
606                                                               audio_output_flags_t flags)
607{
608    // only retain flags that will drive the direct output profile selection
609    // if explicitly requested
610    static const uint32_t kRelevantFlags =
611            (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
612    flags =
613        (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
614
615    sp<IOProfile> profile;
616
617    for (size_t i = 0; i < mHwModules.size(); i++) {
618        if (mHwModules[i]->mHandle == 0) {
619            continue;
620        }
621        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
622            sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
623            if (!curProfile->isCompatibleProfile(device, String8(""),
624                    samplingRate, NULL /*updatedSamplingRate*/,
625                    format, NULL /*updatedFormat*/,
626                    channelMask, NULL /*updatedChannelMask*/,
627                    flags)) {
628                continue;
629            }
630            // reject profiles not corresponding to a device currently available
631            if ((mAvailableOutputDevices.types() & curProfile->mSupportedDevices.types()) == 0) {
632                continue;
633            }
634            // if several profiles are compatible, give priority to one with offload capability
635            if (profile != 0 && ((curProfile->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
636                continue;
637            }
638            profile = curProfile;
639            if ((profile->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
640                break;
641            }
642        }
643    }
644    return profile;
645}
646
647audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
648                                                uint32_t samplingRate,
649                                                audio_format_t format,
650                                                audio_channel_mask_t channelMask,
651                                                audio_output_flags_t flags,
652                                                const audio_offload_info_t *offloadInfo)
653{
654    routing_strategy strategy = getStrategy(stream);
655    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
656    ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
657          device, stream, samplingRate, format, channelMask, flags);
658
659    return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
660                              stream, samplingRate,format, channelMask,
661                              flags, offloadInfo);
662}
663
664status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
665                                              audio_io_handle_t *output,
666                                              audio_session_t session,
667                                              audio_stream_type_t *stream,
668                                              uid_t uid,
669                                              uint32_t samplingRate,
670                                              audio_format_t format,
671                                              audio_channel_mask_t channelMask,
672                                              audio_output_flags_t flags,
673                                              audio_port_handle_t selectedDeviceId,
674                                              const audio_offload_info_t *offloadInfo)
675{
676    audio_attributes_t attributes;
677    if (attr != NULL) {
678        if (!isValidAttributes(attr)) {
679            ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
680                  attr->usage, attr->content_type, attr->flags,
681                  attr->tags);
682            return BAD_VALUE;
683        }
684        attributes = *attr;
685    } else {
686        if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
687            ALOGE("getOutputForAttr():  invalid stream type");
688            return BAD_VALUE;
689        }
690        stream_type_to_audio_attributes(*stream, &attributes);
691    }
692    sp<SwAudioOutputDescriptor> desc;
693    if (mPolicyMixes.getOutputForAttr(attributes, desc) == NO_ERROR) {
694        ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
695        if (!audio_is_linear_pcm(format)) {
696            return BAD_VALUE;
697        }
698        *stream = streamTypefromAttributesInt(&attributes);
699        *output = desc->mIoHandle;
700        ALOGV("getOutputForAttr() returns output %d", *output);
701        return NO_ERROR;
702    }
703    if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
704        ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
705        return BAD_VALUE;
706    }
707
708    ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
709            " session %d selectedDeviceId %d",
710            attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
711            session, selectedDeviceId);
712
713    *stream = streamTypefromAttributesInt(&attributes);
714
715    // Explicit routing?
716    sp<DeviceDescriptor> deviceDesc;
717    for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
718        if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
719            deviceDesc = mAvailableOutputDevices[i];
720            break;
721        }
722    }
723    mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
724
725    routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
726    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
727
728    if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
729        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
730    }
731
732    ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
733          device, samplingRate, format, channelMask, flags);
734
735    *output = getOutputForDevice(device, session, *stream,
736                                 samplingRate, format, channelMask,
737                                 flags, offloadInfo);
738    if (*output == AUDIO_IO_HANDLE_NONE) {
739        mOutputRoutes.removeRoute(session);
740        return INVALID_OPERATION;
741    }
742
743    return NO_ERROR;
744}
745
746audio_io_handle_t AudioPolicyManager::getOutputForDevice(
747        audio_devices_t device,
748        audio_session_t session __unused,
749        audio_stream_type_t stream,
750        uint32_t samplingRate,
751        audio_format_t format,
752        audio_channel_mask_t channelMask,
753        audio_output_flags_t flags,
754        const audio_offload_info_t *offloadInfo)
755{
756    audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
757    uint32_t latency = 0;
758    status_t status;
759
760#ifdef AUDIO_POLICY_TEST
761    if (mCurOutput != 0) {
762        ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
763                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
764
765        if (mTestOutputs[mCurOutput] == 0) {
766            ALOGV("getOutput() opening test output");
767            sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
768                                                                               mpClientInterface);
769            outputDesc->mDevice = mTestDevice;
770            outputDesc->mLatency = mTestLatencyMs;
771            outputDesc->mFlags =
772                    (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
773            outputDesc->mRefCount[stream] = 0;
774            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
775            config.sample_rate = mTestSamplingRate;
776            config.channel_mask = mTestChannels;
777            config.format = mTestFormat;
778            if (offloadInfo != NULL) {
779                config.offload_info = *offloadInfo;
780            }
781            status = mpClientInterface->openOutput(0,
782                                                  &mTestOutputs[mCurOutput],
783                                                  &config,
784                                                  &outputDesc->mDevice,
785                                                  String8(""),
786                                                  &outputDesc->mLatency,
787                                                  outputDesc->mFlags);
788            if (status == NO_ERROR) {
789                outputDesc->mSamplingRate = config.sample_rate;
790                outputDesc->mFormat = config.format;
791                outputDesc->mChannelMask = config.channel_mask;
792                AudioParameter outputCmd = AudioParameter();
793                outputCmd.addInt(String8("set_id"),mCurOutput);
794                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
795                addOutput(mTestOutputs[mCurOutput], outputDesc);
796            }
797        }
798        return mTestOutputs[mCurOutput];
799    }
800#endif //AUDIO_POLICY_TEST
801
802    // open a direct output if required by specified parameters
803    //force direct flag if offload flag is set: offloading implies a direct output stream
804    // and all common behaviors are driven by checking only the direct flag
805    // this should normally be set appropriately in the policy configuration file
806    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
807        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
808    }
809    if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
810        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
811    }
812    // only allow deep buffering for music stream type
813    if (stream != AUDIO_STREAM_MUSIC) {
814        flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
815    } else if (/* stream == AUDIO_STREAM_MUSIC && */
816            flags == AUDIO_OUTPUT_FLAG_NONE &&
817            property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
818        // use DEEP_BUFFER as default output for music stream type
819        flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
820    }
821    if (stream == AUDIO_STREAM_TTS) {
822        flags = AUDIO_OUTPUT_FLAG_TTS;
823    }
824
825    sp<IOProfile> profile;
826
827    // skip direct output selection if the request can obviously be attached to a mixed output
828    // and not explicitly requested
829    if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
830            audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
831            audio_channel_count_from_out_mask(channelMask) <= 2) {
832        goto non_direct_output;
833    }
834
835    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
836    // creating an offloaded track and tearing it down immediately after start when audioflinger
837    // detects there is an active non offloadable effect.
838    // FIXME: We should check the audio session here but we do not have it in this context.
839    // This may prevent offloading in rare situations where effects are left active by apps
840    // in the background.
841
842    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
843            !mEffects.isNonOffloadableEffectEnabled()) {
844        profile = getProfileForDirectOutput(device,
845                                           samplingRate,
846                                           format,
847                                           channelMask,
848                                           (audio_output_flags_t)flags);
849    }
850
851    if (profile != 0) {
852        sp<SwAudioOutputDescriptor> outputDesc = NULL;
853
854        for (size_t i = 0; i < mOutputs.size(); i++) {
855            sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
856            if (!desc->isDuplicated() && (profile == desc->mProfile)) {
857                outputDesc = desc;
858                // reuse direct output if currently open and configured with same parameters
859                if ((samplingRate == outputDesc->mSamplingRate) &&
860                        (format == outputDesc->mFormat) &&
861                        (channelMask == outputDesc->mChannelMask)) {
862                    outputDesc->mDirectOpenCount++;
863                    ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
864                    return mOutputs.keyAt(i);
865                }
866            }
867        }
868        // close direct output if currently open and configured with different parameters
869        if (outputDesc != NULL) {
870            closeOutput(outputDesc->mIoHandle);
871        }
872
873        // if the selected profile is offloaded and no offload info was specified,
874        // create a default one
875        audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
876        if ((profile->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
877            flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
878            defaultOffloadInfo.sample_rate = samplingRate;
879            defaultOffloadInfo.channel_mask = channelMask;
880            defaultOffloadInfo.format = format;
881            defaultOffloadInfo.stream_type = stream;
882            defaultOffloadInfo.bit_rate = 0;
883            defaultOffloadInfo.duration_us = -1;
884            defaultOffloadInfo.has_video = true; // conservative
885            defaultOffloadInfo.is_streaming = true; // likely
886            offloadInfo = &defaultOffloadInfo;
887        }
888
889        outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
890        outputDesc->mDevice = device;
891        outputDesc->mLatency = 0;
892        outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
893        audio_config_t config = AUDIO_CONFIG_INITIALIZER;
894        config.sample_rate = samplingRate;
895        config.channel_mask = channelMask;
896        config.format = format;
897        if (offloadInfo != NULL) {
898            config.offload_info = *offloadInfo;
899        }
900        status = mpClientInterface->openOutput(profile->getModuleHandle(),
901                                               &output,
902                                               &config,
903                                               &outputDesc->mDevice,
904                                               String8(""),
905                                               &outputDesc->mLatency,
906                                               outputDesc->mFlags);
907
908        // only accept an output with the requested parameters
909        if (status != NO_ERROR ||
910            (samplingRate != 0 && samplingRate != config.sample_rate) ||
911            (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
912            (channelMask != 0 && channelMask != config.channel_mask)) {
913            ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
914                    "format %d %d, channelMask %04x %04x", output, samplingRate,
915                    outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
916                    outputDesc->mChannelMask);
917            if (output != AUDIO_IO_HANDLE_NONE) {
918                mpClientInterface->closeOutput(output);
919            }
920            // fall back to mixer output if possible when the direct output could not be open
921            if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
922                goto non_direct_output;
923            }
924            return AUDIO_IO_HANDLE_NONE;
925        }
926        outputDesc->mSamplingRate = config.sample_rate;
927        outputDesc->mChannelMask = config.channel_mask;
928        outputDesc->mFormat = config.format;
929        outputDesc->mRefCount[stream] = 0;
930        outputDesc->mStopTime[stream] = 0;
931        outputDesc->mDirectOpenCount = 1;
932
933        audio_io_handle_t srcOutput = getOutputForEffect();
934        addOutput(output, outputDesc);
935        audio_io_handle_t dstOutput = getOutputForEffect();
936        if (dstOutput == output) {
937            mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
938        }
939        mPreviousOutputs = mOutputs;
940        ALOGV("getOutput() returns new direct output %d", output);
941        mpClientInterface->onAudioPortListUpdate();
942        return output;
943    }
944
945non_direct_output:
946    // ignoring channel mask due to downmix capability in mixer
947
948    // open a non direct output
949
950    // for non direct outputs, only PCM is supported
951    if (audio_is_linear_pcm(format)) {
952        // get which output is suitable for the specified stream. The actual
953        // routing change will happen when startOutput() will be called
954        SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
955
956        // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
957        flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
958        output = selectOutput(outputs, flags, format);
959    }
960    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
961            "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
962
963    ALOGV("  getOutputForDevice() returns output %d", output);
964
965    return output;
966}
967
968audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
969                                                       audio_output_flags_t flags,
970                                                       audio_format_t format)
971{
972    // select one output among several that provide a path to a particular device or set of
973    // devices (the list was previously build by getOutputsForDevice()).
974    // The priority is as follows:
975    // 1: the output with the highest number of requested policy flags
976    // 2: the primary output
977    // 3: the first output in the list
978
979    if (outputs.size() == 0) {
980        return 0;
981    }
982    if (outputs.size() == 1) {
983        return outputs[0];
984    }
985
986    int maxCommonFlags = 0;
987    audio_io_handle_t outputFlags = 0;
988    audio_io_handle_t outputPrimary = 0;
989
990    for (size_t i = 0; i < outputs.size(); i++) {
991        sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
992        if (!outputDesc->isDuplicated()) {
993            // if a valid format is specified, skip output if not compatible
994            if (format != AUDIO_FORMAT_INVALID) {
995                if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
996                    if (format != outputDesc->mFormat) {
997                        continue;
998                    }
999                } else if (!audio_is_linear_pcm(format)) {
1000                    continue;
1001                }
1002            }
1003
1004            int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
1005            if (commonFlags > maxCommonFlags) {
1006                outputFlags = outputs[i];
1007                maxCommonFlags = commonFlags;
1008                ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1009            }
1010            if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1011                outputPrimary = outputs[i];
1012            }
1013        }
1014    }
1015
1016    if (outputFlags != 0) {
1017        return outputFlags;
1018    }
1019    if (outputPrimary != 0) {
1020        return outputPrimary;
1021    }
1022
1023    return outputs[0];
1024}
1025
1026status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
1027                                             audio_stream_type_t stream,
1028                                             audio_session_t session)
1029{
1030    ALOGV("startOutput() output %d, stream %d, session %d",
1031          output, stream, session);
1032    ssize_t index = mOutputs.indexOfKey(output);
1033    if (index < 0) {
1034        ALOGW("startOutput() unknown output %d", output);
1035        return BAD_VALUE;
1036    }
1037
1038    sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1039
1040    // Routing?
1041    mOutputRoutes.incRouteActivity(session);
1042
1043    audio_devices_t newDevice;
1044    if (outputDesc->mPolicyMix != NULL) {
1045        newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1046    } else if (mOutputRoutes.hasRouteChanged(session)) {
1047        newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1048        checkStrategyRoute(getStrategy(stream), output);
1049    } else {
1050        newDevice = AUDIO_DEVICE_NONE;
1051    }
1052
1053    uint32_t delayMs = 0;
1054
1055    status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1056
1057    if (status != NO_ERROR) {
1058        mOutputRoutes.decRouteActivity(session);
1059        return status;
1060    }
1061    // Automatically enable the remote submix input when output is started on a re routing mix
1062    // of type MIX_TYPE_RECORDERS
1063    if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1064            outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1065            setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1066                    AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1067                    outputDesc->mPolicyMix->mRegistrationId,
1068                    "remote-submix");
1069    }
1070
1071    if (delayMs != 0) {
1072        usleep(delayMs * 1000);
1073    }
1074
1075    return status;
1076}
1077
1078status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1079                                             audio_stream_type_t stream,
1080                                             audio_devices_t device,
1081                                             uint32_t *delayMs)
1082{
1083    // cannot start playback of STREAM_TTS if any other output is being used
1084    uint32_t beaconMuteLatency = 0;
1085
1086    *delayMs = 0;
1087    if (stream == AUDIO_STREAM_TTS) {
1088        ALOGV("\t found BEACON stream");
1089        if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1090            return INVALID_OPERATION;
1091        } else {
1092            beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1093        }
1094    } else {
1095        // some playback other than beacon starts
1096        beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1097    }
1098
1099    // check active before incrementing usage count
1100    bool force = !outputDesc->isActive();
1101
1102    // increment usage count for this stream on the requested output:
1103    // NOTE that the usage count is the same for duplicated output and hardware output which is
1104    // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1105    outputDesc->changeRefCount(stream, 1);
1106
1107    if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
1108        // starting an output being rerouted?
1109        if (device == AUDIO_DEVICE_NONE) {
1110            device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1111        }
1112        routing_strategy strategy = getStrategy(stream);
1113        bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1114                            (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1115                            (beaconMuteLatency > 0);
1116        uint32_t waitMs = beaconMuteLatency;
1117        for (size_t i = 0; i < mOutputs.size(); i++) {
1118            sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1119            if (desc != outputDesc) {
1120                // force a device change if any other output is managed by the same hw
1121                // module and has a current device selection that differs from selected device.
1122                // In this case, the audio HAL must receive the new device selection so that it can
1123                // change the device currently selected by the other active output.
1124                if (outputDesc->sharesHwModuleWith(desc) &&
1125                    desc->device() != device) {
1126                    force = true;
1127                }
1128                // wait for audio on other active outputs to be presented when starting
1129                // a notification so that audio focus effect can propagate, or that a mute/unmute
1130                // event occurred for beacon
1131                uint32_t latency = desc->latency();
1132                if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1133                    waitMs = latency;
1134                }
1135            }
1136        }
1137        uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
1138
1139        // handle special case for sonification while in call
1140        if (isInCall()) {
1141            handleIncallSonification(stream, true, false);
1142        }
1143
1144        // apply volume rules for current stream and device if necessary
1145        checkAndSetVolume(stream,
1146                          mStreams.valueFor(stream).getVolumeIndex(device),
1147                          outputDesc,
1148                          device);
1149
1150        // update the outputs if starting an output with a stream that can affect notification
1151        // routing
1152        handleNotificationRoutingForStream(stream);
1153
1154        // force reevaluating accessibility routing when ringtone or alarm starts
1155        if (strategy == STRATEGY_SONIFICATION) {
1156            mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1157        }
1158    }
1159    return NO_ERROR;
1160}
1161
1162
1163status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
1164                                            audio_stream_type_t stream,
1165                                            audio_session_t session)
1166{
1167    ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1168    ssize_t index = mOutputs.indexOfKey(output);
1169    if (index < 0) {
1170        ALOGW("stopOutput() unknown output %d", output);
1171        return BAD_VALUE;
1172    }
1173
1174    sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1175
1176    if (outputDesc->mRefCount[stream] == 1) {
1177        // Automatically disable the remote submix input when output is stopped on a
1178        // re routing mix of type MIX_TYPE_RECORDERS
1179        if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1180                outputDesc->mPolicyMix != NULL &&
1181                outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1182            setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1183                    AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1184                    outputDesc->mPolicyMix->mRegistrationId,
1185                    "remote-submix");
1186        }
1187    }
1188
1189    // Routing?
1190    bool forceDeviceUpdate = false;
1191    if (outputDesc->mRefCount[stream] > 0) {
1192        int activityCount = mOutputRoutes.decRouteActivity(session);
1193        forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1194
1195        if (forceDeviceUpdate) {
1196            checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1197        }
1198    }
1199
1200    return stopSource(outputDesc, stream, forceDeviceUpdate);
1201}
1202
1203status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
1204                                            audio_stream_type_t stream,
1205                                            bool forceDeviceUpdate)
1206{
1207    // always handle stream stop, check which stream type is stopping
1208    handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1209
1210    // handle special case for sonification while in call
1211    if (isInCall()) {
1212        handleIncallSonification(stream, false, false);
1213    }
1214
1215    if (outputDesc->mRefCount[stream] > 0) {
1216        // decrement usage count of this stream on the output
1217        outputDesc->changeRefCount(stream, -1);
1218
1219        // store time at which the stream was stopped - see isStreamActive()
1220        if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
1221            outputDesc->mStopTime[stream] = systemTime();
1222            audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1223            // delay the device switch by twice the latency because stopOutput() is executed when
1224            // the track stop() command is received and at that time the audio track buffer can
1225            // still contain data that needs to be drained. The latency only covers the audio HAL
1226            // and kernel buffers. Also the latency does not always include additional delay in the
1227            // audio path (audio DSP, CODEC ...)
1228            setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
1229
1230            // force restoring the device selection on other active outputs if it differs from the
1231            // one being selected for this output
1232            for (size_t i = 0; i < mOutputs.size(); i++) {
1233                audio_io_handle_t curOutput = mOutputs.keyAt(i);
1234                sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1235                if (desc != outputDesc &&
1236                        desc->isActive() &&
1237                        outputDesc->sharesHwModuleWith(desc) &&
1238                        (newDevice != desc->device())) {
1239                    setOutputDevice(desc,
1240                                    getNewOutputDevice(desc, false /*fromCache*/),
1241                                    true,
1242                                    outputDesc->latency()*2);
1243                }
1244            }
1245            // update the outputs if stopping one with a stream that can affect notification routing
1246            handleNotificationRoutingForStream(stream);
1247        }
1248        return NO_ERROR;
1249    } else {
1250        ALOGW("stopOutput() refcount is already 0");
1251        return INVALID_OPERATION;
1252    }
1253}
1254
1255void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
1256                                       audio_stream_type_t stream __unused,
1257                                       audio_session_t session __unused)
1258{
1259    ALOGV("releaseOutput() %d", output);
1260    ssize_t index = mOutputs.indexOfKey(output);
1261    if (index < 0) {
1262        ALOGW("releaseOutput() releasing unknown output %d", output);
1263        return;
1264    }
1265
1266#ifdef AUDIO_POLICY_TEST
1267    int testIndex = testOutputIndex(output);
1268    if (testIndex != 0) {
1269        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1270        if (outputDesc->isActive()) {
1271            mpClientInterface->closeOutput(output);
1272            removeOutput(output);
1273            mTestOutputs[testIndex] = 0;
1274        }
1275        return;
1276    }
1277#endif //AUDIO_POLICY_TEST
1278
1279    // Routing
1280    mOutputRoutes.removeRoute(session);
1281
1282    sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
1283    if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1284        if (desc->mDirectOpenCount <= 0) {
1285            ALOGW("releaseOutput() invalid open count %d for output %d",
1286                                                              desc->mDirectOpenCount, output);
1287            return;
1288        }
1289        if (--desc->mDirectOpenCount == 0) {
1290            closeOutput(output);
1291            // If effects where present on the output, audioflinger moved them to the primary
1292            // output by default: move them back to the appropriate output.
1293            audio_io_handle_t dstOutput = getOutputForEffect();
1294            if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
1295                mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1296                                               mPrimaryOutput->mIoHandle, dstOutput);
1297            }
1298            mpClientInterface->onAudioPortListUpdate();
1299        }
1300    }
1301}
1302
1303
1304status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1305                                             audio_io_handle_t *input,
1306                                             audio_session_t session,
1307                                             uid_t uid,
1308                                             uint32_t samplingRate,
1309                                             audio_format_t format,
1310                                             audio_channel_mask_t channelMask,
1311                                             audio_input_flags_t flags,
1312                                             audio_port_handle_t selectedDeviceId,
1313                                             input_type_t *inputType)
1314{
1315    ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1316            "session %d, flags %#x",
1317          attr->source, samplingRate, format, channelMask, session, flags);
1318
1319    *input = AUDIO_IO_HANDLE_NONE;
1320    *inputType = API_INPUT_INVALID;
1321    audio_devices_t device;
1322    // handle legacy remote submix case where the address was not always specified
1323    String8 address = String8("");
1324    bool isSoundTrigger = false;
1325    audio_source_t inputSource = attr->source;
1326    audio_source_t halInputSource;
1327    AudioMix *policyMix = NULL;
1328
1329    if (inputSource == AUDIO_SOURCE_DEFAULT) {
1330        inputSource = AUDIO_SOURCE_MIC;
1331    }
1332    halInputSource = inputSource;
1333
1334    // Explicit routing?
1335    sp<DeviceDescriptor> deviceDesc;
1336    for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1337        if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1338            deviceDesc = mAvailableInputDevices[i];
1339            break;
1340        }
1341    }
1342    mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
1343
1344    if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
1345            strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1346        status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1347        if (ret != NO_ERROR) {
1348            return ret;
1349        }
1350        *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1351        device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1352        address = String8(attr->tags + strlen("addr="));
1353    } else {
1354        device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1355        if (device == AUDIO_DEVICE_NONE) {
1356            ALOGW("getInputForAttr() could not find device for source %d", inputSource);
1357            return BAD_VALUE;
1358        }
1359        if (policyMix != NULL) {
1360            address = policyMix->mRegistrationId;
1361            if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1362                // there is an external policy, but this input is attached to a mix of recorders,
1363                // meaning it receives audio injected into the framework, so the recorder doesn't
1364                // know about it and is therefore considered "legacy"
1365                *inputType = API_INPUT_LEGACY;
1366            } else {
1367                // recording a mix of players defined by an external policy, we're rerouting for
1368                // an external policy
1369                *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1370            }
1371        } else if (audio_is_remote_submix_device(device)) {
1372            address = String8("0");
1373            *inputType = API_INPUT_MIX_CAPTURE;
1374        } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1375            *inputType = API_INPUT_TELEPHONY_RX;
1376        } else {
1377            *inputType = API_INPUT_LEGACY;
1378        }
1379        // adapt channel selection to input source
1380        switch (inputSource) {
1381        case AUDIO_SOURCE_VOICE_UPLINK:
1382            channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1383            break;
1384        case AUDIO_SOURCE_VOICE_DOWNLINK:
1385            channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1386            break;
1387        case AUDIO_SOURCE_VOICE_CALL:
1388            channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1389            break;
1390        default:
1391            break;
1392        }
1393        if (inputSource == AUDIO_SOURCE_HOTWORD) {
1394            ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1395            if (index >= 0) {
1396                *input = mSoundTriggerSessions.valueFor(session);
1397                isSoundTrigger = true;
1398                flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1399                ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1400            } else {
1401                halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1402            }
1403        }
1404    }
1405
1406    // find a compatible input profile (not necessarily identical in parameters)
1407    sp<IOProfile> profile;
1408    // samplingRate and flags may be updated by getInputProfile
1409    uint32_t profileSamplingRate = samplingRate;
1410    audio_format_t profileFormat = format;
1411    audio_channel_mask_t profileChannelMask = channelMask;
1412    audio_input_flags_t profileFlags = flags;
1413    for (;;) {
1414        profile = getInputProfile(device, address,
1415                                  profileSamplingRate, profileFormat, profileChannelMask,
1416                                  profileFlags);
1417        if (profile != 0) {
1418            break; // success
1419        } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1420            profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1421        } else { // fail
1422            ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1423                    "format %#x, channelMask 0x%X, flags %#x",
1424                    device, samplingRate, format, channelMask, flags);
1425            return BAD_VALUE;
1426        }
1427    }
1428
1429    if (profile->getModuleHandle() == 0) {
1430        ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
1431        return NO_INIT;
1432    }
1433
1434    audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1435    config.sample_rate = profileSamplingRate;
1436    config.channel_mask = profileChannelMask;
1437    config.format = profileFormat;
1438
1439    status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
1440                                                   input,
1441                                                   &config,
1442                                                   &device,
1443                                                   address,
1444                                                   halInputSource,
1445                                                   profileFlags);
1446
1447    // only accept input with the exact requested set of parameters
1448    if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
1449        (profileSamplingRate != config.sample_rate) ||
1450        (profileFormat != config.format) ||
1451        (profileChannelMask != config.channel_mask)) {
1452        ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d,"
1453                " channelMask %x",
1454                samplingRate, format, channelMask);
1455        if (*input != AUDIO_IO_HANDLE_NONE) {
1456            mpClientInterface->closeInput(*input);
1457        }
1458        return BAD_VALUE;
1459    }
1460
1461    sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
1462    inputDesc->mInputSource = inputSource;
1463    inputDesc->mRefCount = 0;
1464    inputDesc->mOpenRefCount = 1;
1465    inputDesc->mSamplingRate = profileSamplingRate;
1466    inputDesc->mFormat = profileFormat;
1467    inputDesc->mChannelMask = profileChannelMask;
1468    inputDesc->mDevice = device;
1469    inputDesc->mSessions.add(session);
1470    inputDesc->mIsSoundTrigger = isSoundTrigger;
1471    inputDesc->mPolicyMix = policyMix;
1472
1473    ALOGV("getInputForAttr() returns input type = %d", *inputType);
1474
1475    addInput(*input, inputDesc);
1476    mpClientInterface->onAudioPortListUpdate();
1477
1478    return NO_ERROR;
1479}
1480
1481status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1482                                        audio_session_t session)
1483{
1484    ALOGV("startInput() input %d", input);
1485    ssize_t index = mInputs.indexOfKey(input);
1486    if (index < 0) {
1487        ALOGW("startInput() unknown input %d", input);
1488        return BAD_VALUE;
1489    }
1490    sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1491
1492    index = inputDesc->mSessions.indexOf(session);
1493    if (index < 0) {
1494        ALOGW("startInput() unknown session %d on input %d", session, input);
1495        return BAD_VALUE;
1496    }
1497
1498    // virtual input devices are compatible with other input devices
1499    if (!is_virtual_input_device(inputDesc->mDevice)) {
1500
1501        // for a non-virtual input device, check if there is another (non-virtual) active input
1502        audio_io_handle_t activeInput = mInputs.getActiveInput();
1503        if (activeInput != 0 && activeInput != input) {
1504
1505            // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1506            // otherwise the active input continues and the new input cannot be started.
1507            sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1508            if ((activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) &&
1509                    !activeDesc->hasPreemptedSession(session)) {
1510                ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1511                audio_session_t activeSession = activeDesc->mSessions.itemAt(0);
1512                SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1513                sessions.add(activeSession);
1514                inputDesc->setPreemptedSessions(sessions);
1515                stopInput(activeInput, activeSession);
1516                releaseInput(activeInput, activeSession);
1517            } else {
1518                ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1519                return INVALID_OPERATION;
1520            }
1521        }
1522
1523        // Do not allow capture if an active voice call is using a software patch and
1524        // the call TX source device is on the same HW module.
1525        // FIXME: would be better to refine to only inputs whose profile connects to the
1526        // call TX device but this information is not in the audio patch
1527        if (mCallTxPatch != 0 &&
1528            inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1529            return INVALID_OPERATION;
1530        }
1531    }
1532
1533    // Routing?
1534    mInputRoutes.incRouteActivity(session);
1535
1536    if (inputDesc->mRefCount == 0 || mInputRoutes.hasRouteChanged(session)) {
1537        // if input maps to a dynamic policy with an activity listener, notify of state change
1538        if ((inputDesc->mPolicyMix != NULL)
1539                && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1540            mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1541                    MIX_STATE_MIXING);
1542        }
1543
1544        if (mInputs.activeInputsCount() == 0) {
1545            SoundTrigger::setCaptureState(true);
1546        }
1547        setInputDevice(input, getNewInputDevice(input), true /* force */);
1548
1549        // automatically enable the remote submix output when input is started if not
1550        // used by a policy mix of type MIX_TYPE_RECORDERS
1551        // For remote submix (a virtual device), we open only one input per capture request.
1552        if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1553            String8 address = String8("");
1554            if (inputDesc->mPolicyMix == NULL) {
1555                address = String8("0");
1556            } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1557                address = inputDesc->mPolicyMix->mRegistrationId;
1558            }
1559            if (address != "") {
1560                setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1561                        AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1562                        address, "remote-submix");
1563            }
1564        }
1565    }
1566
1567    ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1568
1569    inputDesc->mRefCount++;
1570    return NO_ERROR;
1571}
1572
1573status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1574                                       audio_session_t session)
1575{
1576    ALOGV("stopInput() input %d", input);
1577    ssize_t index = mInputs.indexOfKey(input);
1578    if (index < 0) {
1579        ALOGW("stopInput() unknown input %d", input);
1580        return BAD_VALUE;
1581    }
1582    sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1583
1584    index = inputDesc->mSessions.indexOf(session);
1585    if (index < 0) {
1586        ALOGW("stopInput() unknown session %d on input %d", session, input);
1587        return BAD_VALUE;
1588    }
1589
1590    if (inputDesc->mRefCount == 0) {
1591        ALOGW("stopInput() input %d already stopped", input);
1592        return INVALID_OPERATION;
1593    }
1594
1595    inputDesc->mRefCount--;
1596
1597    // Routing?
1598    mInputRoutes.decRouteActivity(session);
1599
1600    if (inputDesc->mRefCount == 0) {
1601        // if input maps to a dynamic policy with an activity listener, notify of state change
1602        if ((inputDesc->mPolicyMix != NULL)
1603                && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1604            mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1605                    MIX_STATE_IDLE);
1606        }
1607
1608        // automatically disable the remote submix output when input is stopped if not
1609        // used by a policy mix of type MIX_TYPE_RECORDERS
1610        if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1611            String8 address = String8("");
1612            if (inputDesc->mPolicyMix == NULL) {
1613                address = String8("0");
1614            } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1615                address = inputDesc->mPolicyMix->mRegistrationId;
1616            }
1617            if (address != "") {
1618                setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1619                                         AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1620                                         address, "remote-submix");
1621            }
1622        }
1623
1624        resetInputDevice(input);
1625
1626        if (mInputs.activeInputsCount() == 0) {
1627            SoundTrigger::setCaptureState(false);
1628        }
1629        inputDesc->clearPreemptedSessions();
1630    }
1631    return NO_ERROR;
1632}
1633
1634void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1635                                      audio_session_t session)
1636{
1637    ALOGV("releaseInput() %d", input);
1638    ssize_t index = mInputs.indexOfKey(input);
1639    if (index < 0) {
1640        ALOGW("releaseInput() releasing unknown input %d", input);
1641        return;
1642    }
1643
1644    // Routing
1645    mInputRoutes.removeRoute(session);
1646
1647    sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1648    ALOG_ASSERT(inputDesc != 0);
1649
1650    index = inputDesc->mSessions.indexOf(session);
1651    if (index < 0) {
1652        ALOGW("releaseInput() unknown session %d on input %d", session, input);
1653        return;
1654    }
1655    inputDesc->mSessions.remove(session);
1656    if (inputDesc->mOpenRefCount == 0) {
1657        ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1658        return;
1659    }
1660    inputDesc->mOpenRefCount--;
1661    if (inputDesc->mOpenRefCount > 0) {
1662        ALOGV("releaseInput() exit > 0");
1663        return;
1664    }
1665
1666    closeInput(input);
1667    mpClientInterface->onAudioPortListUpdate();
1668    ALOGV("releaseInput() exit");
1669}
1670
1671void AudioPolicyManager::closeAllInputs() {
1672    bool patchRemoved = false;
1673
1674    for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1675        sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1676        ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1677        if (patch_index >= 0) {
1678            sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1679            status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1680            mAudioPatches.removeItemsAt(patch_index);
1681            patchRemoved = true;
1682        }
1683        mpClientInterface->closeInput(mInputs.keyAt(input_index));
1684    }
1685    mInputs.clear();
1686    nextAudioPortGeneration();
1687
1688    if (patchRemoved) {
1689        mpClientInterface->onAudioPatchListUpdate();
1690    }
1691}
1692
1693void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
1694                                            int indexMin,
1695                                            int indexMax)
1696{
1697    ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1698    mEngine->initStreamVolume(stream, indexMin, indexMax);
1699    //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1700    if (stream == AUDIO_STREAM_MUSIC) {
1701        mEngine->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
1702    }
1703}
1704
1705status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
1706                                                  int index,
1707                                                  audio_devices_t device)
1708{
1709
1710    if ((index < mStreams.valueFor(stream).getVolumeIndexMin()) ||
1711            (index > mStreams.valueFor(stream).getVolumeIndexMax())) {
1712        return BAD_VALUE;
1713    }
1714    if (!audio_is_output_device(device)) {
1715        return BAD_VALUE;
1716    }
1717
1718    // Force max volume if stream cannot be muted
1719    if (!mStreams.canBeMuted(stream)) index = mStreams.valueFor(stream).getVolumeIndexMax();
1720
1721    ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1722          stream, device, index);
1723
1724    // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1725    // clear all device specific values
1726    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1727        mStreams.clearCurrentVolumeIndex(stream);
1728    }
1729    mStreams.addCurrentVolumeIndex(stream, device, index);
1730
1731    // update volume on all outputs whose current device is also selected by the same
1732    // strategy as the device specified by the caller
1733    audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1734
1735
1736    //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1737    audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1738    if (stream == AUDIO_STREAM_MUSIC) {
1739        mStreams.addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
1740        accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1741    }
1742    if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1743            (device & (strategyDevice | accessibilityDevice)) == 0) {
1744        return NO_ERROR;
1745    }
1746    status_t status = NO_ERROR;
1747    for (size_t i = 0; i < mOutputs.size(); i++) {
1748        sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1749        audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
1750        if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
1751            status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
1752            if (volStatus != NO_ERROR) {
1753                status = volStatus;
1754            }
1755        }
1756        if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
1757                ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
1758        {
1759            status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1760                                                   index, desc, curDevice);
1761        }
1762    }
1763    return status;
1764}
1765
1766status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
1767                                                      int *index,
1768                                                      audio_devices_t device)
1769{
1770    if (index == NULL) {
1771        return BAD_VALUE;
1772    }
1773    if (!audio_is_output_device(device)) {
1774        return BAD_VALUE;
1775    }
1776    // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1777    // the strategy the stream belongs to.
1778    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1779        device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1780    }
1781    device = Volume::getDeviceForVolume(device);
1782
1783    *index =  mStreams.valueFor(stream).getVolumeIndex(device);
1784    ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1785    return NO_ERROR;
1786}
1787
1788audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
1789                                            const SortedVector<audio_io_handle_t>& outputs)
1790{
1791    // select one output among several suitable for global effects.
1792    // The priority is as follows:
1793    // 1: An offloaded output. If the effect ends up not being offloadable,
1794    //    AudioFlinger will invalidate the track and the offloaded output
1795    //    will be closed causing the effect to be moved to a PCM output.
1796    // 2: A deep buffer output
1797    // 3: the first output in the list
1798
1799    if (outputs.size() == 0) {
1800        return 0;
1801    }
1802
1803    audio_io_handle_t outputOffloaded = 0;
1804    audio_io_handle_t outputDeepBuffer = 0;
1805
1806    for (size_t i = 0; i < outputs.size(); i++) {
1807        sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
1808        ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1809        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1810            outputOffloaded = outputs[i];
1811        }
1812        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1813            outputDeepBuffer = outputs[i];
1814        }
1815    }
1816
1817    ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1818          outputOffloaded, outputDeepBuffer);
1819    if (outputOffloaded != 0) {
1820        return outputOffloaded;
1821    }
1822    if (outputDeepBuffer != 0) {
1823        return outputDeepBuffer;
1824    }
1825
1826    return outputs[0];
1827}
1828
1829audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
1830{
1831    // apply simple rule where global effects are attached to the same output as MUSIC streams
1832
1833    routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
1834    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1835    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1836
1837    audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1838    ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1839          output, (desc == NULL) ? "unspecified" : desc->name,  (desc == NULL) ? 0 : desc->flags);
1840
1841    return output;
1842}
1843
1844status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
1845                                audio_io_handle_t io,
1846                                uint32_t strategy,
1847                                int session,
1848                                int id)
1849{
1850    ssize_t index = mOutputs.indexOfKey(io);
1851    if (index < 0) {
1852        index = mInputs.indexOfKey(io);
1853        if (index < 0) {
1854            ALOGW("registerEffect() unknown io %d", io);
1855            return INVALID_OPERATION;
1856        }
1857    }
1858    return mEffects.registerEffect(desc, io, strategy, session, id);
1859}
1860
1861bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1862{
1863    return mOutputs.isStreamActive(stream, inPastMs);
1864}
1865
1866bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1867{
1868    return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1869}
1870
1871bool AudioPolicyManager::isSourceActive(audio_source_t source) const
1872{
1873    for (size_t i = 0; i < mInputs.size(); i++) {
1874        const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
1875        if (inputDescriptor->mRefCount == 0) {
1876            continue;
1877        }
1878        if (inputDescriptor->mInputSource == (int)source) {
1879            return true;
1880        }
1881        // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
1882        // corresponds to an active capture triggered by a hardware hotword recognition
1883        if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
1884                 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
1885            // FIXME: we should not assume that the first session is the active one and keep
1886            // activity count per session. Same in startInput().
1887            ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
1888            if (index >= 0) {
1889                return true;
1890            }
1891        }
1892    }
1893    return false;
1894}
1895
1896// Register a list of custom mixes with their attributes and format.
1897// When a mix is registered, corresponding input and output profiles are
1898// added to the remote submix hw module. The profile contains only the
1899// parameters (sampling rate, format...) specified by the mix.
1900// The corresponding input remote submix device is also connected.
1901//
1902// When a remote submix device is connected, the address is checked to select the
1903// appropriate profile and the corresponding input or output stream is opened.
1904//
1905// When capture starts, getInputForAttr() will:
1906//  - 1 look for a mix matching the address passed in attribtutes tags if any
1907//  - 2 if none found, getDeviceForInputSource() will:
1908//     - 2.1 look for a mix matching the attributes source
1909//     - 2.2 if none found, default to device selection by policy rules
1910// At this time, the corresponding output remote submix device is also connected
1911// and active playback use cases can be transferred to this mix if needed when reconnecting
1912// after AudioTracks are invalidated
1913//
1914// When playback starts, getOutputForAttr() will:
1915//  - 1 look for a mix matching the address passed in attribtutes tags if any
1916//  - 2 if none found, look for a mix matching the attributes usage
1917//  - 3 if none found, default to device and output selection by policy rules.
1918
1919status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
1920{
1921    sp<HwModule> module;
1922    for (size_t i = 0; i < mHwModules.size(); i++) {
1923        if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1924                mHwModules[i]->mHandle != 0) {
1925            module = mHwModules[i];
1926            break;
1927        }
1928    }
1929
1930    if (module == 0) {
1931        return INVALID_OPERATION;
1932    }
1933
1934    ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
1935
1936    for (size_t i = 0; i < mixes.size(); i++) {
1937        String8 address = mixes[i].mRegistrationId;
1938
1939        if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
1940            continue;
1941        }
1942        audio_config_t outputConfig = mixes[i].mFormat;
1943        audio_config_t inputConfig = mixes[i].mFormat;
1944        // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
1945        // stereo and let audio flinger do the channel conversion if needed.
1946        outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1947        inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
1948        module->addOutputProfile(address, &outputConfig,
1949                                 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
1950        module->addInputProfile(address, &inputConfig,
1951                                 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
1952
1953        if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
1954            setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1955                                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1956                                     address.string(), "remote-submix");
1957        } else {
1958            setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1959                                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1960                                     address.string(), "remote-submix");
1961        }
1962    }
1963    return NO_ERROR;
1964}
1965
1966status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
1967{
1968    sp<HwModule> module;
1969    for (size_t i = 0; i < mHwModules.size(); i++) {
1970        if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1971                mHwModules[i]->mHandle != 0) {
1972            module = mHwModules[i];
1973            break;
1974        }
1975    }
1976
1977    if (module == 0) {
1978        return INVALID_OPERATION;
1979    }
1980
1981    ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
1982
1983    for (size_t i = 0; i < mixes.size(); i++) {
1984        String8 address = mixes[i].mRegistrationId;
1985
1986        if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
1987            continue;
1988        }
1989
1990        if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
1991                                             AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
1992        {
1993            setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1994                                     AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1995                                     address.string(), "remote-submix");
1996        }
1997
1998        if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
1999                                             AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2000        {
2001            setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2002                                     AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2003                                     address.string(), "remote-submix");
2004        }
2005        module->removeOutputProfile(address);
2006        module->removeInputProfile(address);
2007    }
2008    return NO_ERROR;
2009}
2010
2011
2012status_t AudioPolicyManager::dump(int fd)
2013{
2014    const size_t SIZE = 256;
2015    char buffer[SIZE];
2016    String8 result;
2017
2018    snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2019    result.append(buffer);
2020
2021    snprintf(buffer, SIZE, " Primary Output: %d\n",
2022             hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
2023    result.append(buffer);
2024    snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
2025    result.append(buffer);
2026    snprintf(buffer, SIZE, " Force use for communications %d\n",
2027             mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
2028    result.append(buffer);
2029    snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
2030    result.append(buffer);
2031    snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
2032    result.append(buffer);
2033    snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
2034    result.append(buffer);
2035    snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
2036    result.append(buffer);
2037    snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2038            mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
2039    result.append(buffer);
2040    snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2041    result.append(buffer);
2042
2043    write(fd, result.string(), result.size());
2044
2045    mAvailableOutputDevices.dump(fd, String8("output"));
2046    mAvailableInputDevices.dump(fd, String8("input"));
2047    mHwModules.dump(fd);
2048    mOutputs.dump(fd);
2049    mInputs.dump(fd);
2050    mStreams.dump(fd);
2051    mEffects.dump(fd);
2052    mAudioPatches.dump(fd);
2053
2054    return NO_ERROR;
2055}
2056
2057// This function checks for the parameters which can be offloaded.
2058// This can be enhanced depending on the capability of the DSP and policy
2059// of the system.
2060bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
2061{
2062    ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
2063     " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
2064     offloadInfo.sample_rate, offloadInfo.channel_mask,
2065     offloadInfo.format,
2066     offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2067     offloadInfo.has_video);
2068
2069    // Check if offload has been disabled
2070    char propValue[PROPERTY_VALUE_MAX];
2071    if (property_get("audio.offload.disable", propValue, "0")) {
2072        if (atoi(propValue) != 0) {
2073            ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2074            return false;
2075        }
2076    }
2077
2078    // Check if stream type is music, then only allow offload as of now.
2079    if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2080    {
2081        ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2082        return false;
2083    }
2084
2085    //TODO: enable audio offloading with video when ready
2086    const bool allowOffloadWithVideo =
2087            property_get_bool("audio.offload.video", false /* default_value */);
2088    if (offloadInfo.has_video && !allowOffloadWithVideo) {
2089        ALOGV("isOffloadSupported: has_video == true, returning false");
2090        return false;
2091    }
2092
2093    //If duration is less than minimum value defined in property, return false
2094    if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2095        if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2096            ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2097            return false;
2098        }
2099    } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2100        ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2101        return false;
2102    }
2103
2104    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2105    // creating an offloaded track and tearing it down immediately after start when audioflinger
2106    // detects there is an active non offloadable effect.
2107    // FIXME: We should check the audio session here but we do not have it in this context.
2108    // This may prevent offloading in rare situations where effects are left active by apps
2109    // in the background.
2110    if (mEffects.isNonOffloadableEffectEnabled()) {
2111        return false;
2112    }
2113
2114    // See if there is a profile to support this.
2115    // AUDIO_DEVICE_NONE
2116    sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
2117                                            offloadInfo.sample_rate,
2118                                            offloadInfo.format,
2119                                            offloadInfo.channel_mask,
2120                                            AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
2121    ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2122    return (profile != 0);
2123}
2124
2125status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2126                                            audio_port_type_t type,
2127                                            unsigned int *num_ports,
2128                                            struct audio_port *ports,
2129                                            unsigned int *generation)
2130{
2131    if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2132            generation == NULL) {
2133        return BAD_VALUE;
2134    }
2135    ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2136    if (ports == NULL) {
2137        *num_ports = 0;
2138    }
2139
2140    size_t portsWritten = 0;
2141    size_t portsMax = *num_ports;
2142    *num_ports = 0;
2143    if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2144        if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2145            for (size_t i = 0;
2146                    i  < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2147                mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2148            }
2149            *num_ports += mAvailableOutputDevices.size();
2150        }
2151        if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2152            for (size_t i = 0;
2153                    i  < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2154                mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2155            }
2156            *num_ports += mAvailableInputDevices.size();
2157        }
2158    }
2159    if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2160        if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2161            for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2162                mInputs[i]->toAudioPort(&ports[portsWritten++]);
2163            }
2164            *num_ports += mInputs.size();
2165        }
2166        if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2167            size_t numOutputs = 0;
2168            for (size_t i = 0; i < mOutputs.size(); i++) {
2169                if (!mOutputs[i]->isDuplicated()) {
2170                    numOutputs++;
2171                    if (portsWritten < portsMax) {
2172                        mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2173                    }
2174                }
2175            }
2176            *num_ports += numOutputs;
2177        }
2178    }
2179    *generation = curAudioPortGeneration();
2180    ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
2181    return NO_ERROR;
2182}
2183
2184status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2185{
2186    return NO_ERROR;
2187}
2188
2189status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2190                                               audio_patch_handle_t *handle,
2191                                               uid_t uid)
2192{
2193    ALOGV("createAudioPatch()");
2194
2195    if (handle == NULL || patch == NULL) {
2196        return BAD_VALUE;
2197    }
2198    ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2199
2200    if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2201            patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2202        return BAD_VALUE;
2203    }
2204    // only one source per audio patch supported for now
2205    if (patch->num_sources > 1) {
2206        return INVALID_OPERATION;
2207    }
2208
2209    if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
2210        return INVALID_OPERATION;
2211    }
2212    for (size_t i = 0; i < patch->num_sinks; i++) {
2213        if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2214            return INVALID_OPERATION;
2215        }
2216    }
2217
2218    sp<AudioPatch> patchDesc;
2219    ssize_t index = mAudioPatches.indexOfKey(*handle);
2220
2221    ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2222                                                           patch->sources[0].role,
2223                                                           patch->sources[0].type);
2224#if LOG_NDEBUG == 0
2225    for (size_t i = 0; i < patch->num_sinks; i++) {
2226        ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2227                                                             patch->sinks[i].role,
2228                                                             patch->sinks[i].type);
2229    }
2230#endif
2231
2232    if (index >= 0) {
2233        patchDesc = mAudioPatches.valueAt(index);
2234        ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2235                                                                  mUidCached, patchDesc->mUid, uid);
2236        if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2237            return INVALID_OPERATION;
2238        }
2239    } else {
2240        *handle = 0;
2241    }
2242
2243    if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2244        sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
2245        if (outputDesc == NULL) {
2246            ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2247            return BAD_VALUE;
2248        }
2249        ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2250                                                outputDesc->mIoHandle);
2251        if (patchDesc != 0) {
2252            if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2253                ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2254                                          patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2255                return BAD_VALUE;
2256            }
2257        }
2258        DeviceVector devices;
2259        for (size_t i = 0; i < patch->num_sinks; i++) {
2260            // Only support mix to devices connection
2261            // TODO add support for mix to mix connection
2262            if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2263                ALOGV("createAudioPatch() source mix but sink is not a device");
2264                return INVALID_OPERATION;
2265            }
2266            sp<DeviceDescriptor> devDesc =
2267                    mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2268            if (devDesc == 0) {
2269                ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2270                return BAD_VALUE;
2271            }
2272
2273            if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
2274                                                           devDesc->mAddress,
2275                                                           patch->sources[0].sample_rate,
2276                                                           NULL,  // updatedSamplingRate
2277                                                           patch->sources[0].format,
2278                                                           NULL,  // updatedFormat
2279                                                           patch->sources[0].channel_mask,
2280                                                           NULL,  // updatedChannelMask
2281                                                           AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2282                ALOGV("createAudioPatch() profile not supported for device %08x",
2283                        devDesc->type());
2284                return INVALID_OPERATION;
2285            }
2286            devices.add(devDesc);
2287        }
2288        if (devices.size() == 0) {
2289            return INVALID_OPERATION;
2290        }
2291
2292        // TODO: reconfigure output format and channels here
2293        ALOGV("createAudioPatch() setting device %08x on output %d",
2294              devices.types(), outputDesc->mIoHandle);
2295        setOutputDevice(outputDesc, devices.types(), true, 0, handle);
2296        index = mAudioPatches.indexOfKey(*handle);
2297        if (index >= 0) {
2298            if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2299                ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2300            }
2301            patchDesc = mAudioPatches.valueAt(index);
2302            patchDesc->mUid = uid;
2303            ALOGV("createAudioPatch() success");
2304        } else {
2305            ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2306            return INVALID_OPERATION;
2307        }
2308    } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2309        if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2310            // input device to input mix connection
2311            // only one sink supported when connecting an input device to a mix
2312            if (patch->num_sinks > 1) {
2313                return INVALID_OPERATION;
2314            }
2315            sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
2316            if (inputDesc == NULL) {
2317                return BAD_VALUE;
2318            }
2319            if (patchDesc != 0) {
2320                if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2321                    return BAD_VALUE;
2322                }
2323            }
2324            sp<DeviceDescriptor> devDesc =
2325                    mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2326            if (devDesc == 0) {
2327                return BAD_VALUE;
2328            }
2329
2330            if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
2331                                                          devDesc->mAddress,
2332                                                          patch->sinks[0].sample_rate,
2333                                                          NULL, /*updatedSampleRate*/
2334                                                          patch->sinks[0].format,
2335                                                          NULL, /*updatedFormat*/
2336                                                          patch->sinks[0].channel_mask,
2337                                                          NULL, /*updatedChannelMask*/
2338                                                          // FIXME for the parameter type,
2339                                                          // and the NONE
2340                                                          (audio_output_flags_t)
2341                                                            AUDIO_INPUT_FLAG_NONE)) {
2342                return INVALID_OPERATION;
2343            }
2344            // TODO: reconfigure output format and channels here
2345            ALOGV("createAudioPatch() setting device %08x on output %d",
2346                                                  devDesc->type(), inputDesc->mIoHandle);
2347            setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
2348            index = mAudioPatches.indexOfKey(*handle);
2349            if (index >= 0) {
2350                if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2351                    ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2352                }
2353                patchDesc = mAudioPatches.valueAt(index);
2354                patchDesc->mUid = uid;
2355                ALOGV("createAudioPatch() success");
2356            } else {
2357                ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2358                return INVALID_OPERATION;
2359            }
2360        } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2361            // device to device connection
2362            if (patchDesc != 0) {
2363                if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2364                    return BAD_VALUE;
2365                }
2366            }
2367            sp<DeviceDescriptor> srcDeviceDesc =
2368                    mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2369            if (srcDeviceDesc == 0) {
2370                return BAD_VALUE;
2371            }
2372
2373            //update source and sink with our own data as the data passed in the patch may
2374            // be incomplete.
2375            struct audio_patch newPatch = *patch;
2376            srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2377
2378            for (size_t i = 0; i < patch->num_sinks; i++) {
2379                if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2380                    ALOGV("createAudioPatch() source device but one sink is not a device");
2381                    return INVALID_OPERATION;
2382                }
2383
2384                sp<DeviceDescriptor> sinkDeviceDesc =
2385                        mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2386                if (sinkDeviceDesc == 0) {
2387                    return BAD_VALUE;
2388                }
2389                sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2390
2391                // create a software bridge in PatchPanel if:
2392                // - source and sink devices are on differnt HW modules OR
2393                // - audio HAL version is < 3.0
2394                if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
2395                        (srcDeviceDesc->mModule->mHalVersion < AUDIO_DEVICE_API_VERSION_3_0)) {
2396                    // support only one sink device for now to simplify output selection logic
2397                    if (patch->num_sinks > 1) {
2398                        return INVALID_OPERATION;
2399                    }
2400                    SortedVector<audio_io_handle_t> outputs =
2401                                            getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
2402                    // if the sink device is reachable via an opened output stream, request to go via
2403                    // this output stream by adding a second source to the patch description
2404                    audio_io_handle_t output = selectOutput(outputs,
2405                                                            AUDIO_OUTPUT_FLAG_NONE,
2406                                                            AUDIO_FORMAT_INVALID);
2407                    if (output != AUDIO_IO_HANDLE_NONE) {
2408                        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2409                        if (outputDesc->isDuplicated()) {
2410                            return INVALID_OPERATION;
2411                        }
2412                        outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2413                        newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
2414                        newPatch.num_sources = 2;
2415                    }
2416                }
2417            }
2418            // TODO: check from routing capabilities in config file and other conflicting patches
2419
2420            audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2421            if (index >= 0) {
2422                afPatchHandle = patchDesc->mAfPatchHandle;
2423            }
2424
2425            status_t status = mpClientInterface->createAudioPatch(&newPatch,
2426                                                                  &afPatchHandle,
2427                                                                  0);
2428            ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2429                                                                  status, afPatchHandle);
2430            if (status == NO_ERROR) {
2431                if (index < 0) {
2432                    patchDesc = new AudioPatch(&newPatch, uid);
2433                    addAudioPatch(patchDesc->mHandle, patchDesc);
2434                } else {
2435                    patchDesc->mPatch = newPatch;
2436                }
2437                patchDesc->mAfPatchHandle = afPatchHandle;
2438                *handle = patchDesc->mHandle;
2439                nextAudioPortGeneration();
2440                mpClientInterface->onAudioPatchListUpdate();
2441            } else {
2442                ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2443                status);
2444                return INVALID_OPERATION;
2445            }
2446        } else {
2447            return BAD_VALUE;
2448        }
2449    } else {
2450        return BAD_VALUE;
2451    }
2452    return NO_ERROR;
2453}
2454
2455status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2456                                                  uid_t uid)
2457{
2458    ALOGV("releaseAudioPatch() patch %d", handle);
2459
2460    ssize_t index = mAudioPatches.indexOfKey(handle);
2461
2462    if (index < 0) {
2463        return BAD_VALUE;
2464    }
2465    sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2466    ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2467          mUidCached, patchDesc->mUid, uid);
2468    if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2469        return INVALID_OPERATION;
2470    }
2471
2472    struct audio_patch *patch = &patchDesc->mPatch;
2473    patchDesc->mUid = mUidCached;
2474    if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2475        sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
2476        if (outputDesc == NULL) {
2477            ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2478            return BAD_VALUE;
2479        }
2480
2481        setOutputDevice(outputDesc,
2482                        getNewOutputDevice(outputDesc, true /*fromCache*/),
2483                       true,
2484                       0,
2485                       NULL);
2486    } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2487        if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2488            sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
2489            if (inputDesc == NULL) {
2490                ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2491                return BAD_VALUE;
2492            }
2493            setInputDevice(inputDesc->mIoHandle,
2494                           getNewInputDevice(inputDesc->mIoHandle),
2495                           true,
2496                           NULL);
2497        } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2498            audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2499            status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2500            ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2501                                                              status, patchDesc->mAfPatchHandle);
2502            removeAudioPatch(patchDesc->mHandle);
2503            nextAudioPortGeneration();
2504            mpClientInterface->onAudioPatchListUpdate();
2505        } else {
2506            return BAD_VALUE;
2507        }
2508    } else {
2509        return BAD_VALUE;
2510    }
2511    return NO_ERROR;
2512}
2513
2514status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2515                                              struct audio_patch *patches,
2516                                              unsigned int *generation)
2517{
2518    if (generation == NULL) {
2519        return BAD_VALUE;
2520    }
2521    *generation = curAudioPortGeneration();
2522    return mAudioPatches.listAudioPatches(num_patches, patches);
2523}
2524
2525status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
2526{
2527    ALOGV("setAudioPortConfig()");
2528
2529    if (config == NULL) {
2530        return BAD_VALUE;
2531    }
2532    ALOGV("setAudioPortConfig() on port handle %d", config->id);
2533    // Only support gain configuration for now
2534    if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2535        return INVALID_OPERATION;
2536    }
2537
2538    sp<AudioPortConfig> audioPortConfig;
2539    if (config->type == AUDIO_PORT_TYPE_MIX) {
2540        if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2541            sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
2542            if (outputDesc == NULL) {
2543                return BAD_VALUE;
2544            }
2545            ALOG_ASSERT(!outputDesc->isDuplicated(),
2546                        "setAudioPortConfig() called on duplicated output %d",
2547                        outputDesc->mIoHandle);
2548            audioPortConfig = outputDesc;
2549        } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2550            sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
2551            if (inputDesc == NULL) {
2552                return BAD_VALUE;
2553            }
2554            audioPortConfig = inputDesc;
2555        } else {
2556            return BAD_VALUE;
2557        }
2558    } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2559        sp<DeviceDescriptor> deviceDesc;
2560        if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2561            deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2562        } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2563            deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2564        } else {
2565            return BAD_VALUE;
2566        }
2567        if (deviceDesc == NULL) {
2568            return BAD_VALUE;
2569        }
2570        audioPortConfig = deviceDesc;
2571    } else {
2572        return BAD_VALUE;
2573    }
2574
2575    struct audio_port_config backupConfig;
2576    status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2577    if (status == NO_ERROR) {
2578        struct audio_port_config newConfig;
2579        audioPortConfig->toAudioPortConfig(&newConfig, config);
2580        status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
2581    }
2582    if (status != NO_ERROR) {
2583        audioPortConfig->applyAudioPortConfig(&backupConfig);
2584    }
2585
2586    return status;
2587}
2588
2589void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2590{
2591    clearAudioPatches(uid);
2592    clearSessionRoutes(uid);
2593}
2594
2595void AudioPolicyManager::clearAudioPatches(uid_t uid)
2596{
2597    for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--)  {
2598        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2599        if (patchDesc->mUid == uid) {
2600            releaseAudioPatch(mAudioPatches.keyAt(i), uid);
2601        }
2602    }
2603}
2604
2605
2606void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2607                                            audio_io_handle_t ouptutToSkip)
2608{
2609    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2610    SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2611    for (size_t j = 0; j < mOutputs.size(); j++) {
2612        if (mOutputs.keyAt(j) == ouptutToSkip) {
2613            continue;
2614        }
2615        sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2616        if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2617            continue;
2618        }
2619        // If the default device for this strategy is on another output mix,
2620        // invalidate all tracks in this strategy to force re connection.
2621        // Otherwise select new device on the output mix.
2622        if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
2623            for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
2624                if (stream == AUDIO_STREAM_PATCH) {
2625                    continue;
2626                }
2627                if (getStrategy((audio_stream_type_t)stream) == strategy) {
2628                    mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2629                }
2630            }
2631        } else {
2632            audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2633            setOutputDevice(outputDesc, newDevice, false);
2634        }
2635    }
2636}
2637
2638void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2639{
2640    // remove output routes associated with this uid
2641    SortedVector<routing_strategy> affectedStrategies;
2642    for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--)  {
2643        sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2644        if (route->mUid == uid) {
2645            mOutputRoutes.removeItemsAt(i);
2646            if (route->mDeviceDescriptor != 0) {
2647                affectedStrategies.add(getStrategy(route->mStreamType));
2648            }
2649        }
2650    }
2651    // reroute outputs if necessary
2652    for (size_t i = 0; i < affectedStrategies.size(); i++) {
2653        checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2654    }
2655
2656    // remove input routes associated with this uid
2657    SortedVector<audio_source_t> affectedSources;
2658    for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--)  {
2659        sp<SessionRoute> route = mInputRoutes.valueAt(i);
2660        if (route->mUid == uid) {
2661            mInputRoutes.removeItemsAt(i);
2662            if (route->mDeviceDescriptor != 0) {
2663                affectedSources.add(route->mSource);
2664            }
2665        }
2666    }
2667    // reroute inputs if necessary
2668    SortedVector<audio_io_handle_t> inputsToClose;
2669    for (size_t i = 0; i < mInputs.size(); i++) {
2670        sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
2671        if (affectedSources.indexOf(inputDesc->mInputSource) >= 0) {
2672            inputsToClose.add(inputDesc->mIoHandle);
2673        }
2674    }
2675    for (size_t i = 0; i < inputsToClose.size(); i++) {
2676        closeInput(inputsToClose[i]);
2677    }
2678}
2679
2680
2681status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2682                                       audio_io_handle_t *ioHandle,
2683                                       audio_devices_t *device)
2684{
2685    *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2686    *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2687    *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
2688
2689    return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
2690}
2691
2692status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source __unused,
2693                                       const audio_attributes_t *attributes __unused,
2694                                       audio_io_handle_t *handle __unused)
2695{
2696    return INVALID_OPERATION;
2697}
2698
2699status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
2700{
2701    return INVALID_OPERATION;
2702}
2703
2704// ----------------------------------------------------------------------------
2705// AudioPolicyManager
2706// ----------------------------------------------------------------------------
2707uint32_t AudioPolicyManager::nextAudioPortGeneration()
2708{
2709    return android_atomic_inc(&mAudioPortGeneration);
2710}
2711
2712AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
2713    :
2714#ifdef AUDIO_POLICY_TEST
2715    Thread(false),
2716#endif //AUDIO_POLICY_TEST
2717    mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2718    mA2dpSuspended(false),
2719    mSpeakerDrcEnabled(false),
2720    mAudioPortGeneration(1),
2721    mBeaconMuteRefCount(0),
2722    mBeaconPlayingRefCount(0),
2723    mBeaconMuted(false),
2724    mTtsOutputAvailable(false)
2725{
2726    audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
2727    if (!engineInstance) {
2728        ALOGE("%s:  Could not get an instance of policy engine", __FUNCTION__);
2729        return;
2730    }
2731    // Retrieve the Policy Manager Interface
2732    mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
2733    if (mEngine == NULL) {
2734        ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
2735        return;
2736    }
2737    mEngine->setObserver(this);
2738    status_t status = mEngine->initCheck();
2739    ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
2740
2741    mUidCached = getuid();
2742    mpClientInterface = clientInterface;
2743
2744    mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
2745    if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE,
2746                 mHwModules, mAvailableInputDevices, mAvailableOutputDevices,
2747                 mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) {
2748        if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE,
2749                                  mHwModules, mAvailableInputDevices, mAvailableOutputDevices,
2750                                  mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) {
2751            ALOGE("could not load audio policy configuration file, setting defaults");
2752            defaultAudioPolicyConfig();
2753        }
2754    }
2755    // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
2756
2757    // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
2758    mEngine->initializeVolumeCurves(mSpeakerDrcEnabled);
2759
2760    // open all output streams needed to access attached devices
2761    audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2762    audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
2763    for (size_t i = 0; i < mHwModules.size(); i++) {
2764        mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2765        if (mHwModules[i]->mHandle == 0) {
2766            ALOGW("could not open HW module %s", mHwModules[i]->mName);
2767            continue;
2768        }
2769        // open all output streams needed to access attached devices
2770        // except for direct output streams that are only opened when they are actually
2771        // required by an app.
2772        // This also validates mAvailableOutputDevices list
2773        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2774        {
2775            const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
2776
2777            if (outProfile->mSupportedDevices.isEmpty()) {
2778                ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2779                continue;
2780            }
2781            if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_TTS) != 0) {
2782                mTtsOutputAvailable = true;
2783            }
2784
2785            if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2786                continue;
2787            }
2788            audio_devices_t profileType = outProfile->mSupportedDevices.types();
2789            if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
2790                profileType = mDefaultOutputDevice->type();
2791            } else {
2792                // chose first device present in mSupportedDevices also part of
2793                // outputDeviceTypes
2794                for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
2795                    profileType = outProfile->mSupportedDevices[k]->type();
2796                    if ((profileType & outputDeviceTypes) != 0) {
2797                        break;
2798                    }
2799                }
2800            }
2801            if ((profileType & outputDeviceTypes) == 0) {
2802                continue;
2803            }
2804            sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
2805                                                                                 mpClientInterface);
2806
2807            outputDesc->mDevice = profileType;
2808            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2809            config.sample_rate = outputDesc->mSamplingRate;
2810            config.channel_mask = outputDesc->mChannelMask;
2811            config.format = outputDesc->mFormat;
2812            audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2813            status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
2814                                                            &output,
2815                                                            &config,
2816                                                            &outputDesc->mDevice,
2817                                                            String8(""),
2818                                                            &outputDesc->mLatency,
2819                                                            outputDesc->mFlags);
2820
2821            if (status != NO_ERROR) {
2822                ALOGW("Cannot open output stream for device %08x on hw module %s",
2823                      outputDesc->mDevice,
2824                      mHwModules[i]->mName);
2825            } else {
2826                outputDesc->mSamplingRate = config.sample_rate;
2827                outputDesc->mChannelMask = config.channel_mask;
2828                outputDesc->mFormat = config.format;
2829
2830                for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
2831                    audio_devices_t type = outProfile->mSupportedDevices[k]->type();
2832                    ssize_t index =
2833                            mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2834                    // give a valid ID to an attached device once confirmed it is reachable
2835                    if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
2836                        mAvailableOutputDevices[index]->attach(mHwModules[i]);
2837                    }
2838                }
2839                if (mPrimaryOutput == 0 &&
2840                        outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2841                    mPrimaryOutput = outputDesc;
2842                }
2843                addOutput(output, outputDesc);
2844                setOutputDevice(outputDesc,
2845                                outputDesc->mDevice,
2846                                true);
2847            }
2848        }
2849        // open input streams needed to access attached devices to validate
2850        // mAvailableInputDevices list
2851        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2852        {
2853            const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
2854
2855            if (inProfile->mSupportedDevices.isEmpty()) {
2856                ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2857                continue;
2858            }
2859            // chose first device present in mSupportedDevices also part of
2860            // inputDeviceTypes
2861            audio_devices_t profileType = AUDIO_DEVICE_NONE;
2862            for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
2863                profileType = inProfile->mSupportedDevices[k]->type();
2864                if (profileType & inputDeviceTypes) {
2865                    break;
2866                }
2867            }
2868            if ((profileType & inputDeviceTypes) == 0) {
2869                continue;
2870            }
2871            sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2872
2873            inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2874            inputDesc->mDevice = profileType;
2875
2876            // find the address
2877            DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2878            //   the inputs vector must be of size 1, but we don't want to crash here
2879            String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2880                    : String8("");
2881            ALOGV("  for input device 0x%x using address %s", profileType, address.string());
2882            ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2883
2884            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2885            config.sample_rate = inputDesc->mSamplingRate;
2886            config.channel_mask = inputDesc->mChannelMask;
2887            config.format = inputDesc->mFormat;
2888            audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2889            status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
2890                                                           &input,
2891                                                           &config,
2892                                                           &inputDesc->mDevice,
2893                                                           address,
2894                                                           AUDIO_SOURCE_MIC,
2895                                                           AUDIO_INPUT_FLAG_NONE);
2896
2897            if (status == NO_ERROR) {
2898                for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
2899                    audio_devices_t type = inProfile->mSupportedDevices[k]->type();
2900                    ssize_t index =
2901                            mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2902                    // give a valid ID to an attached device once confirmed it is reachable
2903                    if (index >= 0) {
2904                        sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
2905                        if (!devDesc->isAttached()) {
2906                            devDesc->attach(mHwModules[i]);
2907                            devDesc->importAudioPort(inProfile);
2908                        }
2909                    }
2910                }
2911                mpClientInterface->closeInput(input);
2912            } else {
2913                ALOGW("Cannot open input stream for device %08x on hw module %s",
2914                      inputDesc->mDevice,
2915                      mHwModules[i]->mName);
2916            }
2917        }
2918    }
2919    // make sure all attached devices have been allocated a unique ID
2920    for (size_t i = 0; i  < mAvailableOutputDevices.size();) {
2921        if (!mAvailableOutputDevices[i]->isAttached()) {
2922            ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->type());
2923            mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2924            continue;
2925        }
2926        // The device is now validated and can be appended to the available devices of the engine
2927        mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
2928                                          AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
2929        i++;
2930    }
2931    for (size_t i = 0; i  < mAvailableInputDevices.size();) {
2932        if (!mAvailableInputDevices[i]->isAttached()) {
2933            ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
2934            mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2935            continue;
2936        }
2937        // The device is now validated and can be appended to the available devices of the engine
2938        mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
2939                                          AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
2940        i++;
2941    }
2942    // make sure default device is reachable
2943    if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
2944        ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
2945    }
2946
2947    ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2948
2949    updateDevicesAndOutputs();
2950
2951#ifdef AUDIO_POLICY_TEST
2952    if (mPrimaryOutput != 0) {
2953        AudioParameter outputCmd = AudioParameter();
2954        outputCmd.addInt(String8("set_id"), 0);
2955        mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
2956
2957        mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2958        mTestSamplingRate = 44100;
2959        mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2960        mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
2961        mTestLatencyMs = 0;
2962        mCurOutput = 0;
2963        mDirectOutput = false;
2964        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2965            mTestOutputs[i] = 0;
2966        }
2967
2968        const size_t SIZE = 256;
2969        char buffer[SIZE];
2970        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2971        run(buffer, ANDROID_PRIORITY_AUDIO);
2972    }
2973#endif //AUDIO_POLICY_TEST
2974}
2975
2976AudioPolicyManager::~AudioPolicyManager()
2977{
2978#ifdef AUDIO_POLICY_TEST
2979    exit();
2980#endif //AUDIO_POLICY_TEST
2981   for (size_t i = 0; i < mOutputs.size(); i++) {
2982        mpClientInterface->closeOutput(mOutputs.keyAt(i));
2983   }
2984   for (size_t i = 0; i < mInputs.size(); i++) {
2985        mpClientInterface->closeInput(mInputs.keyAt(i));
2986   }
2987   mAvailableOutputDevices.clear();
2988   mAvailableInputDevices.clear();
2989   mOutputs.clear();
2990   mInputs.clear();
2991   mHwModules.clear();
2992}
2993
2994status_t AudioPolicyManager::initCheck()
2995{
2996    return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
2997}
2998
2999#ifdef AUDIO_POLICY_TEST
3000bool AudioPolicyManager::threadLoop()
3001{
3002    ALOGV("entering threadLoop()");
3003    while (!exitPending())
3004    {
3005        String8 command;
3006        int valueInt;
3007        String8 value;
3008
3009        Mutex::Autolock _l(mLock);
3010        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3011
3012        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3013        AudioParameter param = AudioParameter(command);
3014
3015        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3016            valueInt != 0) {
3017            ALOGV("Test command %s received", command.string());
3018            String8 target;
3019            if (param.get(String8("target"), target) != NO_ERROR) {
3020                target = "Manager";
3021            }
3022            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3023                param.remove(String8("test_cmd_policy_output"));
3024                mCurOutput = valueInt;
3025            }
3026            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3027                param.remove(String8("test_cmd_policy_direct"));
3028                if (value == "false") {
3029                    mDirectOutput = false;
3030                } else if (value == "true") {
3031                    mDirectOutput = true;
3032                }
3033            }
3034            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3035                param.remove(String8("test_cmd_policy_input"));
3036                mTestInput = valueInt;
3037            }
3038
3039            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3040                param.remove(String8("test_cmd_policy_format"));
3041                int format = AUDIO_FORMAT_INVALID;
3042                if (value == "PCM 16 bits") {
3043                    format = AUDIO_FORMAT_PCM_16_BIT;
3044                } else if (value == "PCM 8 bits") {
3045                    format = AUDIO_FORMAT_PCM_8_BIT;
3046                } else if (value == "Compressed MP3") {
3047                    format = AUDIO_FORMAT_MP3;
3048                }
3049                if (format != AUDIO_FORMAT_INVALID) {
3050                    if (target == "Manager") {
3051                        mTestFormat = format;
3052                    } else if (mTestOutputs[mCurOutput] != 0) {
3053                        AudioParameter outputParam = AudioParameter();
3054                        outputParam.addInt(String8("format"), format);
3055                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3056                    }
3057                }
3058            }
3059            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3060                param.remove(String8("test_cmd_policy_channels"));
3061                int channels = 0;
3062
3063                if (value == "Channels Stereo") {
3064                    channels =  AUDIO_CHANNEL_OUT_STEREO;
3065                } else if (value == "Channels Mono") {
3066                    channels =  AUDIO_CHANNEL_OUT_MONO;
3067                }
3068                if (channels != 0) {
3069                    if (target == "Manager") {
3070                        mTestChannels = channels;
3071                    } else if (mTestOutputs[mCurOutput] != 0) {
3072                        AudioParameter outputParam = AudioParameter();
3073                        outputParam.addInt(String8("channels"), channels);
3074                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3075                    }
3076                }
3077            }
3078            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3079                param.remove(String8("test_cmd_policy_sampleRate"));
3080                if (valueInt >= 0 && valueInt <= 96000) {
3081                    int samplingRate = valueInt;
3082                    if (target == "Manager") {
3083                        mTestSamplingRate = samplingRate;
3084                    } else if (mTestOutputs[mCurOutput] != 0) {
3085                        AudioParameter outputParam = AudioParameter();
3086                        outputParam.addInt(String8("sampling_rate"), samplingRate);
3087                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3088                    }
3089                }
3090            }
3091
3092            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3093                param.remove(String8("test_cmd_policy_reopen"));
3094
3095                mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
3096
3097                audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
3098
3099                removeOutput(mPrimaryOutput->mIoHandle);
3100                sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3101                                                                               mpClientInterface);
3102                outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
3103                audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3104                config.sample_rate = outputDesc->mSamplingRate;
3105                config.channel_mask = outputDesc->mChannelMask;
3106                config.format = outputDesc->mFormat;
3107                audio_io_handle_t handle;
3108                status_t status = mpClientInterface->openOutput(moduleHandle,
3109                                                                &handle,
3110                                                                &config,
3111                                                                &outputDesc->mDevice,
3112                                                                String8(""),
3113                                                                &outputDesc->mLatency,
3114                                                                outputDesc->mFlags);
3115                if (status != NO_ERROR) {
3116                    ALOGE("Failed to reopen hardware output stream, "
3117                        "samplingRate: %d, format %d, channels %d",
3118                        outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
3119                } else {
3120                    outputDesc->mSamplingRate = config.sample_rate;
3121                    outputDesc->mChannelMask = config.channel_mask;
3122                    outputDesc->mFormat = config.format;
3123                    mPrimaryOutput = outputDesc;
3124                    AudioParameter outputCmd = AudioParameter();
3125                    outputCmd.addInt(String8("set_id"), 0);
3126                    mpClientInterface->setParameters(handle, outputCmd.toString());
3127                    addOutput(handle, outputDesc);
3128                }
3129            }
3130
3131
3132            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3133        }
3134    }
3135    return false;
3136}
3137
3138void AudioPolicyManager::exit()
3139{
3140    {
3141        AutoMutex _l(mLock);
3142        requestExit();
3143        mWaitWorkCV.signal();
3144    }
3145    requestExitAndWait();
3146}
3147
3148int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
3149{
3150    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3151        if (output == mTestOutputs[i]) return i;
3152    }
3153    return 0;
3154}
3155#endif //AUDIO_POLICY_TEST
3156
3157// ---
3158
3159void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
3160{
3161    outputDesc->setIoHandle(output);
3162    mOutputs.add(output, outputDesc);
3163    nextAudioPortGeneration();
3164}
3165
3166void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3167{
3168    mOutputs.removeItem(output);
3169}
3170
3171void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
3172{
3173    inputDesc->setIoHandle(input);
3174    mInputs.add(input, inputDesc);
3175    nextAudioPortGeneration();
3176}
3177
3178void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
3179        const audio_devices_t device /*in*/,
3180        const String8 address /*in*/,
3181        SortedVector<audio_io_handle_t>& outputs /*out*/) {
3182    sp<DeviceDescriptor> devDesc =
3183        desc->mProfile->mSupportedDevices.getDevice(device, address);
3184    if (devDesc != 0) {
3185        ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3186              desc->mIoHandle, address.string());
3187        outputs.add(desc->mIoHandle);
3188    }
3189}
3190
3191status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
3192                                                   audio_policy_dev_state_t state,
3193                                                   SortedVector<audio_io_handle_t>& outputs,
3194                                                   const String8 address)
3195{
3196    audio_devices_t device = devDesc->type();
3197    sp<SwAudioOutputDescriptor> desc;
3198
3199    if (audio_device_is_digital(device)) {
3200        // erase all current sample rates, formats and channel masks
3201        devDesc->clearCapabilities();
3202    }
3203
3204    if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3205        // first list already open outputs that can be routed to this device
3206        for (size_t i = 0; i < mOutputs.size(); i++) {
3207            desc = mOutputs.valueAt(i);
3208            if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3209                if (!device_distinguishes_on_address(device)) {
3210                    ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3211                    outputs.add(mOutputs.keyAt(i));
3212                } else {
3213                    ALOGV("  checking address match due to device 0x%x", device);
3214                    findIoHandlesByAddress(desc, device, address, outputs);
3215                }
3216            }
3217        }
3218        // then look for output profiles that can be routed to this device
3219        SortedVector< sp<IOProfile> > profiles;
3220        for (size_t i = 0; i < mHwModules.size(); i++)
3221        {
3222            if (mHwModules[i]->mHandle == 0) {
3223                continue;
3224            }
3225            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3226            {
3227                sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3228                if (profile->mSupportedDevices.types() & device) {
3229                    if (!device_distinguishes_on_address(device) ||
3230                            address == profile->mSupportedDevices[0]->mAddress) {
3231                        profiles.add(profile);
3232                        ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3233                    }
3234                }
3235            }
3236        }
3237
3238        ALOGV("  found %d profiles, %d outputs", profiles.size(), outputs.size());
3239
3240        if (profiles.isEmpty() && outputs.isEmpty()) {
3241            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3242            return BAD_VALUE;
3243        }
3244
3245        // open outputs for matching profiles if needed. Direct outputs are also opened to
3246        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3247        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3248            sp<IOProfile> profile = profiles[profile_index];
3249
3250            // nothing to do if one output is already opened for this profile
3251            size_t j;
3252            for (j = 0; j < outputs.size(); j++) {
3253                desc = mOutputs.valueFor(outputs.itemAt(j));
3254                if (!desc->isDuplicated() && desc->mProfile == profile) {
3255                    // matching profile: save the sample rates, format and channel masks supported
3256                    // by the profile in our device descriptor
3257                    if (audio_device_is_digital(device)) {
3258                        devDesc->importAudioPort(profile);
3259                    }
3260                    break;
3261                }
3262            }
3263            if (j != outputs.size()) {
3264                continue;
3265            }
3266
3267            ALOGV("opening output for device %08x with params %s profile %p",
3268                                                      device, address.string(), profile.get());
3269            desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3270            desc->mDevice = device;
3271            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3272            config.sample_rate = desc->mSamplingRate;
3273            config.channel_mask = desc->mChannelMask;
3274            config.format = desc->mFormat;
3275            config.offload_info.sample_rate = desc->mSamplingRate;
3276            config.offload_info.channel_mask = desc->mChannelMask;
3277            config.offload_info.format = desc->mFormat;
3278            audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3279            status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
3280                                                            &output,
3281                                                            &config,
3282                                                            &desc->mDevice,
3283                                                            address,
3284                                                            &desc->mLatency,
3285                                                            desc->mFlags);
3286            if (status == NO_ERROR) {
3287                desc->mSamplingRate = config.sample_rate;
3288                desc->mChannelMask = config.channel_mask;
3289                desc->mFormat = config.format;
3290
3291                // Here is where the out_set_parameters() for card & device gets called
3292                if (!address.isEmpty()) {
3293                    char *param = audio_device_address_to_parameter(device, address);
3294                    mpClientInterface->setParameters(output, String8(param));
3295                    free(param);
3296                }
3297
3298                // Here is where we step through and resolve any "dynamic" fields
3299                String8 reply;
3300                char *value;
3301                if (profile->mSamplingRates[0] == 0) {
3302                    reply = mpClientInterface->getParameters(output,
3303                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3304                    ALOGV("checkOutputsForDevice() supported sampling rates %s",
3305                              reply.string());
3306                    value = strpbrk((char *)reply.string(), "=");
3307                    if (value != NULL) {
3308                        profile->loadSamplingRates(value + 1);
3309                    }
3310                }
3311                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3312                    reply = mpClientInterface->getParameters(output,
3313                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3314                    ALOGV("checkOutputsForDevice() supported formats %s",
3315                              reply.string());
3316                    value = strpbrk((char *)reply.string(), "=");
3317                    if (value != NULL) {
3318                        profile->loadFormats(value + 1);
3319                    }
3320                }
3321                if (profile->mChannelMasks[0] == 0) {
3322                    reply = mpClientInterface->getParameters(output,
3323                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3324                    ALOGV("checkOutputsForDevice() supported channel masks %s",
3325                              reply.string());
3326                    value = strpbrk((char *)reply.string(), "=");
3327                    if (value != NULL) {
3328                        profile->loadOutChannels(value + 1);
3329                    }
3330                }
3331                if (((profile->mSamplingRates[0] == 0) &&
3332                         (profile->mSamplingRates.size() < 2)) ||
3333                     ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3334                         (profile->mFormats.size() < 2)) ||
3335                     ((profile->mChannelMasks[0] == 0) &&
3336                         (profile->mChannelMasks.size() < 2))) {
3337                    ALOGW("checkOutputsForDevice() missing param");
3338                    mpClientInterface->closeOutput(output);
3339                    output = AUDIO_IO_HANDLE_NONE;
3340                } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3341                            profile->mChannelMasks[0] == 0) {
3342                    mpClientInterface->closeOutput(output);
3343                    config.sample_rate = profile->pickSamplingRate();
3344                    config.channel_mask = profile->pickChannelMask();
3345                    config.format = profile->pickFormat();
3346                    config.offload_info.sample_rate = config.sample_rate;
3347                    config.offload_info.channel_mask = config.channel_mask;
3348                    config.offload_info.format = config.format;
3349                    status = mpClientInterface->openOutput(profile->getModuleHandle(),
3350                                                           &output,
3351                                                           &config,
3352                                                           &desc->mDevice,
3353                                                           address,
3354                                                           &desc->mLatency,
3355                                                           desc->mFlags);
3356                    if (status == NO_ERROR) {
3357                        desc->mSamplingRate = config.sample_rate;
3358                        desc->mChannelMask = config.channel_mask;
3359                        desc->mFormat = config.format;
3360                    } else {
3361                        output = AUDIO_IO_HANDLE_NONE;
3362                    }
3363                }
3364
3365                if (output != AUDIO_IO_HANDLE_NONE) {
3366                    addOutput(output, desc);
3367                    if (device_distinguishes_on_address(device) && address != "0") {
3368                        sp<AudioPolicyMix> policyMix;
3369                        if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
3370                            ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3371                                  address.string());
3372                        }
3373                        policyMix->setOutput(desc);
3374                        desc->mPolicyMix = policyMix->getMix();
3375
3376                    } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3377                                    hasPrimaryOutput()) {
3378                        // no duplicated output for direct outputs and
3379                        // outputs used by dynamic policy mixes
3380                        audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
3381
3382                        // set initial stream volume for device
3383                        applyStreamVolumes(desc, device, 0, true);
3384
3385                        //TODO: configure audio effect output stage here
3386
3387                        // open a duplicating output thread for the new output and the primary output
3388                        duplicatedOutput =
3389                                mpClientInterface->openDuplicateOutput(output,
3390                                                                       mPrimaryOutput->mIoHandle);
3391                        if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
3392                            // add duplicated output descriptor
3393                            sp<SwAudioOutputDescriptor> dupOutputDesc =
3394                                    new SwAudioOutputDescriptor(NULL, mpClientInterface);
3395                            dupOutputDesc->mOutput1 = mPrimaryOutput;
3396                            dupOutputDesc->mOutput2 = desc;
3397                            dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3398                            dupOutputDesc->mFormat = desc->mFormat;
3399                            dupOutputDesc->mChannelMask = desc->mChannelMask;
3400                            dupOutputDesc->mLatency = desc->mLatency;
3401                            addOutput(duplicatedOutput, dupOutputDesc);
3402                            applyStreamVolumes(dupOutputDesc, device, 0, true);
3403                        } else {
3404                            ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3405                                    mPrimaryOutput->mIoHandle, output);
3406                            mpClientInterface->closeOutput(output);
3407                            removeOutput(output);
3408                            nextAudioPortGeneration();
3409                            output = AUDIO_IO_HANDLE_NONE;
3410                        }
3411                    }
3412                }
3413            } else {
3414                output = AUDIO_IO_HANDLE_NONE;
3415            }
3416            if (output == AUDIO_IO_HANDLE_NONE) {
3417                ALOGW("checkOutputsForDevice() could not open output for device %x", device);
3418                profiles.removeAt(profile_index);
3419                profile_index--;
3420            } else {
3421                outputs.add(output);
3422                // Load digital format info only for digital devices
3423                if (audio_device_is_digital(device)) {
3424                    devDesc->importAudioPort(profile);
3425                }
3426
3427                if (device_distinguishes_on_address(device)) {
3428                    ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3429                            device, address.string());
3430                    setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
3431                            NULL/*patch handle*/, address.string());
3432                }
3433                ALOGV("checkOutputsForDevice(): adding output %d", output);
3434            }
3435        }
3436
3437        if (profiles.isEmpty()) {
3438            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3439            return BAD_VALUE;
3440        }
3441    } else { // Disconnect
3442        // check if one opened output is not needed any more after disconnecting one device
3443        for (size_t i = 0; i < mOutputs.size(); i++) {
3444            desc = mOutputs.valueAt(i);
3445            if (!desc->isDuplicated()) {
3446                // exact match on device
3447                if (device_distinguishes_on_address(device) &&
3448                        (desc->supportedDevices() == device)) {
3449                    findIoHandlesByAddress(desc, device, address, outputs);
3450                } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
3451                    ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3452                            mOutputs.keyAt(i));
3453                    outputs.add(mOutputs.keyAt(i));
3454                }
3455            }
3456        }
3457        // Clear any profiles associated with the disconnected device.
3458        for (size_t i = 0; i < mHwModules.size(); i++)
3459        {
3460            if (mHwModules[i]->mHandle == 0) {
3461                continue;
3462            }
3463            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3464            {
3465                sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3466                if (profile->mSupportedDevices.types() & device) {
3467                    ALOGV("checkOutputsForDevice(): "
3468                            "clearing direct output profile %zu on module %zu", j, i);
3469                    if (profile->mSamplingRates[0] == 0) {
3470                        profile->mSamplingRates.clear();
3471                        profile->mSamplingRates.add(0);
3472                    }
3473                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3474                        profile->mFormats.clear();
3475                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3476                    }
3477                    if (profile->mChannelMasks[0] == 0) {
3478                        profile->mChannelMasks.clear();
3479                        profile->mChannelMasks.add(0);
3480                    }
3481                }
3482            }
3483        }
3484    }
3485    return NO_ERROR;
3486}
3487
3488status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
3489                                                  audio_policy_dev_state_t state,
3490                                                  SortedVector<audio_io_handle_t>& inputs,
3491                                                  const String8 address)
3492{
3493    audio_devices_t device = devDesc->type();
3494    sp<AudioInputDescriptor> desc;
3495
3496    if (audio_device_is_digital(device)) {
3497        // erase all current sample rates, formats and channel masks
3498        devDesc->clearCapabilities();
3499    }
3500
3501    if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3502        // first list already open inputs that can be routed to this device
3503        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3504            desc = mInputs.valueAt(input_index);
3505            if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3506                ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3507               inputs.add(mInputs.keyAt(input_index));
3508            }
3509        }
3510
3511        // then look for input profiles that can be routed to this device
3512        SortedVector< sp<IOProfile> > profiles;
3513        for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3514        {
3515            if (mHwModules[module_idx]->mHandle == 0) {
3516                continue;
3517            }
3518            for (size_t profile_index = 0;
3519                 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3520                 profile_index++)
3521            {
3522                sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3523
3524                if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3525                    if (!device_distinguishes_on_address(device) ||
3526                            address == profile->mSupportedDevices[0]->mAddress) {
3527                        profiles.add(profile);
3528                        ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3529                              profile_index, module_idx);
3530                    }
3531                }
3532            }
3533        }
3534
3535        if (profiles.isEmpty() && inputs.isEmpty()) {
3536            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3537            return BAD_VALUE;
3538        }
3539
3540        // open inputs for matching profiles if needed. Direct inputs are also opened to
3541        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3542        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3543
3544            sp<IOProfile> profile = profiles[profile_index];
3545            // nothing to do if one input is already opened for this profile
3546            size_t input_index;
3547            for (input_index = 0; input_index < mInputs.size(); input_index++) {
3548                desc = mInputs.valueAt(input_index);
3549                if (desc->mProfile == profile) {
3550                    if (audio_device_is_digital(device)) {
3551                        devDesc->importAudioPort(profile);
3552                    }
3553                    break;
3554                }
3555            }
3556            if (input_index != mInputs.size()) {
3557                continue;
3558            }
3559
3560            ALOGV("opening input for device 0x%X with params %s", device, address.string());
3561            desc = new AudioInputDescriptor(profile);
3562            desc->mDevice = device;
3563            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3564            config.sample_rate = desc->mSamplingRate;
3565            config.channel_mask = desc->mChannelMask;
3566            config.format = desc->mFormat;
3567            audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3568            status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
3569                                                           &input,
3570                                                           &config,
3571                                                           &desc->mDevice,
3572                                                           address,
3573                                                           AUDIO_SOURCE_MIC,
3574                                                           AUDIO_INPUT_FLAG_NONE /*FIXME*/);
3575
3576            if (status == NO_ERROR) {
3577                desc->mSamplingRate = config.sample_rate;
3578                desc->mChannelMask = config.channel_mask;
3579                desc->mFormat = config.format;
3580
3581                if (!address.isEmpty()) {
3582                    char *param = audio_device_address_to_parameter(device, address);
3583                    mpClientInterface->setParameters(input, String8(param));
3584                    free(param);
3585                }
3586
3587                // Here is where we step through and resolve any "dynamic" fields
3588                String8 reply;
3589                char *value;
3590                if (profile->mSamplingRates[0] == 0) {
3591                    reply = mpClientInterface->getParameters(input,
3592                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3593                    ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3594                              reply.string());
3595                    value = strpbrk((char *)reply.string(), "=");
3596                    if (value != NULL) {
3597                        profile->loadSamplingRates(value + 1);
3598                    }
3599                }
3600                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3601                    reply = mpClientInterface->getParameters(input,
3602                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3603                    ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3604                    value = strpbrk((char *)reply.string(), "=");
3605                    if (value != NULL) {
3606                        profile->loadFormats(value + 1);
3607                    }
3608                }
3609                if (profile->mChannelMasks[0] == 0) {
3610                    reply = mpClientInterface->getParameters(input,
3611                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3612                    ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3613                              reply.string());
3614                    value = strpbrk((char *)reply.string(), "=");
3615                    if (value != NULL) {
3616                        profile->loadInChannels(value + 1);
3617                    }
3618                }
3619                if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3620                     ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3621                     ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3622                    ALOGW("checkInputsForDevice() direct input missing param");
3623                    mpClientInterface->closeInput(input);
3624                    input = AUDIO_IO_HANDLE_NONE;
3625                }
3626
3627                if (input != 0) {
3628                    addInput(input, desc);
3629                }
3630            } // endif input != 0
3631
3632            if (input == AUDIO_IO_HANDLE_NONE) {
3633                ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
3634                profiles.removeAt(profile_index);
3635                profile_index--;
3636            } else {
3637                inputs.add(input);
3638                if (audio_device_is_digital(device)) {
3639                    devDesc->importAudioPort(profile);
3640                }
3641                ALOGV("checkInputsForDevice(): adding input %d", input);
3642            }
3643        } // end scan profiles
3644
3645        if (profiles.isEmpty()) {
3646            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3647            return BAD_VALUE;
3648        }
3649    } else {
3650        // Disconnect
3651        // check if one opened input is not needed any more after disconnecting one device
3652        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3653            desc = mInputs.valueAt(input_index);
3654            if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3655                    ~AUDIO_DEVICE_BIT_IN)) {
3656                ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3657                      mInputs.keyAt(input_index));
3658                inputs.add(mInputs.keyAt(input_index));
3659            }
3660        }
3661        // Clear any profiles associated with the disconnected device.
3662        for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3663            if (mHwModules[module_index]->mHandle == 0) {
3664                continue;
3665            }
3666            for (size_t profile_index = 0;
3667                 profile_index < mHwModules[module_index]->mInputProfiles.size();
3668                 profile_index++) {
3669                sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
3670                if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3671                    ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
3672                          profile_index, module_index);
3673                    if (profile->mSamplingRates[0] == 0) {
3674                        profile->mSamplingRates.clear();
3675                        profile->mSamplingRates.add(0);
3676                    }
3677                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3678                        profile->mFormats.clear();
3679                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3680                    }
3681                    if (profile->mChannelMasks[0] == 0) {
3682                        profile->mChannelMasks.clear();
3683                        profile->mChannelMasks.add(0);
3684                    }
3685                }
3686            }
3687        }
3688    } // end disconnect
3689
3690    return NO_ERROR;
3691}
3692
3693
3694void AudioPolicyManager::closeOutput(audio_io_handle_t output)
3695{
3696    ALOGV("closeOutput(%d)", output);
3697
3698    sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3699    if (outputDesc == NULL) {
3700        ALOGW("closeOutput() unknown output %d", output);
3701        return;
3702    }
3703    mPolicyMixes.closeOutput(outputDesc);
3704
3705    // look for duplicated outputs connected to the output being removed.
3706    for (size_t i = 0; i < mOutputs.size(); i++) {
3707        sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
3708        if (dupOutputDesc->isDuplicated() &&
3709                (dupOutputDesc->mOutput1 == outputDesc ||
3710                dupOutputDesc->mOutput2 == outputDesc)) {
3711            sp<AudioOutputDescriptor> outputDesc2;
3712            if (dupOutputDesc->mOutput1 == outputDesc) {
3713                outputDesc2 = dupOutputDesc->mOutput2;
3714            } else {
3715                outputDesc2 = dupOutputDesc->mOutput1;
3716            }
3717            // As all active tracks on duplicated output will be deleted,
3718            // and as they were also referenced on the other output, the reference
3719            // count for their stream type must be adjusted accordingly on
3720            // the other output.
3721            for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
3722                int refCount = dupOutputDesc->mRefCount[j];
3723                outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
3724            }
3725            audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3726            ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3727
3728            mpClientInterface->closeOutput(duplicatedOutput);
3729            removeOutput(duplicatedOutput);
3730        }
3731    }
3732
3733    nextAudioPortGeneration();
3734
3735    ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3736    if (index >= 0) {
3737        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3738        status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3739        mAudioPatches.removeItemsAt(index);
3740        mpClientInterface->onAudioPatchListUpdate();
3741    }
3742
3743    AudioParameter param;
3744    param.add(String8("closing"), String8("true"));
3745    mpClientInterface->setParameters(output, param.toString());
3746
3747    mpClientInterface->closeOutput(output);
3748    removeOutput(output);
3749    mPreviousOutputs = mOutputs;
3750}
3751
3752void AudioPolicyManager::closeInput(audio_io_handle_t input)
3753{
3754    ALOGV("closeInput(%d)", input);
3755
3756    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3757    if (inputDesc == NULL) {
3758        ALOGW("closeInput() unknown input %d", input);
3759        return;
3760    }
3761
3762    nextAudioPortGeneration();
3763
3764    ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3765    if (index >= 0) {
3766        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3767        status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3768        mAudioPatches.removeItemsAt(index);
3769        mpClientInterface->onAudioPatchListUpdate();
3770    }
3771
3772    mpClientInterface->closeInput(input);
3773    mInputs.removeItem(input);
3774}
3775
3776SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
3777                                                                audio_devices_t device,
3778                                                                SwAudioOutputCollection openOutputs)
3779{
3780    SortedVector<audio_io_handle_t> outputs;
3781
3782    ALOGVV("getOutputsForDevice() device %04x", device);
3783    for (size_t i = 0; i < openOutputs.size(); i++) {
3784        ALOGVV("output %d isDuplicated=%d device=%04x",
3785                i, openOutputs.valueAt(i)->isDuplicated(),
3786                openOutputs.valueAt(i)->supportedDevices());
3787        if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3788            ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3789            outputs.add(openOutputs.keyAt(i));
3790        }
3791    }
3792    return outputs;
3793}
3794
3795bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
3796                                      SortedVector<audio_io_handle_t>& outputs2)
3797{
3798    if (outputs1.size() != outputs2.size()) {
3799        return false;
3800    }
3801    for (size_t i = 0; i < outputs1.size(); i++) {
3802        if (outputs1[i] != outputs2[i]) {
3803            return false;
3804        }
3805    }
3806    return true;
3807}
3808
3809void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
3810{
3811    audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3812    audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3813    SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3814    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3815
3816    // also take into account external policy-related changes: add all outputs which are
3817    // associated with policies in the "before" and "after" output vectors
3818    ALOGVV("checkOutputForStrategy(): policy related outputs");
3819    for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
3820        const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
3821        if (desc != 0 && desc->mPolicyMix != NULL) {
3822            srcOutputs.add(desc->mIoHandle);
3823            ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
3824        }
3825    }
3826    for (size_t i = 0 ; i < mOutputs.size() ; i++) {
3827        const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3828        if (desc != 0 && desc->mPolicyMix != NULL) {
3829            dstOutputs.add(desc->mIoHandle);
3830            ALOGVV(" new outputs: adding %d", desc->mIoHandle);
3831        }
3832    }
3833
3834    if (!vectorsEqual(srcOutputs,dstOutputs)) {
3835        ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3836              strategy, srcOutputs[0], dstOutputs[0]);
3837        // mute strategy while moving tracks from one output to another
3838        for (size_t i = 0; i < srcOutputs.size(); i++) {
3839            sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
3840            if (isStrategyActive(desc, strategy)) {
3841                setStrategyMute(strategy, true, desc);
3842                setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
3843            }
3844        }
3845
3846        // Move effects associated to this strategy from previous output to new output
3847        if (strategy == STRATEGY_MEDIA) {
3848            audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3849            SortedVector<audio_io_handle_t> moved;
3850            for (size_t i = 0; i < mEffects.size(); i++) {
3851                sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3852                if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3853                        effectDesc->mIo != fxOutput) {
3854                    if (moved.indexOf(effectDesc->mIo) < 0) {
3855                        ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3856                              mEffects.keyAt(i), fxOutput);
3857                        mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
3858                                                       fxOutput);
3859                        moved.add(effectDesc->mIo);
3860                    }
3861                    effectDesc->mIo = fxOutput;
3862                }
3863            }
3864        }
3865        // Move tracks associated to this strategy from previous output to new output
3866        for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3867            if (i == AUDIO_STREAM_PATCH) {
3868                continue;
3869            }
3870            if (getStrategy((audio_stream_type_t)i) == strategy) {
3871                mpClientInterface->invalidateStream((audio_stream_type_t)i);
3872            }
3873        }
3874    }
3875}
3876
3877void AudioPolicyManager::checkOutputForAllStrategies()
3878{
3879    if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3880        checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3881    checkOutputForStrategy(STRATEGY_PHONE);
3882    if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3883        checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3884    checkOutputForStrategy(STRATEGY_SONIFICATION);
3885    checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3886    checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
3887    checkOutputForStrategy(STRATEGY_MEDIA);
3888    checkOutputForStrategy(STRATEGY_DTMF);
3889    checkOutputForStrategy(STRATEGY_REROUTING);
3890}
3891
3892void AudioPolicyManager::checkA2dpSuspend()
3893{
3894    audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
3895    if (a2dpOutput == 0) {
3896        mA2dpSuspended = false;
3897        return;
3898    }
3899
3900    bool isScoConnected =
3901            ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3902                    ~AUDIO_DEVICE_BIT_IN) != 0) ||
3903            ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
3904    // suspend A2DP output if:
3905    //      (NOT already suspended) &&
3906    //      ((SCO device is connected &&
3907    //       (forced usage for communication || for record is SCO))) ||
3908    //      (phone state is ringing || in call)
3909    //
3910    // restore A2DP output if:
3911    //      (Already suspended) &&
3912    //      ((SCO device is NOT connected ||
3913    //       (forced usage NOT for communication && NOT for record is SCO))) &&
3914    //      (phone state is NOT ringing && NOT in call)
3915    //
3916    if (mA2dpSuspended) {
3917        if ((!isScoConnected ||
3918             ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
3919              (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
3920             ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
3921              (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
3922
3923            mpClientInterface->restoreOutput(a2dpOutput);
3924            mA2dpSuspended = false;
3925        }
3926    } else {
3927        if ((isScoConnected &&
3928             ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
3929              (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
3930             ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
3931              (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
3932
3933            mpClientInterface->suspendOutput(a2dpOutput);
3934            mA2dpSuspended = true;
3935        }
3936    }
3937}
3938
3939audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
3940                                                       bool fromCache)
3941{
3942    audio_devices_t device = AUDIO_DEVICE_NONE;
3943
3944    ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3945    if (index >= 0) {
3946        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3947        if (patchDesc->mUid != mUidCached) {
3948            ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3949                  outputDesc->device(), outputDesc->mPatchHandle);
3950            return outputDesc->device();
3951        }
3952    }
3953
3954    // check the following by order of priority to request a routing change if necessary:
3955    // 1: the strategy enforced audible is active and enforced on the output:
3956    //      use device for strategy enforced audible
3957    // 2: we are in call or the strategy phone is active on the output:
3958    //      use device for strategy phone
3959    // 3: the strategy for enforced audible is active but not enforced on the output:
3960    //      use the device for strategy enforced audible
3961    // 4: the strategy accessibility is active on the output:
3962    //      use device for strategy accessibility
3963    // 5: the strategy sonification is active on the output:
3964    //      use device for strategy sonification
3965    // 6: the strategy "respectful" sonification is active on the output:
3966    //      use device for strategy "respectful" sonification
3967    // 7: the strategy media is active on the output:
3968    //      use device for strategy media
3969    // 8: the strategy DTMF is active on the output:
3970    //      use device for strategy DTMF
3971    // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
3972    //      use device for strategy t-t-s
3973    if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
3974        mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
3975        device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3976    } else if (isInCall() ||
3977                    isStrategyActive(outputDesc, STRATEGY_PHONE)) {
3978        device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3979    } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
3980        device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3981    } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
3982        device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
3983    } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
3984        device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3985    } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
3986        device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3987    } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
3988        device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3989    } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
3990        device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3991    } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
3992        device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
3993    } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
3994        device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
3995    }
3996
3997    ALOGV("getNewOutputDevice() selected device %x", device);
3998    return device;
3999}
4000
4001audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4002{
4003    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4004
4005    ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4006    if (index >= 0) {
4007        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4008        if (patchDesc->mUid != mUidCached) {
4009            ALOGV("getNewInputDevice() device %08x forced by patch %d",
4010                  inputDesc->mDevice, inputDesc->mPatchHandle);
4011            return inputDesc->mDevice;
4012        }
4013    }
4014
4015    audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
4016
4017    return device;
4018}
4019
4020uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
4021    return (uint32_t)getStrategy(stream);
4022}
4023
4024audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
4025    // By checking the range of stream before calling getStrategy, we avoid
4026    // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
4027    // and then return STRATEGY_MEDIA, but we want to return the empty set.
4028    if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
4029        return AUDIO_DEVICE_NONE;
4030    }
4031    audio_devices_t devices;
4032    routing_strategy strategy = getStrategy(stream);
4033    devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4034    SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4035    for (size_t i = 0; i < outputs.size(); i++) {
4036        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
4037        if (isStrategyActive(outputDesc, strategy)) {
4038            devices = outputDesc->device();
4039            break;
4040        }
4041    }
4042
4043    /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4044      and doesn't really need to.*/
4045    if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4046        devices |= AUDIO_DEVICE_OUT_SPEAKER;
4047        devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4048    }
4049
4050    return devices;
4051}
4052
4053routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4054{
4055    ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4056    return mEngine->getStrategyForStream(stream);
4057}
4058
4059uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4060    // flags to strategy mapping
4061    if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4062        return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4063    }
4064    if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4065        return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4066    }
4067    // usage to strategy mapping
4068    return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
4069}
4070
4071void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
4072    switch(stream) {
4073    case AUDIO_STREAM_MUSIC:
4074        checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4075        updateDevicesAndOutputs();
4076        break;
4077    default:
4078        break;
4079    }
4080}
4081
4082uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4083
4084    // skip beacon mute management if a dedicated TTS output is available
4085    if (mTtsOutputAvailable) {
4086        return 0;
4087    }
4088
4089    switch(event) {
4090    case STARTING_OUTPUT:
4091        mBeaconMuteRefCount++;
4092        break;
4093    case STOPPING_OUTPUT:
4094        if (mBeaconMuteRefCount > 0) {
4095            mBeaconMuteRefCount--;
4096        }
4097        break;
4098    case STARTING_BEACON:
4099        mBeaconPlayingRefCount++;
4100        break;
4101    case STOPPING_BEACON:
4102        if (mBeaconPlayingRefCount > 0) {
4103            mBeaconPlayingRefCount--;
4104        }
4105        break;
4106    }
4107
4108    if (mBeaconMuteRefCount > 0) {
4109        // any playback causes beacon to be muted
4110        return setBeaconMute(true);
4111    } else {
4112        // no other playback: unmute when beacon starts playing, mute when it stops
4113        return setBeaconMute(mBeaconPlayingRefCount == 0);
4114    }
4115}
4116
4117uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4118    ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4119            mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4120    // keep track of muted state to avoid repeating mute/unmute operations
4121    if (mBeaconMuted != mute) {
4122        // mute/unmute AUDIO_STREAM_TTS on all outputs
4123        ALOGV("\t muting %d", mute);
4124        uint32_t maxLatency = 0;
4125        for (size_t i = 0; i < mOutputs.size(); i++) {
4126            sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4127            setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4128                    desc,
4129                    0 /*delay*/, AUDIO_DEVICE_NONE);
4130            const uint32_t latency = desc->latency() * 2;
4131            if (latency > maxLatency) {
4132                maxLatency = latency;
4133            }
4134        }
4135        mBeaconMuted = mute;
4136        return maxLatency;
4137    }
4138    return 0;
4139}
4140
4141audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
4142                                                         bool fromCache)
4143{
4144    // Routing
4145    // see if we have an explicit route
4146    // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4147    // (getStrategy(stream)).
4148    // if the strategy from the stream type in the RouteMap is the same as the argument above,
4149    // and activity count is non-zero
4150    // the device = the device from the descriptor in the RouteMap, and exit.
4151    for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4152        sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4153        routing_strategy strat = getStrategy(route->mStreamType);
4154        // Special case for accessibility strategy which must follow any strategy it is
4155        // currently remapped to
4156        bool strategyMatch = (strat == strategy) ||
4157                             ((strategy == STRATEGY_ACCESSIBILITY) &&
4158                              ((mEngine->getStrategyForUsage(
4159                                      AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) == strat) ||
4160                               (strat == STRATEGY_MEDIA)));
4161        if (strategyMatch && route->isActive()) {
4162            return route->mDeviceDescriptor->type();
4163        }
4164    }
4165
4166    if (fromCache) {
4167        ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4168              strategy, mDeviceForStrategy[strategy]);
4169        return mDeviceForStrategy[strategy];
4170    }
4171    return mEngine->getDeviceForStrategy(strategy);
4172}
4173
4174void AudioPolicyManager::updateDevicesAndOutputs()
4175{
4176    for (int i = 0; i < NUM_STRATEGIES; i++) {
4177        mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4178    }
4179    mPreviousOutputs = mOutputs;
4180}
4181
4182uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
4183                                                       audio_devices_t prevDevice,
4184                                                       uint32_t delayMs)
4185{
4186    // mute/unmute strategies using an incompatible device combination
4187    // if muting, wait for the audio in pcm buffer to be drained before proceeding
4188    // if unmuting, unmute only after the specified delay
4189    if (outputDesc->isDuplicated()) {
4190        return 0;
4191    }
4192
4193    uint32_t muteWaitMs = 0;
4194    audio_devices_t device = outputDesc->device();
4195    bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
4196
4197    for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4198        audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4199        curDevice = curDevice & outputDesc->supportedDevices();
4200        bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4201        bool doMute = false;
4202
4203        if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4204            doMute = true;
4205            outputDesc->mStrategyMutedByDevice[i] = true;
4206        } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4207            doMute = true;
4208            outputDesc->mStrategyMutedByDevice[i] = false;
4209        }
4210        if (doMute) {
4211            for (size_t j = 0; j < mOutputs.size(); j++) {
4212                sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
4213                // skip output if it does not share any device with current output
4214                if ((desc->supportedDevices() & outputDesc->supportedDevices())
4215                        == AUDIO_DEVICE_NONE) {
4216                    continue;
4217                }
4218                ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4219                      mute ? "muting" : "unmuting", i, curDevice);
4220                setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
4221                if (isStrategyActive(desc, (routing_strategy)i)) {
4222                    if (mute) {
4223                        // FIXME: should not need to double latency if volume could be applied
4224                        // immediately by the audioflinger mixer. We must account for the delay
4225                        // between now and the next time the audioflinger thread for this output
4226                        // will process a buffer (which corresponds to one buffer size,
4227                        // usually 1/2 or 1/4 of the latency).
4228                        if (muteWaitMs < desc->latency() * 2) {
4229                            muteWaitMs = desc->latency() * 2;
4230                        }
4231                    }
4232                }
4233            }
4234        }
4235    }
4236
4237    // temporary mute output if device selection changes to avoid volume bursts due to
4238    // different per device volumes
4239    if (outputDesc->isActive() && (device != prevDevice)) {
4240        if (muteWaitMs < outputDesc->latency() * 2) {
4241            muteWaitMs = outputDesc->latency() * 2;
4242        }
4243        for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4244            if (isStrategyActive(outputDesc, (routing_strategy)i)) {
4245                setStrategyMute((routing_strategy)i, true, outputDesc);
4246                // do tempMute unmute after twice the mute wait time
4247                setStrategyMute((routing_strategy)i, false, outputDesc,
4248                                muteWaitMs *2, device);
4249            }
4250        }
4251    }
4252
4253    // wait for the PCM output buffers to empty before proceeding with the rest of the command
4254    if (muteWaitMs > delayMs) {
4255        muteWaitMs -= delayMs;
4256        usleep(muteWaitMs * 1000);
4257        return muteWaitMs;
4258    }
4259    return 0;
4260}
4261
4262uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4263                                             audio_devices_t device,
4264                                             bool force,
4265                                             int delayMs,
4266                                             audio_patch_handle_t *patchHandle,
4267                                             const char* address)
4268{
4269    ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
4270    AudioParameter param;
4271    uint32_t muteWaitMs;
4272
4273    if (outputDesc->isDuplicated()) {
4274        muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4275        muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
4276        return muteWaitMs;
4277    }
4278    // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4279    // output profile
4280    if ((device != AUDIO_DEVICE_NONE) &&
4281            ((device & outputDesc->supportedDevices()) == 0)) {
4282        return 0;
4283    }
4284
4285    // filter devices according to output selected
4286    device = (audio_devices_t)(device & outputDesc->supportedDevices());
4287
4288    audio_devices_t prevDevice = outputDesc->mDevice;
4289
4290    ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
4291
4292    if (device != AUDIO_DEVICE_NONE) {
4293        outputDesc->mDevice = device;
4294    }
4295    muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4296
4297    // Do not change the routing if:
4298    //      the requested device is AUDIO_DEVICE_NONE
4299    //      OR the requested device is the same as current device
4300    //  AND force is not specified
4301    //  AND the output is connected by a valid audio patch.
4302    // Doing this check here allows the caller to call setOutputDevice() without conditions
4303    if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4304        !force &&
4305        outputDesc->mPatchHandle != 0) {
4306        ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
4307        return muteWaitMs;
4308    }
4309
4310    ALOGV("setOutputDevice() changing device");
4311
4312    // do the routing
4313    if (device == AUDIO_DEVICE_NONE) {
4314        resetOutputDevice(outputDesc, delayMs, NULL);
4315    } else {
4316        DeviceVector deviceList = (address == NULL) ?
4317                mAvailableOutputDevices.getDevicesFromType(device)
4318                : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4319        if (!deviceList.isEmpty()) {
4320            struct audio_patch patch;
4321            outputDesc->toAudioPortConfig(&patch.sources[0]);
4322            patch.num_sources = 1;
4323            patch.num_sinks = 0;
4324            for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4325                deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
4326                patch.num_sinks++;
4327            }
4328            ssize_t index;
4329            if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4330                index = mAudioPatches.indexOfKey(*patchHandle);
4331            } else {
4332                index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4333            }
4334            sp< AudioPatch> patchDesc;
4335            audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4336            if (index >= 0) {
4337                patchDesc = mAudioPatches.valueAt(index);
4338                afPatchHandle = patchDesc->mAfPatchHandle;
4339            }
4340
4341            status_t status = mpClientInterface->createAudioPatch(&patch,
4342                                                                   &afPatchHandle,
4343                                                                   delayMs);
4344            ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4345                    "num_sources %d num_sinks %d",
4346                                       status, afPatchHandle, patch.num_sources, patch.num_sinks);
4347            if (status == NO_ERROR) {
4348                if (index < 0) {
4349                    patchDesc = new AudioPatch(&patch, mUidCached);
4350                    addAudioPatch(patchDesc->mHandle, patchDesc);
4351                } else {
4352                    patchDesc->mPatch = patch;
4353                }
4354                patchDesc->mAfPatchHandle = afPatchHandle;
4355                patchDesc->mUid = mUidCached;
4356                if (patchHandle) {
4357                    *patchHandle = patchDesc->mHandle;
4358                }
4359                outputDesc->mPatchHandle = patchDesc->mHandle;
4360                nextAudioPortGeneration();
4361                mpClientInterface->onAudioPatchListUpdate();
4362            }
4363        }
4364
4365        // inform all input as well
4366        for (size_t i = 0; i < mInputs.size(); i++) {
4367            const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
4368            if (!is_virtual_input_device(inputDescriptor->mDevice)) {
4369                AudioParameter inputCmd = AudioParameter();
4370                ALOGV("%s: inform input %d of device:%d", __func__,
4371                      inputDescriptor->mIoHandle, device);
4372                inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4373                mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4374                                                 inputCmd.toString(),
4375                                                 delayMs);
4376            }
4377        }
4378    }
4379
4380    // update stream volumes according to new device
4381    applyStreamVolumes(outputDesc, device, delayMs);
4382
4383    return muteWaitMs;
4384}
4385
4386status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4387                                               int delayMs,
4388                                               audio_patch_handle_t *patchHandle)
4389{
4390    ssize_t index;
4391    if (patchHandle) {
4392        index = mAudioPatches.indexOfKey(*patchHandle);
4393    } else {
4394        index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4395    }
4396    if (index < 0) {
4397        return INVALID_OPERATION;
4398    }
4399    sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4400    status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
4401    ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4402    outputDesc->mPatchHandle = 0;
4403    removeAudioPatch(patchDesc->mHandle);
4404    nextAudioPortGeneration();
4405    mpClientInterface->onAudioPatchListUpdate();
4406    return status;
4407}
4408
4409status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4410                                            audio_devices_t device,
4411                                            bool force,
4412                                            audio_patch_handle_t *patchHandle)
4413{
4414    status_t status = NO_ERROR;
4415
4416    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4417    if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4418        inputDesc->mDevice = device;
4419
4420        DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4421        if (!deviceList.isEmpty()) {
4422            struct audio_patch patch;
4423            inputDesc->toAudioPortConfig(&patch.sinks[0]);
4424            // AUDIO_SOURCE_HOTWORD is for internal use only:
4425            // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
4426            if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4427                    !inputDesc->mIsSoundTrigger) {
4428                patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4429            }
4430            patch.num_sinks = 1;
4431            //only one input device for now
4432            deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
4433            patch.num_sources = 1;
4434            ssize_t index;
4435            if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4436                index = mAudioPatches.indexOfKey(*patchHandle);
4437            } else {
4438                index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4439            }
4440            sp< AudioPatch> patchDesc;
4441            audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4442            if (index >= 0) {
4443                patchDesc = mAudioPatches.valueAt(index);
4444                afPatchHandle = patchDesc->mAfPatchHandle;
4445            }
4446
4447            status_t status = mpClientInterface->createAudioPatch(&patch,
4448                                                                  &afPatchHandle,
4449                                                                  0);
4450            ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
4451                                                                          status, afPatchHandle);
4452            if (status == NO_ERROR) {
4453                if (index < 0) {
4454                    patchDesc = new AudioPatch(&patch, mUidCached);
4455                    addAudioPatch(patchDesc->mHandle, patchDesc);
4456                } else {
4457                    patchDesc->mPatch = patch;
4458                }
4459                patchDesc->mAfPatchHandle = afPatchHandle;
4460                patchDesc->mUid = mUidCached;
4461                if (patchHandle) {
4462                    *patchHandle = patchDesc->mHandle;
4463                }
4464                inputDesc->mPatchHandle = patchDesc->mHandle;
4465                nextAudioPortGeneration();
4466                mpClientInterface->onAudioPatchListUpdate();
4467            }
4468        }
4469    }
4470    return status;
4471}
4472
4473status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4474                                              audio_patch_handle_t *patchHandle)
4475{
4476    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4477    ssize_t index;
4478    if (patchHandle) {
4479        index = mAudioPatches.indexOfKey(*patchHandle);
4480    } else {
4481        index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4482    }
4483    if (index < 0) {
4484        return INVALID_OPERATION;
4485    }
4486    sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4487    status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4488    ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4489    inputDesc->mPatchHandle = 0;
4490    removeAudioPatch(patchDesc->mHandle);
4491    nextAudioPortGeneration();
4492    mpClientInterface->onAudioPatchListUpdate();
4493    return status;
4494}
4495
4496sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
4497                                                  String8 address,
4498                                                  uint32_t& samplingRate,
4499                                                  audio_format_t& format,
4500                                                  audio_channel_mask_t& channelMask,
4501                                                  audio_input_flags_t flags)
4502{
4503    // Choose an input profile based on the requested capture parameters: select the first available
4504    // profile supporting all requested parameters.
4505    //
4506    // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4507    // the best matching profile, not the first one.
4508
4509    for (size_t i = 0; i < mHwModules.size(); i++)
4510    {
4511        if (mHwModules[i]->mHandle == 0) {
4512            continue;
4513        }
4514        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4515        {
4516            sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
4517            // profile->log();
4518            if (profile->isCompatibleProfile(device, address, samplingRate,
4519                                             &samplingRate /*updatedSamplingRate*/,
4520                                             format,
4521                                             &format /*updatedFormat*/,
4522                                             channelMask,
4523                                             &channelMask /*updatedChannelMask*/,
4524                                             (audio_output_flags_t) flags)) {
4525
4526                return profile;
4527            }
4528        }
4529    }
4530    return NULL;
4531}
4532
4533
4534audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
4535                                                                  AudioMix **policyMix)
4536{
4537    audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4538    audio_devices_t selectedDeviceFromMix =
4539           mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
4540
4541    if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4542        return selectedDeviceFromMix;
4543    }
4544    return getDeviceForInputSource(inputSource);
4545}
4546
4547audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4548{
4549    for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4550         sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
4551         if (inputSource == route->mSource && route->isActive()) {
4552             return route->mDeviceDescriptor->type();
4553         }
4554     }
4555
4556     return mEngine->getDeviceForInputSource(inputSource);
4557}
4558
4559float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
4560                                            int index,
4561                                            audio_devices_t device)
4562{
4563    float volumeDb = mEngine->volIndexToDb(Volume::getDeviceCategory(device), stream, index);
4564
4565    // if a headset is connected, apply the following rules to ring tones and notifications
4566    // to avoid sound level bursts in user's ears:
4567    // - always attenuate ring tones and notifications volume by 6dB
4568    // - if music is playing, always limit the volume to current music volume,
4569    // with a minimum threshold at -36dB so that notification is always perceived.
4570    const routing_strategy stream_strategy = getStrategy(stream);
4571    if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4572            AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4573            AUDIO_DEVICE_OUT_WIRED_HEADSET |
4574            AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4575        ((stream_strategy == STRATEGY_SONIFICATION)
4576                || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
4577                || (stream == AUDIO_STREAM_SYSTEM)
4578                || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
4579                    (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
4580            mStreams.canBeMuted(stream)) {
4581        volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
4582        // when the phone is ringing we must consider that music could have been paused just before
4583        // by the music application and behave as if music was active if the last music track was
4584        // just stopped
4585        if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
4586                mLimitRingtoneVolume) {
4587            audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
4588            float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
4589                                 mStreams.valueFor(AUDIO_STREAM_MUSIC).getVolumeIndex(musicDevice),
4590                               musicDevice);
4591            float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4592                    musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4593            if (volumeDb > minVolDB) {
4594                volumeDb = minVolDB;
4595                ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
4596            }
4597        }
4598    }
4599
4600    return volumeDb;
4601}
4602
4603status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
4604                                                   int index,
4605                                                   const sp<AudioOutputDescriptor>& outputDesc,
4606                                                   audio_devices_t device,
4607                                                   int delayMs,
4608                                                   bool force)
4609{
4610    // do not change actual stream volume if the stream is muted
4611    if (outputDesc->mMuteCount[stream] != 0) {
4612        ALOGVV("checkAndSetVolume() stream %d muted count %d",
4613              stream, outputDesc->mMuteCount[stream]);
4614        return NO_ERROR;
4615    }
4616    audio_policy_forced_cfg_t forceUseForComm =
4617            mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
4618    // do not change in call volume if bluetooth is connected and vice versa
4619    if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4620        (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
4621        ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
4622             stream, forceUseForComm);
4623        return INVALID_OPERATION;
4624    }
4625
4626    if (device == AUDIO_DEVICE_NONE) {
4627        device = outputDesc->device();
4628    }
4629
4630    float volumeDb = computeVolume(stream, index, device);
4631    if (outputDesc->isFixedVolume(device)) {
4632        volumeDb = 0.0f;
4633    }
4634
4635    outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
4636
4637    if (stream == AUDIO_STREAM_VOICE_CALL ||
4638        stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4639        float voiceVolume;
4640        // Force voice volume to max for bluetooth SCO as volume is managed by the headset
4641        if (stream == AUDIO_STREAM_VOICE_CALL) {
4642            voiceVolume = (float)index/(float)mStreams.valueFor(stream).getVolumeIndexMax();
4643        } else {
4644            voiceVolume = 1.0;
4645        }
4646
4647        if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
4648            mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4649            mLastVoiceVolume = voiceVolume;
4650        }
4651    }
4652
4653    return NO_ERROR;
4654}
4655
4656void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4657                                                audio_devices_t device,
4658                                                int delayMs,
4659                                                bool force)
4660{
4661    ALOGVV("applyStreamVolumes() for device %08x", device);
4662
4663    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4664        if (stream == AUDIO_STREAM_PATCH) {
4665            continue;
4666        }
4667        checkAndSetVolume((audio_stream_type_t)stream,
4668                          mStreams.valueFor((audio_stream_type_t)stream).getVolumeIndex(device),
4669                          outputDesc,
4670                          device,
4671                          delayMs,
4672                          force);
4673    }
4674}
4675
4676void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
4677                                             bool on,
4678                                             const sp<AudioOutputDescriptor>& outputDesc,
4679                                             int delayMs,
4680                                             audio_devices_t device)
4681{
4682    ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
4683           strategy, on, outputDesc->getId());
4684    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4685        if (stream == AUDIO_STREAM_PATCH) {
4686            continue;
4687        }
4688        if (getStrategy((audio_stream_type_t)stream) == strategy) {
4689            setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
4690        }
4691    }
4692}
4693
4694void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
4695                                           bool on,
4696                                           const sp<AudioOutputDescriptor>& outputDesc,
4697                                           int delayMs,
4698                                           audio_devices_t device)
4699{
4700    const StreamDescriptor& streamDesc = mStreams.valueFor(stream);
4701    if (device == AUDIO_DEVICE_NONE) {
4702        device = outputDesc->device();
4703    }
4704
4705    ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
4706          stream, on, outputDesc->mMuteCount[stream], device);
4707
4708    if (on) {
4709        if (outputDesc->mMuteCount[stream] == 0) {
4710            if (streamDesc.canBeMuted() &&
4711                    ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4712                     (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
4713                checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
4714            }
4715        }
4716        // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4717        outputDesc->mMuteCount[stream]++;
4718    } else {
4719        if (outputDesc->mMuteCount[stream] == 0) {
4720            ALOGV("setStreamMute() unmuting non muted stream!");
4721            return;
4722        }
4723        if (--outputDesc->mMuteCount[stream] == 0) {
4724            checkAndSetVolume(stream,
4725                              streamDesc.getVolumeIndex(device),
4726                              outputDesc,
4727                              device,
4728                              delayMs);
4729        }
4730    }
4731}
4732
4733void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
4734                                                      bool starting, bool stateChange)
4735{
4736    if(!hasPrimaryOutput()) {
4737        return;
4738    }
4739
4740    // if the stream pertains to sonification strategy and we are in call we must
4741    // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4742    // in the device used for phone strategy and play the tone if the selected device does not
4743    // interfere with the device used for phone strategy
4744    // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4745    // many times as there are active tracks on the output
4746    const routing_strategy stream_strategy = getStrategy(stream);
4747    if ((stream_strategy == STRATEGY_SONIFICATION) ||
4748            ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
4749        sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
4750        ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4751                stream, starting, outputDesc->mDevice, stateChange);
4752        if (outputDesc->mRefCount[stream]) {
4753            int muteCount = 1;
4754            if (stateChange) {
4755                muteCount = outputDesc->mRefCount[stream];
4756            }
4757            if (audio_is_low_visibility(stream)) {
4758                ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4759                for (int i = 0; i < muteCount; i++) {
4760                    setStreamMute(stream, starting, mPrimaryOutput);
4761                }
4762            } else {
4763                ALOGV("handleIncallSonification() high visibility");
4764                if (outputDesc->device() &
4765                        getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4766                    ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4767                    for (int i = 0; i < muteCount; i++) {
4768                        setStreamMute(stream, starting, mPrimaryOutput);
4769                    }
4770                }
4771                if (starting) {
4772                    mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4773                                                 AUDIO_STREAM_VOICE_CALL);
4774                } else {
4775                    mpClientInterface->stopTone();
4776                }
4777            }
4778        }
4779    }
4780}
4781
4782
4783
4784void AudioPolicyManager::defaultAudioPolicyConfig(void)
4785{
4786    sp<HwModule> module;
4787    sp<IOProfile> profile;
4788    sp<DeviceDescriptor> defaultInputDevice =
4789                    new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
4790    mAvailableOutputDevices.add(mDefaultOutputDevice);
4791    mAvailableInputDevices.add(defaultInputDevice);
4792
4793    module = new HwModule("primary");
4794
4795    profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE);
4796    profile->attach(module);
4797    profile->mSamplingRates.add(44100);
4798    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4799    profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
4800    profile->mSupportedDevices.add(mDefaultOutputDevice);
4801    profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4802    module->mOutputProfiles.add(profile);
4803
4804    profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK);
4805    profile->attach(module);
4806    profile->mSamplingRates.add(8000);
4807    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4808    profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
4809    profile->mSupportedDevices.add(defaultInputDevice);
4810    module->mInputProfiles.add(profile);
4811
4812    mHwModules.add(module);
4813}
4814
4815audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
4816{
4817    // flags to stream type mapping
4818    if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4819        return AUDIO_STREAM_ENFORCED_AUDIBLE;
4820    }
4821    if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
4822        return AUDIO_STREAM_BLUETOOTH_SCO;
4823    }
4824    if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4825        return AUDIO_STREAM_TTS;
4826    }
4827
4828    // usage to stream type mapping
4829    switch (attr->usage) {
4830    case AUDIO_USAGE_MEDIA:
4831    case AUDIO_USAGE_GAME:
4832    case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4833        return AUDIO_STREAM_MUSIC;
4834    case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4835        if (isStreamActive(AUDIO_STREAM_ALARM)) {
4836            return AUDIO_STREAM_ALARM;
4837        }
4838        if (isStreamActive(AUDIO_STREAM_RING)) {
4839            return AUDIO_STREAM_RING;
4840        }
4841        if (isInCall()) {
4842            return AUDIO_STREAM_VOICE_CALL;
4843        }
4844        return AUDIO_STREAM_ACCESSIBILITY;
4845    case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4846        return AUDIO_STREAM_SYSTEM;
4847    case AUDIO_USAGE_VOICE_COMMUNICATION:
4848        return AUDIO_STREAM_VOICE_CALL;
4849
4850    case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4851        return AUDIO_STREAM_DTMF;
4852
4853    case AUDIO_USAGE_ALARM:
4854        return AUDIO_STREAM_ALARM;
4855    case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4856        return AUDIO_STREAM_RING;
4857
4858    case AUDIO_USAGE_NOTIFICATION:
4859    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4860    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4861    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4862    case AUDIO_USAGE_NOTIFICATION_EVENT:
4863        return AUDIO_STREAM_NOTIFICATION;
4864
4865    case AUDIO_USAGE_UNKNOWN:
4866    default:
4867        return AUDIO_STREAM_MUSIC;
4868    }
4869}
4870
4871bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
4872{
4873    // has flags that map to a strategy?
4874    if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
4875        return true;
4876    }
4877
4878    // has known usage?
4879    switch (paa->usage) {
4880    case AUDIO_USAGE_UNKNOWN:
4881    case AUDIO_USAGE_MEDIA:
4882    case AUDIO_USAGE_VOICE_COMMUNICATION:
4883    case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4884    case AUDIO_USAGE_ALARM:
4885    case AUDIO_USAGE_NOTIFICATION:
4886    case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4887    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4888    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4889    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4890    case AUDIO_USAGE_NOTIFICATION_EVENT:
4891    case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4892    case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4893    case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4894    case AUDIO_USAGE_GAME:
4895    case AUDIO_USAGE_VIRTUAL_SOURCE:
4896        break;
4897    default:
4898        return false;
4899    }
4900    return true;
4901}
4902
4903bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
4904                                          routing_strategy strategy, uint32_t inPastMs,
4905                                          nsecs_t sysTime) const
4906{
4907    if ((sysTime == 0) && (inPastMs != 0)) {
4908        sysTime = systemTime();
4909    }
4910    for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4911        if (i == AUDIO_STREAM_PATCH) {
4912            continue;
4913        }
4914        if (((getStrategy((audio_stream_type_t)i) == strategy) ||
4915                (NUM_STRATEGIES == strategy)) &&
4916                outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
4917            return true;
4918        }
4919    }
4920    return false;
4921}
4922
4923audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
4924{
4925    return mEngine->getForceUse(usage);
4926}
4927
4928bool AudioPolicyManager::isInCall()
4929{
4930    return isStateInCall(mEngine->getPhoneState());
4931}
4932
4933bool AudioPolicyManager::isStateInCall(int state)
4934{
4935    return is_state_in_call(state);
4936}
4937
4938}; // namespace android
4939