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