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