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