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