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