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