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