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