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