blob: 133b3d065dd4a462cd080e21d249350293d812a2 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
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
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
Cheney Nie5985452019-02-24 01:39:15 +080036#define AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME \
37 "audio_policy_configuration_bluetooth_legacy_hal.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010038
Eric Laurent16c66dd2019-05-01 17:54:10 -070039#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070040#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080042#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080043#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110044#include <vector>
Glenn Kasten76a13442020-07-01 12:10:59 -070045#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070046#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070049#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070050#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganovedc0ae12020-04-14 14:47:01 -070052#include <system/audio_config.h>
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010054#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010056#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070057
Eric Laurent3b73df72014-03-11 09:06:29 -070058namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurentdc462862016-07-19 12:29:53 -070060//FIXME: workaround for truncated touch sounds
61// to be removed when the problem is handled by system UI
62#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070063
64// Largest difference in dB on earpiece in call between the voice volume and another
65// media / notification / system volume.
66constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
67
Mikhail Naganov15be9d22017-11-08 14:18:13 +110068// Compressed formats for MSD module, ordered from most preferred to least preferred.
69static const std::vector<audio_format_t> compressedFormatsOrder = {{
70 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
71 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
72// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
73static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
74 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
75 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
76 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
77
jiabin4562b3b2019-07-29 10:13:34 -070078template <typename T>
79bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
80{
81 if (left.size() != right.size()) {
82 return false;
83 }
84 for (size_t index = 0; index < right.size(); index++) {
85 if (left[index] != right[index]) {
86 return false;
87 }
88 }
89 return true;
90}
91
92template <typename T>
93bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
94{
95 return !(left == right);
96}
97
Eric Laurente552edb2014-03-10 17:42:56 -070098// ----------------------------------------------------------------------------
99// AudioPolicyInterface implementation
100// ----------------------------------------------------------------------------
101
Eric Laurente0720872014-03-11 09:30:41 -0700102status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800103 audio_policy_dev_state_t state,
104 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800105 const char *device_name,
106 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700107{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800108 status_t status = setDeviceConnectionStateInt(device, state, device_address,
109 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800110 nextAudioPortGeneration();
111 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800112}
113
François Gaffie11d30102018-11-02 16:09:09 +0100114void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
115 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200116{
jiabin6713a382019-09-12 16:29:15 -0700117 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200118 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovbb3b1602019-07-08 15:28:43 -0700119 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100120 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200121 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
122}
123
François Gaffie11d30102018-11-02 16:09:09 +0100124status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800125 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800126 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800127 const char *device_name,
128 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800129{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800130 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
131 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700132
133 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100134 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700135
François Gaffie11d30102018-11-02 16:09:09 +0100136 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800137 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100138 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganova30ec142020-03-24 09:32:34 -0700139 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
140}
Paul McLeane743a472015-01-28 11:07:31 -0800141
Mikhail Naganova30ec142020-03-24 09:32:34 -0700142status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
143 audio_policy_dev_state_t state)
144{
Eric Laurente552edb2014-03-10 17:42:56 -0700145 // handle output devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700146 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700147 SortedVector <audio_io_handle_t> outputs;
148
François Gaffie11d30102018-11-02 16:09:09 +0100149 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150
Eric Laurente552edb2014-03-10 17:42:56 -0700151 // save a copy of the opened output descriptors before any output is opened or closed
152 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
153 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700154 switch (state)
155 {
156 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800157 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700158 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100159 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700160 return INVALID_OPERATION;
161 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800162 ALOGV("%s() connecting device %s format %x",
Mikhail Naganova30ec142020-03-24 09:32:34 -0700163 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700164
Eric Laurente552edb2014-03-10 17:42:56 -0700165 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200166 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700167 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700168 }
169
François Gaffie44481e72016-04-20 07:49:57 +0200170 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
171 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100172 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200173
François Gaffie11d30102018-11-02 16:09:09 +0100174 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
175 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200176
Francois Gaffie716e1432019-01-14 16:58:59 +0100177 mHwModules.cleanUpForDevice(device);
178
François Gaffie11d30102018-11-02 16:09:09 +0100179 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700180 return INVALID_OPERATION;
181 }
François Gaffie2110e042015-03-24 08:41:51 +0100182
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700183 // outputs should never be empty here
184 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
185 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800187
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100192 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700193 return INVALID_OPERATION;
194 }
195
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700197
Paul McLeane743a472015-01-28 11:07:31 -0800198 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100199 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100202 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100204 mOutputs.clearSessionRoutesForDevice(device);
205
François Gaffie11d30102018-11-02 16:09:09 +0100206 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100207
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800208 // Reset active device codec
209 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
210
Eric Laurente552edb2014-03-10 17:42:56 -0700211 } break;
212
213 default:
François Gaffie11d30102018-11-02 16:09:09 +0100214 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700215 return BAD_VALUE;
216 }
217
Eric Laurent736a1022019-03-27 18:28:46 -0700218 // Propagate device availability to Engine
219 setEngineDeviceConnectionState(device, state);
220
Eric Laurentae970022019-01-29 14:25:04 -0800221 // No need to evaluate playback routing when connecting a remote submix
222 // output device used by a dynamic policy of type recorder as no
223 // playback use case is affected.
224 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganova30ec142020-03-24 09:32:34 -0700225 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800226 for (audio_io_handle_t output : outputs) {
227 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800228 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
229 if (policyMix != nullptr
230 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganova30ec142020-03-24 09:32:34 -0700231 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800232 doCheckForDeviceAndOutputChanges = false;
233 break;
234 }
235 }
236 }
237
238 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700239 // outputs must be closed after checkOutputForAllStrategies() is executed
240 if (!outputs.isEmpty()) {
241 for (audio_io_handle_t output : outputs) {
242 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100243 // close unused outputs after device disconnection or direct outputs that have
244 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700245 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
246 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800247 (desc->mDirectOpenCount == 0))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700248 closeOutput(output);
249 }
Eric Laurente552edb2014-03-10 17:42:56 -0700250 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700251 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
252 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700253 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700254 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800255 };
256
257 if (doCheckForDeviceAndOutputChanges) {
258 checkForDeviceAndOutputChanges(checkCloseOutputs);
259 } else {
260 checkCloseOutputs();
261 }
Eric Laurente552edb2014-03-10 17:42:56 -0700262
Eric Laurent87ffa392015-05-22 10:32:38 -0700263 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100264 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
265 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700266 }
François Gaffie11d30102018-11-02 16:09:09 +0100267 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700268 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
270 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100271 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700272 // do not force device change on duplicated output because if device is 0, it will
273 // also force a device 0 for the two outputs it is duplicated to which may override
274 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100275 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100276 && !desc->isDuplicated()
Mikhail Naganova30ec142020-03-24 09:32:34 -0700277 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700278 // always force when disconnecting (a non-duplicated device)
279 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100280 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700281 }
Eric Laurente552edb2014-03-10 17:42:56 -0700282 }
283
Eric Laurentd60560a2015-04-10 11:31:20 -0700284 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100285 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700286 }
287
Eric Laurent72aa32f2014-05-30 18:51:48 -0700288 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700289 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } // end if is output device
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // handle input devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700293 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100294 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 switch (state)
296 {
297 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700298 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100300 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700301 return INVALID_OPERATION;
302 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700303
304 if (mAvailableInputDevices.add(device) < 0) {
305 return NO_MEMORY;
306 }
307
François Gaffie44481e72016-04-20 07:49:57 +0200308 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
309 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100310 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200311
Eric Laurent0dd51852019-04-19 18:18:58 -0700312 if (checkInputsForDevice(device, state) != NO_ERROR) {
313 mAvailableInputDevices.remove(device);
314
François Gaffie11d30102018-11-02 16:09:09 +0100315 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100316
317 mHwModules.cleanUpForDevice(device);
318
Eric Laurentd4692962014-05-05 18:13:44 -0700319 return INVALID_OPERATION;
320 }
321
Eric Laurentd4692962014-05-05 18:13:44 -0700322 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700323
324 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700330
François Gaffie11d30102018-11-02 16:09:09 +0100331 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700332
333 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100334 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700335
François Gaffie11d30102018-11-02 16:09:09 +0100336 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700337
338 checkInputsForDevice(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700339 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700340
341 default:
François Gaffie11d30102018-11-02 16:09:09 +0100342 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700343 return BAD_VALUE;
344 }
345
Eric Laurent736a1022019-03-27 18:28:46 -0700346 // Propagate device availability to Engine
347 setEngineDeviceConnectionState(device, state);
348
Eric Laurent0dd51852019-04-19 18:18:58 -0700349 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700350 // As the input device list can impact the output device selection, update
351 // getDeviceForStrategy() cache
352 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700353
Eric Laurent87ffa392015-05-22 10:32:38 -0700354 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100355 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
356 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700357 }
358
Eric Laurentd60560a2015-04-10 11:31:20 -0700359 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100360 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700361 }
362
Eric Laurentb52c1522014-05-20 11:27:36 -0700363 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700364 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700365 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700366
François Gaffie11d30102018-11-02 16:09:09 +0100367 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700368 return BAD_VALUE;
369}
370
Eric Laurent736a1022019-03-27 18:28:46 -0700371void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
372 audio_policy_dev_state_t state) {
373
374 // the Engine does not have to know about remote submix devices used by dynamic audio policies
375 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
376 return;
377 }
378 mEngine->setDeviceConnectionState(device, state);
379}
380
381
Eric Laurente0720872014-03-11 09:30:41 -0700382audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100383 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700384{
Eric Laurent634b7142016-04-20 13:48:02 -0700385 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800386 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
387 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700388 (strlen(device_address) != 0)/*matchAddress*/);
389
390 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100391 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700392 device, device_address);
393 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
394 }
François Gaffie53615e22015-03-19 09:24:12 +0100395
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 DeviceVector *deviceVector;
397
Eric Laurente552edb2014-03-10 17:42:56 -0700398 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700399 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700400 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 deviceVector = &mAvailableInputDevices;
402 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700404 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700405 }
Eric Laurent634b7142016-04-20 13:48:02 -0700406
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800407 return (deviceVector->getDevice(
408 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700409 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800410}
411
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800412status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
413 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800414 const char *device_name,
415 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800416{
417 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700418 String8 reply;
419 AudioParameter param;
420 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800421
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800422 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
423 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800424
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800425 // connect/disconnect only 1 device at a time
426 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
427
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800428 // Check if the device is currently connected
jiabin12dc6b02019-10-01 09:38:30 -0700429 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800430 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 // Nothing to do: device is not connected
432 return NO_ERROR;
433 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800434 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800435
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700436 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800437 // configure codecs.
438 // Handle two specific cases by sending a set parameter to
439 // configure A2DP codecs. No need to toggle device state.
440 // Case 1: A2DP active device switches from primary to primary
441 // module
442 // Case 2: A2DP device config changes on primary module.
jiabin12dc6b02019-10-01 09:38:30 -0700443 if (audio_is_a2dp_out_device(device)) {
444 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800445 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
446 if (availablePrimaryOutputDevices().contains(devDesc) &&
447 (module != 0 && module->getHandle() == primaryHandle)) {
448 reply = mpClientInterface->getParameters(
449 AUDIO_IO_HANDLE_NONE,
450 String8(AudioParameter::keyReconfigA2dpSupported));
451 AudioParameter repliedParameters(reply);
452 repliedParameters.getInt(
453 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
454 if (isReconfigA2dpSupported) {
455 const String8 key(AudioParameter::keyReconfigA2dp);
456 param.add(key, String8("true"));
457 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
458 devDesc->setEncodedFormat(encodedFormat);
459 return NO_ERROR;
460 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700461 }
462 }
463
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800464 // Toggle the device state: UNAVAILABLE -> AVAILABLE
465 // This will force reading again the device configuration
466 status = setDeviceConnectionState(device,
467 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 device_address, device_name,
469 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800470 if (status != NO_ERROR) {
471 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
472 status);
473 return status;
474 }
475
476 status = setDeviceConnectionState(device,
477 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800478 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800479 if (status != NO_ERROR) {
480 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
481 status);
482 return status;
483 }
484
485 return NO_ERROR;
486}
487
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800488status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
489 std::vector<audio_format_t> *formats)
490{
491 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800492 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800493 std::unordered_set<audio_format_t> formatSet;
494 sp<HwModule> primaryModule =
495 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Lata5b023eb2019-07-03 11:20:36 -0700496 if (primaryModule == nullptr) {
497 ALOGE("%s() unable to get primary module", __func__);
498 return NO_INIT;
499 }
jiabin12dc6b02019-10-01 09:38:30 -0700500 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
501 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800502 for (const auto& device : declaredDevices) {
503 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800504 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800505 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800506 return status;
507}
508
François Gaffie11d30102018-11-02 16:09:09 +0100509uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700510{
511 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100512 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700513 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700514
jiabin12dc6b02019-10-01 09:38:30 -0700515 if(!hasPrimaryOutput() ||
516 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700517 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700518 }
François Gaffie11d30102018-11-02 16:09:09 +0100519 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
520
Francois Gaffie716e1432019-01-14 16:58:59 +0100521 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100522 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100523 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100524
525 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100526 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700527
528 // release existing RX patch if any
529 if (mCallRxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100530 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700531 mCallRxPatch.clear();
532 }
533 // release TX patch if any
534 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100535 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700536 mCallTxPatch.clear();
537 }
538
François Gaffie9eb18552018-11-05 10:33:26 +0100539 auto telephonyRxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700540 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100541 auto telephonyTxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700542 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100543 // retrieve Rx Source and Tx Sink device descriptors
544 sp<DeviceDescriptor> rxSourceDevice =
545 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
546 String8(),
547 AUDIO_FORMAT_DEFAULT);
548 sp<DeviceDescriptor> txSinkDevice =
549 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
550 String8(),
551 AUDIO_FORMAT_DEFAULT);
552
553 // RX and TX Telephony device are declared by Primary Audio HAL
554 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
555 (telephonyRxModule->getHalVersionMajor() >= 3)) {
556 if (rxSourceDevice == 0 || txSinkDevice == 0) {
557 // RX / TX Telephony device(s) is(are) not currently available
558 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
559 return muteWaitMs;
560 }
François Gaffiead447b72019-11-18 15:50:22 +0100561 // createAudioPatchInternal now supports both HW / SW bridging
562 createRxPatch = true;
563 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100564 } else {
565 // If the RX device is on the primary HW module, then use legacy routing method for
566 // voice calls via setOutputDevice() on primary output.
567 // Otherwise, create two audio patches for TX and RX path.
568 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
569 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700570 // If the TX device is also on the primary HW module, setOutputDevice() will take care
571 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100572 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
573 (txSinkDevice != 0);
574 }
575 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
576 // Otherwise, create two audio patches for TX and RX path.
577 if (!createRxPatch) {
578 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700579 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100580 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800581
582 // If the TX device is on the primary HW module but RX device is
583 // on other HW module, SinkMetaData of telephony input should handle it
584 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700585 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700586 if (createTxPatch) { // create TX path audio patch
François Gaffiead447b72019-11-18 15:50:22 +0100587 // terminate active capture if on the same HW module as the call TX source device
588 // FIXME: would be better to refine to only inputs whose profile connects to the
589 // call TX device but this information is not in the audio patch and logic here must be
590 // symmetric to the one in startInput()
591 for (const auto& activeDesc : mInputs.getActiveInputs()) {
592 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
593 closeActiveClients(activeDesc);
594 }
595 }
François Gaffie9eb18552018-11-05 10:33:26 +0100596 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800597 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700598
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800599 return muteWaitMs;
600}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700601
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800602sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100603 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700604 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605
François Gaffie11d30102018-11-02 16:09:09 +0100606 if (device == nullptr) {
607 return nullptr;
608 }
François Gaffiead447b72019-11-18 15:50:22 +0100609
610 // @TODO: still ignoring the address, or not dealing platform with mutliple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800611 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100612 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800613 addSource(mAvailableInputDevices.getDevice(
614 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800615 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100616 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800617 addSink(mAvailableOutputDevices.getDevice(
618 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800619 }
620
François Gaffiead447b72019-11-18 15:50:22 +0100621 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
622 status_t status =
623 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
624 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
625 if (status != NO_ERROR || index < 0) {
626 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
627 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800628 }
François Gaffiead447b72019-11-18 15:50:22 +0100629 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800630}
631
Mikhail Naganov100f0122018-11-29 11:22:16 -0800632bool AudioPolicyManager::isDeviceOfModule(
633 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
634 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
635 if (module != 0) {
636 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
637 .indexOf(devDesc) != NAME_NOT_FOUND
638 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
639 .indexOf(devDesc) != NAME_NOT_FOUND;
640 }
641 return false;
642}
643
Eric Laurente0720872014-03-11 09:30:41 -0700644void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700645{
646 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100647 // store previous phone state for management of sonification strategy below
648 int oldState = mEngine->getPhoneState();
649
650 if (mEngine->setPhoneState(state) != NO_ERROR) {
651 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700652 return;
653 }
François Gaffie2110e042015-03-24 08:41:51 +0100654 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700655 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700656 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700657 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800658 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700659 }
660
François Gaffie2110e042015-03-24 08:41:51 +0100661 /**
662 * Switching to or from incall state or switching between telephony and VoIP lead to force
663 * routing command.
664 */
665 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
666 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700667
668 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700669 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700670
Eric Laurente552edb2014-03-10 17:42:56 -0700671 int delayMs = 0;
672 if (isStateInCall(state)) {
673 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100674 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
675 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700676 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700677 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700678 // mute media and sonification strategies and delay device switch by the largest
679 // latency of any output where either strategy is active.
680 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100681 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
682 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
683 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700684 (delayMs < (int)desc->latency()*2)) {
685 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700686 }
François Gaffiec005e562018-11-06 15:04:49 +0100687 setStrategyMute(musicStrategy, true, desc);
688 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
689 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
690 nullptr, true /*fromCache*/).types());
691 setStrategyMute(sonificationStrategy, true, desc);
692 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
693 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
694 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700695 }
696 }
697
Eric Laurent87ffa392015-05-22 10:32:38 -0700698 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100699 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700700 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100701 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700702 // force routing command to audio hardware when ending call
703 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100704 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
705 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707
Eric Laurent87ffa392015-05-22 10:32:38 -0700708 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100709 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700710 } else if (oldState == AUDIO_MODE_IN_CALL) {
711 if (mCallRxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100712 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700713 mCallRxPatch.clear();
714 }
715 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100716 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700717 mCallTxPatch.clear();
718 }
François Gaffie11d30102018-11-02 16:09:09 +0100719 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700720 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100721 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700722 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700724
725 // reevaluate routing on all outputs in case tracks have been started during the call
726 for (size_t i = 0; i < mOutputs.size(); i++) {
727 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100728 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700729 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100730 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700731 }
732 }
733
Eric Laurente552edb2014-03-10 17:42:56 -0700734 if (isStateInCall(state)) {
735 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700736 // force reevaluating accessibility routing when call starts
737 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700738 }
739
740 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100741 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
742 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700743}
744
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700745audio_mode_t AudioPolicyManager::getPhoneState() {
746 return mEngine->getPhoneState();
747}
748
Eric Laurente0720872014-03-11 09:30:41 -0700749void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100750 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700751{
François Gaffie2110e042015-03-24 08:41:51 +0100752 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700753 if (config == mEngine->getForceUse(usage)) {
754 return;
755 }
Eric Laurente552edb2014-03-10 17:42:56 -0700756
François Gaffie2110e042015-03-24 08:41:51 +0100757 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
758 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
759 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700760 }
François Gaffie2110e042015-03-24 08:41:51 +0100761 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
762 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
763 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700764
765 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700766 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800767
Eric Laurent22fcda22019-05-17 16:28:47 -0700768 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
769 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
770 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
771 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
772 }
773
Eric Laurentdc462862016-07-19 12:29:53 -0700774 //FIXME: workaround for truncated touch sounds
775 // to be removed when the problem is handled by system UI
776 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700777 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
778 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
779 }
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -0700780
781 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -0700782
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800783 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100784 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700785 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100786 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800787 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700788 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800789 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700790 }
Eric Laurente552edb2014-03-10 17:42:56 -0700791 }
Eric Laurente552edb2014-03-10 17:42:56 -0700792}
793
Eric Laurente0720872014-03-11 09:30:41 -0700794void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700795{
796 ALOGV("setSystemProperty() property %s, value %s", property, value);
797}
798
Michael Chana94fbb22018-04-24 14:31:19 +1000799// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
800// search to profiles for direct outputs.
801sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100802 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000803 uint32_t samplingRate,
804 audio_format_t format,
805 audio_channel_mask_t channelMask,
806 audio_output_flags_t flags,
807 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700808{
Michael Chana94fbb22018-04-24 14:31:19 +1000809 if (directOnly) {
810 // only retain flags that will drive the direct output profile selection
811 // if explicitly requested
812 static const uint32_t kRelevantFlags =
813 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lata97a47182019-07-03 11:15:33 -0700814 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000815 flags =
816 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
817 }
Eric Laurent861a6282015-05-18 15:40:16 -0700818
819 sp<IOProfile> profile;
820
Mikhail Naganovd4120142017-12-06 15:49:22 -0800821 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800822 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100823 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700824 samplingRate, NULL /*updatedSamplingRate*/,
825 format, NULL /*updatedFormat*/,
826 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700827 flags)) {
828 continue;
829 }
830 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100831 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700832 continue;
833 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800834 // reject profiles if connected device does not support codec
jiabin12dc6b02019-10-01 09:38:30 -0700835 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800836 continue;
837 }
Michael Chana94fbb22018-04-24 14:31:19 +1000838 if (!directOnly) return curProfile;
839 // when searching for direct outputs, if several profiles are compatible, give priority
840 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100841 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700842 continue;
843 }
844 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100845 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700846 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700847 }
Eric Laurente552edb2014-03-10 17:42:56 -0700848 }
849 }
Eric Laurent861a6282015-05-18 15:40:16 -0700850 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700851}
852
Eric Laurentf4e63452017-11-06 19:31:46 +0000853audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700854{
François Gaffiec005e562018-11-06 15:04:49 +0100855 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800856
857 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
858 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
859 // format, flags, etc. This may result in some discrepancy for functions that utilize
860 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
861 // and AudioSystem::getOutputSamplingRate().
862
François Gaffie11d30102018-11-02 16:09:09 +0100863 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700864 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700865
François Gaffie11d30102018-11-02 16:09:09 +0100866 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
867 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000868 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700869}
870
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700871status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
872 const audio_attributes_t *srcAttr,
873 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700874{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700875 if (srcAttr != NULL) {
876 if (!isValidAttributes(srcAttr)) {
877 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
878 __func__,
879 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
880 srcAttr->tags);
881 return BAD_VALUE;
882 }
883 *dstAttr = *srcAttr;
884 } else {
885 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
886 ALOGE("%s: invalid stream type", __func__);
887 return BAD_VALUE;
888 }
François Gaffiec005e562018-11-06 15:04:49 +0100889 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700890 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700891
892 // Only honor audibility enforced when required. The client will be
893 // forced to reconnect if the forced usage changes.
894 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
895 dstAttr->flags &= ~AUDIO_FLAG_AUDIBILITY_ENFORCED;
896 }
897
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700898 return NO_ERROR;
899}
900
Kevin Rocard153f92d2018-12-18 18:33:28 -0800901status_t AudioPolicyManager::getOutputForAttrInt(
902 audio_attributes_t *resultAttr,
903 audio_io_handle_t *output,
904 audio_session_t session,
905 const audio_attributes_t *attr,
906 audio_stream_type_t *stream,
907 uid_t uid,
908 const audio_config_t *config,
909 audio_output_flags_t *flags,
910 audio_port_handle_t *selectedDeviceId,
911 bool *isRequestedDeviceForExclusiveUse,
912 std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700913{
François Gaffiec005e562018-11-06 15:04:49 +0100914 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100915 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100916 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100917 const sp<DeviceDescriptor> requestedDevice =
918 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
919
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700920 status_t status = getAudioAttributes(resultAttr, attr, *stream);
921 if (status != NO_ERROR) {
922 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700923 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700924 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
925 resultAttr->flags |= it->second;
926 }
François Gaffiec005e562018-11-06 15:04:49 +0100927 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700928
François Gaffiec005e562018-11-06 15:04:49 +0100929 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
930 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700931
Kevin Rocard153f92d2018-12-18 18:33:28 -0800932 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
933 // otherwise, fallback to the dynamic policies, if none match, query the engine.
934 // Secondary outputs are always found by dynamic policies as the engine do not support them
935 sp<SwAudioOutputDescriptor> policyDesc;
Kevin Rocard94114a22019-04-01 19:38:23 -0700936 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, policyDesc, secondaryDescs);
937 if (status != OK) {
938 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800939 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700940
Kevin Rocard153f92d2018-12-18 18:33:28 -0800941 // Explicit routing is higher priority then any dynamic policy primary output
942 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && policyDesc != nullptr;
943
944 // FIXME: in case of RENDER policy, the output capabilities should be checked
945 if ((usePrimaryOutputFromPolicyMixes || !secondaryDescs->empty())
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800946 && !audio_is_linear_pcm(config->format)) {
947 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800948 return BAD_VALUE;
949 }
950 if (usePrimaryOutputFromPolicyMixes) {
951 *output = policyDesc->mIoHandle;
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800952 sp<AudioPolicyMix> mix = policyDesc->mPolicyMix.promote();
François Gaffiec005e562018-11-06 15:04:49 +0100953 sp<DeviceDescriptor> deviceDesc =
954 mAvailableOutputDevices.getDevice(mix->mDeviceType,
955 mix->mDeviceAddress,
956 AUDIO_FORMAT_DEFAULT);
957 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
958 ALOGV("getOutputForAttr() returns output %d", *output);
959 return NO_ERROR;
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700960 }
François Gaffiec005e562018-11-06 15:04:49 +0100961 // Virtual sources must always be dynamicaly or explicitly routed
962 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
963 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
964 return BAD_VALUE;
965 }
966 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
967 // in order to let the choice of the order to future vendor engine
968 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700969
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700970 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200971 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700972 }
973
Nadav Barb2f18162018-07-18 13:01:53 +0300974 // Set incall music only if device was explicitly set, and fallback to the device which is
975 // chosen by the engine if not.
976 // FIXME: provide a more generic approach which is not device specific and move this back
977 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200978 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin12dc6b02019-10-01 09:38:30 -0700979 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +0100980 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300981 audio_is_linear_pcm(config->format) &&
982 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100983 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300984 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +0100985 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +0300986 }
987 }
988
François Gaffiec005e562018-11-06 15:04:49 +0100989 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
990 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
991 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700992
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100993 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100994 if (!msdDevices.isEmpty()) {
995 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +0100996 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
997 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
998 ALOGV("%s() Using MSD devices %s instead of devices %s",
999 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1000 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001001 } else {
1002 *output = AUDIO_IO_HANDLE_NONE;
1003 }
1004 }
1005 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001006 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001007 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001008 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001009 if (*output == AUDIO_IO_HANDLE_NONE) {
1010 return INVALID_OPERATION;
1011 }
Paul McLeanaa981192015-03-21 09:55:15 -07001012
François Gaffiec005e562018-11-06 15:04:49 +01001013 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001014
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001015 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1016
1017 return NO_ERROR;
1018}
1019
1020status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1021 audio_io_handle_t *output,
1022 audio_session_t session,
1023 audio_stream_type_t *stream,
1024 uid_t uid,
1025 const audio_config_t *config,
1026 audio_output_flags_t *flags,
1027 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001028 audio_port_handle_t *portId,
1029 std::vector<audio_io_handle_t> *secondaryOutputs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001030{
1031 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1032 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1033 return INVALID_OPERATION;
1034 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001035 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001036 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001037 bool isRequestedDeviceForExclusiveUse = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001038 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputDescs;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001039 const sp<DeviceDescriptor> requestedDevice =
1040 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1041
1042 // Prevent from storing invalid requested device id in clients
1043 const audio_port_handle_t sanitizedRequestedPortId =
1044 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1045 *selectedDeviceId = sanitizedRequestedPortId;
1046
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001047 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001048 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
1049 &secondaryOutputDescs);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001050 if (status != NO_ERROR) {
1051 return status;
1052 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001053 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1054 for (auto& secondaryDesc : secondaryOutputDescs) {
1055 secondaryOutputs->push_back(secondaryDesc->mIoHandle);
1056 weakSecondaryOutputDescs.push_back(secondaryDesc);
1057 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001058
Eric Laurent8fc147b2018-07-22 19:13:55 -07001059 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001060 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001061 .format = config->format,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001062 };
jiabindff2a4f2019-09-10 14:29:54 -07001063 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001064
Eric Laurent8fc147b2018-07-22 19:13:55 -07001065 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001066 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001067 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001068 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001069 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001070 *flags, isRequestedDeviceForExclusiveUse,
1071 std::move(weakSecondaryOutputDescs));
Eric Laurent8fc147b2018-07-22 19:13:55 -07001072 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001073 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001074
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001075 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1076 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001077
Eric Laurente83b55d2014-11-14 10:06:21 -08001078 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001079}
1080
François Gaffie11d30102018-11-02 16:09:09 +01001081audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1082 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001083 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001084 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001085 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001086 audio_output_flags_t *flags,
1087 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001088{
Andy Hungc88b0642018-04-27 15:42:35 -07001089 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001090 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001091
jiabine375d412019-02-26 12:54:53 -08001092 // Discard haptic channel mask when forcing muting haptic channels.
1093 audio_channel_mask_t channelMask = forceMutingHaptic
1094 ? (config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL) : config->channel_mask;
1095
Eric Laurente552edb2014-03-10 17:42:56 -07001096 // open a direct output if required by specified parameters
1097 //force direct flag if offload flag is set: offloading implies a direct output stream
1098 // and all common behaviors are driven by checking only the direct flag
1099 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001100 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1101 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001102 }
Nadav Bar766fb022018-01-07 12:18:03 +02001103 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1104 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001105 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001106 // only allow deep buffering for music stream type
1107 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001108 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001109 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001110 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001111 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1112 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001113 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001114 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001115 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001116 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001117 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001118 audio_is_linear_pcm(config->format) &&
1119 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001120 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001121 AUDIO_OUTPUT_FLAG_DIRECT);
1122 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001123 }
Eric Laurente552edb2014-03-10 17:42:56 -07001124
Nadav Bar766fb022018-01-07 12:18:03 +02001125
Eric Laurentb732cf52014-09-24 19:08:21 -07001126 sp<IOProfile> profile;
1127
1128 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001129 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001130 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001131 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
jiabine375d412019-02-26 12:54:53 -08001132 audio_channel_count_from_out_mask(channelMask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001133 goto non_direct_output;
1134 }
1135
Andy Hung2ddee192015-12-18 17:34:44 -08001136 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1137 // This prevents creating an offloaded track and tearing it down immediately after start
1138 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001139 // FIXME: We should check the audio session here but we do not have it in this context.
1140 // This may prevent offloading in rare situations where effects are left active by apps
1141 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001142
Nadav Bar766fb022018-01-07 12:18:03 +02001143 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001144 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001145 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001146 config->sample_rate,
1147 config->format,
jiabine375d412019-02-26 12:54:53 -08001148 channelMask,
Michael Chana94fbb22018-04-24 14:31:19 +10001149 (audio_output_flags_t)*flags,
1150 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001151 }
1152
Eric Laurent1c333e22014-05-20 10:48:17 -07001153 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001154 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1155 for (size_t i = 0; i < mOutputs.size(); i++) {
1156 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1157 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1158 // reuse direct output if currently open by the same client
1159 // and configured with same parameters
jiabineaf09f02019-08-19 15:08:30 -07001160 if ((config->sample_rate == desc->getSamplingRate()) &&
1161 (config->format == desc->getFormat()) &&
1162 (channelMask == desc->getChannelMask()) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001163 (session == desc->mDirectClientSession)) {
1164 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001165 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001166 mOutputs.keyAt(i), session);
1167 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001168 }
1169 }
1170 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001171
1172 if (!profile->canOpenNewIo()) {
1173 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001174 }
Eric Laurent861a6282015-05-18 15:40:16 -07001175
Eric Laurent3974e3b2017-12-07 17:58:43 -08001176 sp<SwAudioOutputDescriptor> outputDesc =
1177 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001178
François Gaffie11d30102018-11-02 16:09:09 +01001179 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001180
Dean Wheatley3023b382018-08-09 07:42:40 +10001181 // MSD patch may be using the only output stream that can service this request. Release
1182 // MSD patch to prioritize this request over any active output on MSD.
1183 AudioPatchCollection msdPatches = getMsdPatches();
1184 for (size_t i = 0; i < msdPatches.size(); i++) {
1185 const auto& patch = msdPatches[i];
1186 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1187 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1188 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
jiabin12dc6b02019-10-01 09:38:30 -07001189 devices.containsDeviceWithType(sink->ext.device.type) &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001190 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1191 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
François Gaffiead447b72019-11-18 15:50:22 +01001192 releaseAudioPatch(patch->getHandle(), mUidCached);
Dean Wheatley3023b382018-08-09 07:42:40 +10001193 break;
1194 }
1195 }
1196 }
1197
François Gaffie11d30102018-11-02 16:09:09 +01001198 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001199
1200 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001201 if (status != NO_ERROR ||
jiabineaf09f02019-08-19 15:08:30 -07001202 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1203 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1204 (channelMask != 0 && channelMask != outputDesc->getChannelMask())) {
François Gaffie11d30102018-11-02 16:09:09 +01001205 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1206 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
jiabineaf09f02019-08-19 15:08:30 -07001207 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1208 channelMask, outputDesc->getChannelMask());
Eric Laurentcf2c0212014-07-25 16:20:43 -07001209 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001210 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001211 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001212 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001213 if (audio_is_linear_pcm(config->format) &&
1214 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001215 goto non_direct_output;
1216 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001217 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001218 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001219 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001220 outputDesc->mDirectClientSession = session;
1221
Eric Laurente552edb2014-03-10 17:42:56 -07001222 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001223 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001224 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001225 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001226 return output;
1227 }
1228
Eric Laurentb732cf52014-09-24 19:08:21 -07001229non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001230
1231 // A request for HW A/V sync cannot fallback to a mixed output because time
1232 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001233 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001234 return AUDIO_IO_HANDLE_NONE;
1235 }
1236
Eric Laurente552edb2014-03-10 17:42:56 -07001237 // ignoring channel mask due to downmix capability in mixer
1238
1239 // open a non direct output
1240
1241 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001242 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001243 // get which output is suitable for the specified stream. The actual
1244 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001245 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001246
Eric Laurent8838a382014-09-08 16:44:28 -07001247 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001248 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabine375d412019-02-26 12:54:53 -08001249 output = selectOutput(outputs, *flags, config->format, channelMask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001250 }
François Gaffie11d30102018-11-02 16:09:09 +01001251 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001252 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001253 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001254
Eric Laurente552edb2014-03-10 17:42:56 -07001255 return output;
1256}
1257
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001258sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001259 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1260 mAvailableInputDevices);
1261 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1262}
1263
1264DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1265 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1266 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267}
1268
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001269const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1270 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001271 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1272 if (msdModule != 0) {
1273 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1274 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1275 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1276 const struct audio_port_config *source = &patch->mPatch.sources[j];
1277 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1278 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffiead447b72019-11-18 15:50:22 +01001279 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001280 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001281 }
1282 }
1283 }
1284 return msdPatches;
1285}
1286
François Gaffie11d30102018-11-02 16:09:09 +01001287status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001288 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1289{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001290 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001291 if (msdModule == nullptr) {
1292 ALOGE("%s() unable to get MSD module", __func__);
1293 return NO_INIT;
1294 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001295 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001296 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001297 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001298 return NO_INIT;
1299 }
1300 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1301 if (inputProfiles.isEmpty()) {
1302 ALOGE("%s() no input profiles for MSD module", __func__);
1303 return NO_INIT;
1304 }
1305 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1306 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001307 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001308 return NO_INIT;
1309 }
1310 AudioProfileVector msdProfiles;
1311 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1312 for (const auto &inProfile : inputProfiles) {
1313 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabinb9733bc2019-09-10 14:27:34 -07001314 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001315 }
1316 }
1317 AudioProfileVector deviceProfiles;
1318 for (const auto &outProfile : outputProfiles) {
1319 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabinb9733bc2019-09-10 14:27:34 -07001320 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001321 }
1322 }
1323 struct audio_config_base bestSinkConfig;
jiabinb9733bc2019-09-10 14:27:34 -07001324 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001325 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabinb9733bc2019-09-10 14:27:34 -07001326 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001327 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001328 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1329 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001330 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001331 }
1332 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1333 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1334 sinkConfig->format = bestSinkConfig.format;
1335 // For encoded streams force direct flag to prevent downstream mixing.
1336 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1337 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001338 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1339 // For formats compatible with IEC61937 encapsulation, assume that
1340 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1341 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1342 // raw and IEC61937 framed streams.
1343 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1344 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1345 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1347 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1348 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1349 sourceConfig->format = bestSinkConfig.format;
1350 // Copy input stream directly without any processing (e.g. resampling).
1351 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1352 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1353 if (hwAvSync) {
1354 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1355 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1356 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1357 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1358 }
1359 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1360 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1361 sinkConfig->config_mask |= config_mask;
1362 sourceConfig->config_mask |= config_mask;
1363 return NO_ERROR;
1364}
1365
François Gaffie11d30102018-11-02 16:09:09 +01001366PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001367{
1368 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001369 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001370 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1371 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1372 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1373 // For now, we just forcefully try with HwAvSync first.
1374 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1375 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1376 getBestMsdAudioProfileFor(
1377 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1378 if (res == NO_ERROR) {
1379 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1380 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1381 }
1382 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1383 " supporting PCM format conversion.", __func__);
1384 return patchBuilder;
1385}
1386
François Gaffie11d30102018-11-02 16:09:09 +01001387status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1388 sp<DeviceDescriptor> device = outputDevice;
1389 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001390 // Use media strategy for unspecified output device. This should only
1391 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1392 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001393 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1394 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001395 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1396 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001397 }
François Gaffie11d30102018-11-02 16:09:09 +01001398 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1399 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001400 const struct audio_patch* patch = patchBuilder.patch();
1401 const AudioPatchCollection msdPatches = getMsdPatches();
1402 if (!msdPatches.isEmpty()) {
1403 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1404 "The current MSD prototype only supports one output patch");
1405 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1406 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1407 return NO_ERROR;
1408 }
François Gaffiead447b72019-11-18 15:50:22 +01001409 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001410 }
1411 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1412 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1413 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1414 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001415 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1416 device->toString().c_str(), patch->sources[0].format,
1417 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 return status;
1419}
1420
Eric Laurente0720872014-03-11 09:30:41 -07001421audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001422 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001423 audio_format_t format,
1424 audio_channel_mask_t channelMask,
1425 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001426{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001427 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1428 "%s called with format %#x", __func__, format);
1429
1430 // Flags disqualifying an output: the match must happen before calling selectOutput()
1431 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1432 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1433
1434 // Flags expressing a functional request: must be honored in priority over
1435 // other criteria
1436 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1437 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1438 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1439 // Flags expressing a performance request: have lower priority than serving
1440 // requested sampling rate or channel mask
1441 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1442 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1443 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1444
1445 const audio_output_flags_t functionalFlags =
1446 (audio_output_flags_t)(flags & kFunctionalFlags);
1447 const audio_output_flags_t performanceFlags =
1448 (audio_output_flags_t)(flags & kPerformanceFlags);
1449
1450 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1451
Eric Laurente552edb2014-03-10 17:42:56 -07001452 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001453 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001454 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001455 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001456 // 2: the output with the highest number of requested functional flags
1457 // 3: the output supporting the exact channel mask
1458 // 4: the output with a higher channel count than requested
1459 // 5: the output with a higher sampling rate than requested
1460 // 6: the output with the highest number of requested performance flags
1461 // 7: the output with the bit depth the closest to the requested one
1462 // 8: the primary output
1463 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001464
Eric Laurent16c66dd2019-05-01 17:54:10 -07001465 // matching criteria values in priority order for best matching output so far
1466 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001467
Eric Laurent16c66dd2019-05-01 17:54:10 -07001468 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1469 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1470 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001471
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001472 for (audio_io_handle_t output : outputs) {
1473 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001474 // matching criteria values in priority order for current output
1475 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001476
Eric Laurent16c66dd2019-05-01 17:54:10 -07001477 if (outputDesc->isDuplicated()) {
1478 continue;
1479 }
1480 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1481 continue;
1482 }
Eric Laurent8838a382014-09-08 16:44:28 -07001483
Eric Laurent16c66dd2019-05-01 17:54:10 -07001484 // If haptic channel is specified, use the haptic output if present.
1485 // When using haptic output, same audio format and sample rate are required.
1486 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabineaf09f02019-08-19 15:08:30 -07001487 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001488 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1489 continue;
1490 }
1491 if (outputHapticChannelCount >= hapticChannelCount
jiabineaf09f02019-08-19 15:08:30 -07001492 && format == outputDesc->getFormat()
1493 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001494 currentMatchCriteria[0] = outputHapticChannelCount;
1495 }
1496
1497 // functional flags match
1498 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1499
1500 // channel mask and channel count match
jiabineaf09f02019-08-19 15:08:30 -07001501 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1502 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001503 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1504 channelCount <= outputChannelCount) {
1505 if ((audio_channel_mask_get_representation(channelMask) ==
jiabineaf09f02019-08-19 15:08:30 -07001506 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1507 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001508 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001509 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001510 currentMatchCriteria[3] = outputChannelCount;
1511 }
1512
1513 // sampling rate match
1514 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabineaf09f02019-08-19 15:08:30 -07001515 samplingRate <= outputDesc->getSamplingRate()) {
1516 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001517 }
1518
1519 // performance flags match
1520 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1521
1522 // format match
1523 if (format != AUDIO_FORMAT_INVALID) {
1524 currentMatchCriteria[6] =
jiabindff2a4f2019-09-10 14:29:54 -07001525 PolicyAudioPort::kFormatDistanceMax -
1526 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001527 }
1528
1529 // primary output match
1530 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1531
1532 // compare match criteria by priority then value
1533 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1534 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1535 bestMatchCriteria = currentMatchCriteria;
1536 bestOutput = output;
1537
1538 std::stringstream result;
1539 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1540 std::ostream_iterator<int>(result, " "));
1541 ALOGV("%s new bestOutput %d criteria %s",
1542 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001543 }
1544 }
1545
Eric Laurent16c66dd2019-05-01 17:54:10 -07001546 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001547}
1548
Eric Laurent8fc147b2018-07-22 19:13:55 -07001549status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001550{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001551 ALOGV("%s portId %d", __FUNCTION__, portId);
1552
1553 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1554 if (outputDesc == 0) {
1555 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001556 return BAD_VALUE;
1557 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001558 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001559
Eric Laurent8fc147b2018-07-22 19:13:55 -07001560 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001561 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001562
Eric Laurent733ce942017-12-07 12:18:25 -08001563 status_t status = outputDesc->start();
1564 if (status != NO_ERROR) {
1565 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001566 }
1567
Eric Laurent97ac8712018-07-27 18:59:02 -07001568 uint32_t delayMs;
1569 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001570
1571 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001572 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001573 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001574 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001575 if (delayMs != 0) {
1576 usleep(delayMs * 1000);
1577 }
1578
1579 return status;
1580}
1581
Eric Laurent97ac8712018-07-27 18:59:02 -07001582status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1583 const sp<TrackClientDescriptor>& client,
1584 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001585{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001586 // cannot start playback of STREAM_TTS if any other output is being used
1587 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001588
1589 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001590 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001591 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001592 auto clientStrategy = client->strategy();
1593 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001594 if (stream == AUDIO_STREAM_TTS) {
1595 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001596 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001597 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001598 return INVALID_OPERATION;
1599 } else {
1600 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1601 }
1602 } else {
1603 // some playback other than beacon starts
1604 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1605 }
1606
Eric Laurent77305a62016-07-25 16:39:22 -07001607 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001608 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001609 bool force = !outputDesc->isActive() &&
1610 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001611
François Gaffie11d30102018-11-02 16:09:09 +01001612 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001613 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001614 const char *address = NULL;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001615 if (policyMix != NULL) {
François Gaffie11d30102018-11-02 16:09:09 +01001616 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001617 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001618 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001619 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001620 } else {
1621 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001622 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001623 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1624 AUDIO_FORMAT_DEFAULT);
1625 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1626 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001627 }
1628
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001629 // requiresMuteCheck is false when we can bypass mute strategy.
1630 // It covers a common case when there is no materially active audio
1631 // and muting would result in unnecessary delay and dropped audio.
1632 const uint32_t outputLatencyMs = outputDesc->latency();
1633 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1634
Eric Laurente552edb2014-03-10 17:42:56 -07001635 // increment usage count for this stream on the requested output:
1636 // NOTE that the usage count is the same for duplicated output and hardware output which is
1637 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001638 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001639
1640 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001641 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1642 client->isPreferredDeviceForExclusiveUse()) {
1643 // Preferred device may be exclusive, use only if no other active clients on this output
1644 devices = DeviceVector(
1645 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1646 } else {
1647 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1648 }
François Gaffie11d30102018-11-02 16:09:09 +01001649 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001650 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001651 }
1652 }
Eric Laurente552edb2014-03-10 17:42:56 -07001653
François Gaffiec005e562018-11-06 15:04:49 +01001654 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001655 selectOutputForMusicEffects();
1656 }
1657
François Gaffie1c878552018-11-22 16:53:21 +01001658 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001659 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001660 if (devices.isEmpty()) {
1661 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001662 }
François Gaffiec005e562018-11-06 15:04:49 +01001663 bool shouldWait =
1664 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1665 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1666 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001667 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001668 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001669 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001670 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001671 // An output has a shared device if
1672 // - managed by the same hw module
1673 // - supports the currently selected device
1674 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001675 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001676
Eric Laurent77305a62016-07-25 16:39:22 -07001677 // force a device change if any other output is:
1678 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001679 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001680 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001681 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001682 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001683 // change the device currently selected by the other output.
1684 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001685 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001686 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001687 force = true;
1688 }
1689 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001690 // a notification so that audio focus effect can propagate, or that a mute/unmute
1691 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001692 const uint32_t latencyMs = desc->latency();
1693 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1694
1695 if (shouldWait && isActive && (waitMs < latencyMs)) {
1696 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001697 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001698
1699 // Require mute check if another output is on a shared device
1700 // and currently active to have proper drain and avoid pops.
1701 // Note restoring AudioTracks onto this output needs to invoke
1702 // a volume ramp if there is no mute.
1703 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001704 }
1705 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001706
1707 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001708 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001709
Eric Laurente552edb2014-03-10 17:42:56 -07001710 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001711 auto &curves = getVolumeCurves(client->attributes());
1712 checkAndSetVolume(curves, client->volumeSource(),
1713 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001714 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001715 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001716
1717 // update the outputs if starting an output with a stream that can affect notification
1718 // routing
1719 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001720
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001721 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001722 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001723 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1724 }
Eric Laurentdc462862016-07-19 12:29:53 -07001725
1726 if (waitMs > muteWaitMs) {
1727 *delayMs = waitMs - muteWaitMs;
1728 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001729
1730 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1731 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1732 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1733 // change occurs after the MixerThread starts and causes a stream volume
1734 // glitch.
1735 //
1736 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001737 }
Eric Laurentdc462862016-07-19 12:29:53 -07001738
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001739 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin12dc6b02019-10-01 09:38:30 -07001740 mEngine->getForceUse(
1741 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001742 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001743 }
1744
Eric Laurent97ac8712018-07-27 18:59:02 -07001745 // Automatically enable the remote submix input when output is started on a re routing mix
1746 // of type MIX_TYPE_RECORDERS
jiabin12dc6b02019-10-01 09:38:30 -07001747 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1748 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001749 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1750 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1751 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001752 "remote-submix",
1753 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001754 }
1755
Eric Laurente552edb2014-03-10 17:42:56 -07001756 return NO_ERROR;
1757}
1758
Eric Laurent8fc147b2018-07-22 19:13:55 -07001759status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001760{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001761 ALOGV("%s portId %d", __FUNCTION__, portId);
1762
1763 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1764 if (outputDesc == 0) {
1765 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001766 return BAD_VALUE;
1767 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001768 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001769
Eric Laurent97ac8712018-07-27 18:59:02 -07001770 ALOGV("stopOutput() output %d, stream %d, session %d",
1771 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001772
Eric Laurent97ac8712018-07-27 18:59:02 -07001773 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001774
Eric Laurent733ce942017-12-07 12:18:25 -08001775 if (status == NO_ERROR ) {
1776 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001777 }
1778 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001779}
1780
Eric Laurent97ac8712018-07-27 18:59:02 -07001781status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1782 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001783{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001784 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001785 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001786 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001787
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001788 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1789
François Gaffie1c878552018-11-22 16:53:21 +01001790 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1791 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001792 // Automatically disable the remote submix input when output is stopped on a
1793 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001794 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin12dc6b02019-10-01 09:38:30 -07001795 if (isSingleDeviceType(
1796 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001797 policyMix != NULL &&
1798 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001799 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1800 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001801 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001802 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001803 }
1804 }
1805 bool forceDeviceUpdate = false;
1806 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001807 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001808 forceDeviceUpdate = true;
1809 }
1810
Eric Laurente552edb2014-03-10 17:42:56 -07001811 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001812 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001813
Eric Laurente552edb2014-03-10 17:42:56 -07001814 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001815 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001816 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001817 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001818 // delay the device switch by twice the latency because stopOutput() is executed when
1819 // the track stop() command is received and at that time the audio track buffer can
1820 // still contain data that needs to be drained. The latency only covers the audio HAL
1821 // and kernel buffers. Also the latency does not always include additional delay in the
1822 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001823 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001824
1825 // force restoring the device selection on other active outputs if it differs from the
1826 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001827 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001828 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001829 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001830 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001831 desc->isActive() &&
1832 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001833 (newDevices != desc->devices())) {
1834 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1835 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001836
François Gaffie11d30102018-11-02 16:09:09 +01001837 setOutputDevices(desc, newDevices2, force, delayMs);
1838
Eric Laurent57de36c2016-09-28 16:59:11 -07001839 // re-apply device specific volume if not done by setOutputDevice()
1840 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001841 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001842 }
Eric Laurente552edb2014-03-10 17:42:56 -07001843 }
1844 }
1845 // update the outputs if stopping one with a stream that can affect notification routing
1846 handleNotificationRoutingForStream(stream);
1847 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001848
1849 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1850 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001851 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001852 }
1853
François Gaffiec005e562018-11-06 15:04:49 +01001854 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001855 selectOutputForMusicEffects();
1856 }
Eric Laurente552edb2014-03-10 17:42:56 -07001857 return NO_ERROR;
1858 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001859 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001860 return INVALID_OPERATION;
1861 }
1862}
1863
Eric Laurent8fc147b2018-07-22 19:13:55 -07001864void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001865{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001866 ALOGV("%s portId %d", __FUNCTION__, portId);
1867
1868 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1869 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001870 // If an output descriptor is closed due to a device routing change,
1871 // then there are race conditions with releaseOutput from tracks
1872 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1873 // destroyed shortly thereafter.
1874 //
1875 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001876 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001877 return;
1878 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001879
1880 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001881
Eric Laurent8fc147b2018-07-22 19:13:55 -07001882 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1883 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001884 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001885 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001886 return;
1887 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001888 if (--outputDesc->mDirectOpenCount == 0) {
1889 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001890 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001891 }
1892 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001893 // stopOutput() needs to be successfully called before releaseOutput()
1894 // otherwise there may be inaccurate stream reference counts.
1895 // This is checked in outputDesc->removeClient below.
1896 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001897}
1898
Eric Laurentcaf7f482014-11-25 17:50:47 -08001899status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1900 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001901 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001902 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001903 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001904 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001905 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001906 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001907 input_type_t *inputType,
1908 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001909{
François Gaffiec005e562018-11-06 15:04:49 +01001910 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1911 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1912 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001913
Eric Laurentad2e7b92017-09-14 20:06:42 -07001914 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001915 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001916 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001917 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001918 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001919 sp<AudioInputDescriptor> inputDesc;
1920 sp<RecordClientDescriptor> clientDesc;
1921 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001922 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001923
1924 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1925 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1926 return INVALID_OPERATION;
1927 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001928
Francois Gaffie716e1432019-01-14 16:58:59 +01001929 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1930 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001931 }
1932
Paul McLean466dc8e2015-04-17 13:15:36 -06001933 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001934 sp<DeviceDescriptor> explicitRoutingDevice =
1935 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001936
Eric Laurentad2e7b92017-09-14 20:06:42 -07001937 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1938 // possible
1939 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1940 *input != AUDIO_IO_HANDLE_NONE) {
1941 ssize_t index = mInputs.indexOfKey(*input);
1942 if (index < 0) {
1943 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1944 status = BAD_VALUE;
1945 goto error;
1946 }
1947 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001948 RecordClientVector clients = inputDesc->getClientsForSession(session);
1949 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001950 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1951 status = BAD_VALUE;
1952 goto error;
1953 }
1954 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1955 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001956 // corresponds to a new client and is only permitted from the same UID.
1957 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001958 if (clients.size() > 1) {
1959 for (const auto& client : clients) {
1960 // The client map is ordered by key values (portId) and portIds are allocated
1961 // incrementaly. So the first client in this list is the one opened by audio flinger
1962 // when the mmap stream is created and should be ignored as it does not correspond
1963 // to an actual client
1964 if (client == *clients.cbegin()) {
1965 continue;
1966 }
1967 if (uid != client->uid() && !client->isSilenced()) {
1968 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1969 uid, client->portId(), client->uid());
1970 status = INVALID_OPERATION;
1971 goto error;
1972 }
Eric Laurent331679c2018-04-16 17:03:16 -07001973 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001974 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001975 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001976 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001977
Eric Laurent8f42ea12018-08-08 09:08:25 -07001978 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001979 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001980 }
1981
1982 *input = AUDIO_IO_HANDLE_NONE;
1983 *inputType = API_INPUT_INVALID;
1984
Francois Gaffie716e1432019-01-14 16:58:59 +01001985 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001986
Francois Gaffie716e1432019-01-14 16:58:59 +01001987 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1988 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1989 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001990 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07001991 ALOGW("%s could not find input mix for attr %s",
1992 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07001993 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001994 }
jiabinc1de2df2019-05-07 14:26:40 -07001995 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1996 String8(attr->tags + strlen("addr=")),
1997 AUDIO_FORMAT_DEFAULT);
1998 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07001999 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002000 __func__, attributes.source, attributes.tags);
2001 status = BAD_VALUE;
2002 goto error;
2003 }
2004
Kevin Rocard25f9b052019-02-27 15:08:54 -08002005 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2006 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2007 } else {
2008 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2009 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002010 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002011 if (explicitRoutingDevice != nullptr) {
2012 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002013 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002014 // Prevent from storing invalid requested device id in clients
2015 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002016 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002017 }
François Gaffie11d30102018-11-02 16:09:09 +01002018 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002019 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002020 status = BAD_VALUE;
2021 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002022 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002023 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002024 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2025 // there is an external policy, but this input is attached to a mix of recorders,
2026 // meaning it receives audio injected into the framework, so the recorder doesn't
2027 // know about it and is therefore considered "legacy"
2028 *inputType = API_INPUT_LEGACY;
2029 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002030 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002031 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002032 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002033 } else {
2034 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002035 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002036
Eric Laurent599c7582015-12-07 18:05:55 -08002037 }
2038
François Gaffiec005e562018-11-06 15:04:49 +01002039 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002040 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002041 status = INVALID_OPERATION;
2042 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002043 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002044
Eric Laurent8f42ea12018-08-08 09:08:25 -07002045exit:
2046
François Gaffiec005e562018-11-06 15:04:49 +01002047 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2048 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002049
Francois Gaffie716e1432019-01-14 16:58:59 +01002050 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002051 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabindff2a4f2019-09-10 14:29:54 -07002052 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002053
Mikhail Naganov2996f672019-04-18 12:29:59 -07002054 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002055 requestedDeviceId, attributes.source, flags,
2056 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002057 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002058 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002059
2060 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2061 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002062
Eric Laurent599c7582015-12-07 18:05:55 -08002063 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002064
2065error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002066 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002067}
2068
2069
François Gaffie11d30102018-11-02 16:09:09 +01002070audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002071 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002072 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002073 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002074 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002075 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002076{
2077 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002078 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002079 bool isSoundTrigger = false;
2080
François Gaffiec005e562018-11-06 15:04:49 +01002081 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002082 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2083 if (index >= 0) {
2084 input = mSoundTriggerSessions.valueFor(session);
2085 isSoundTrigger = true;
2086 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2087 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2088 } else {
2089 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002090 }
François Gaffiec005e562018-11-06 15:04:49 +01002091 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002092 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002093 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002094 }
2095
Andy Hungf129b032015-04-07 13:45:50 -07002096 // find a compatible input profile (not necessarily identical in parameters)
2097 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002098 // sampling rate and flags may be updated by getInputProfile
2099 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2100 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002101 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002102 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002103 audio_input_flags_t profileFlags = flags;
2104 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002105 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002106 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002107 profileFlags);
2108 if (profile != 0) {
2109 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002110 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2111 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002112 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2113 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2114 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002115 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2116 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2117 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002118 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002119 }
Eric Laurente552edb2014-03-10 17:42:56 -07002120 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002121 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002122 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002123 if (samplingRate == 0) {
2124 samplingRate = profileSamplingRate;
2125 }
Eric Laurente552edb2014-03-10 17:42:56 -07002126
Eric Laurent322b4d22015-04-03 15:57:54 -07002127 if (profile->getModuleHandle() == 0) {
2128 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002129 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002130 }
2131
Eric Laurent3974e3b2017-12-07 17:58:43 -08002132 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002133 for (size_t i = 0; i < mInputs.size(); ) {
2134 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2135 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002136 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002137 continue;
2138 }
2139 // if sound trigger, reuse input if used by other sound trigger on same session
2140 // else
2141 // reuse input if active client app is not in IDLE state
2142 //
2143 RecordClientVector clients = desc->clientsList();
2144 bool doClose = false;
2145 for (const auto& client : clients) {
2146 if (isSoundTrigger != client->isSoundTrigger()) {
2147 continue;
2148 }
2149 if (client->isSoundTrigger()) {
2150 if (session == client->session()) {
2151 return desc->mIoHandle;
2152 }
2153 continue;
2154 }
2155 if (client->active() && client->appState() != APP_STATE_IDLE) {
2156 return desc->mIoHandle;
2157 }
2158 doClose = true;
2159 }
2160 if (doClose) {
2161 closeInput(desc->mIoHandle);
2162 } else {
2163 i++;
2164 }
2165 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002166 }
2167
Eric Laurentfe231122017-11-17 17:48:06 -08002168 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002169
Eric Laurentfe231122017-11-17 17:48:06 -08002170 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2171 lConfig.sample_rate = profileSamplingRate;
2172 lConfig.channel_mask = profileChannelMask;
2173 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002174
François Gaffie11d30102018-11-02 16:09:09 +01002175 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002176
2177 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002178 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002179 (profileSamplingRate != lConfig.sample_rate) ||
2180 !audio_formats_match(profileFormat, lConfig.format) ||
2181 (profileChannelMask != lConfig.channel_mask)) {
2182 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002183 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002184 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002185 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002186 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002187 }
Eric Laurent599c7582015-12-07 18:05:55 -08002188 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002189 }
2190
Eric Laurentc722f302014-12-10 11:21:49 -08002191 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002192
Eric Laurent599c7582015-12-07 18:05:55 -08002193 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002194 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002195
Eric Laurent599c7582015-12-07 18:05:55 -08002196 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002197}
2198
Eric Laurent4eb58f12018-12-07 16:41:02 -08002199status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002200{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002201 ALOGV("%s portId %d", __FUNCTION__, portId);
2202
2203 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2204 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002205 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002206 return BAD_VALUE;
2207 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002208 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002209 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 if (client->active()) {
2211 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2212 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002213 }
2214
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 audio_session_t session = client->session();
2216
Eric Laurent4eb58f12018-12-07 16:41:02 -08002217 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002218
Eric Laurent4eb58f12018-12-07 16:41:02 -08002219 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002220
Eric Laurent4eb58f12018-12-07 16:41:02 -08002221 status_t status = inputDesc->start();
2222 if (status != NO_ERROR) {
2223 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002224 }
Eric Laurente552edb2014-03-10 17:42:56 -07002225
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002226 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002227 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002228 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002229
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230 // indicate active capture to sound trigger service if starting capture from a mic on
2231 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002232 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002233 if (device != nullptr) {
2234 status = setInputDevice(input, device, true /* force */);
2235 } else {
2236 ALOGW("%s no new input device can be found for descriptor %d",
2237 __FUNCTION__, inputDesc->getId());
2238 status = BAD_VALUE;
2239 }
Eric Laurente552edb2014-03-10 17:42:56 -07002240
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002241 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002242 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002243 // if input maps to a dynamic policy with an activity listener, notify of state change
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002244 if ((policyMix != NULL)
2245 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2246 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002247 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002248 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002249
François Gaffie11d30102018-11-02 16:09:09 +01002250 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2251 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002252 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2253 SoundTrigger::setCaptureState(true);
2254 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002255
Eric Laurent8f42ea12018-08-08 09:08:25 -07002256 // automatically enable the remote submix output when input is started if not
2257 // used by a policy mix of type MIX_TYPE_RECORDERS
2258 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002259 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002260 String8 address = String8("");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002261 if (policyMix == NULL) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002262 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002263 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2264 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002265 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002266 if (address != "") {
2267 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2268 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002269 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002270 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002271 }
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002272 } else if (status != NO_ERROR) {
2273 // Restore client activity state.
2274 inputDesc->setClientActive(client, false);
2275 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002276 }
2277
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002278 ALOGV("%s input %d source = %d status = %d exit",
2279 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002280
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002281 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002282}
2283
Eric Laurent8fc147b2018-07-22 19:13:55 -07002284status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002285{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002286 ALOGV("%s portId %d", __FUNCTION__, portId);
2287
2288 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2289 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002290 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002291 return BAD_VALUE;
2292 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002293 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002294 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002295 if (!client->active()) {
2296 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002297 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002298 }
2299
Eric Laurent8f42ea12018-08-08 09:08:25 -07002300 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002301
Eric Laurent8f42ea12018-08-08 09:08:25 -07002302 inputDesc->stop();
2303 if (inputDesc->isActive()) {
2304 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2305 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002306 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002307 // if input maps to a dynamic policy with an activity listener, notify of state change
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002308 if ((policyMix != NULL)
2309 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2310 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002311 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002312 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002313
2314 // automatically disable the remote submix output when input is stopped if not
2315 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002316 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002317 String8 address = String8("");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002318 if (policyMix == NULL) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002319 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002320 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2321 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002322 }
2323 if (address != "") {
2324 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2325 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002326 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002327 }
2328 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002329 resetInputDevice(input);
2330
2331 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2332 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002333 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2334 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002335 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2336 SoundTrigger::setCaptureState(false);
2337 }
2338 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002339 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002340 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002341}
2342
Eric Laurent8fc147b2018-07-22 19:13:55 -07002343void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002344{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002345 ALOGV("%s portId %d", __FUNCTION__, portId);
2346
2347 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2348 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002349 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002350 return;
2351 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002352 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002353 audio_io_handle_t input = inputDesc->mIoHandle;
2354
Eric Laurent8f42ea12018-08-08 09:08:25 -07002355 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002356
Andy Hung39efb7a2018-09-26 15:39:28 -07002357 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002358
Andy Hung39efb7a2018-09-26 15:39:28 -07002359 if (inputDesc->getClientCount() > 0) {
2360 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002361 return;
2362 }
2363
Eric Laurent05b90f82014-08-27 15:32:29 -07002364 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002365 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002366 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002367}
2368
Eric Laurent8f42ea12018-08-08 09:08:25 -07002369void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002370{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002371 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002372
2373 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002374 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002375 }
2376}
2377
Eric Laurent8f42ea12018-08-08 09:08:25 -07002378void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2379{
2380 stopInput(portId);
2381 releaseInput(portId);
2382}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002383
Eric Laurent0dd51852019-04-19 18:18:58 -07002384void AudioPolicyManager::checkCloseInputs() {
2385 // After connecting or disconnecting an input device, close input if:
2386 // - it has no client (was just opened to check profile) OR
2387 // - none of its supported devices are connected anymore OR
2388 // - one of its clients cannot be routed to one of its supported
2389 // devices anymore. Otherwise update device selection
2390 std::vector<audio_io_handle_t> inputsToClose;
2391 for (size_t i = 0; i < mInputs.size(); i++) {
2392 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2393 if (input->clientsList().size() == 0
Eric Laurentb5dc2d12019-07-13 09:32:47 -07002394 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())
jiabindff2a4f2019-09-10 14:29:54 -07002395 || (input->getPolicyAudioPort()->getFlags()
2396 & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002397 inputsToClose.push_back(mInputs.keyAt(i));
2398 } else {
2399 bool close = false;
2400 for (const auto& client : input->clientsList()) {
2401 sp<DeviceDescriptor> device =
2402 mEngine->getInputDeviceForAttributes(client->attributes());
2403 if (!input->supportedDevices().contains(device)) {
2404 close = true;
2405 break;
2406 }
2407 }
2408 if (close) {
2409 inputsToClose.push_back(mInputs.keyAt(i));
2410 } else {
2411 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2412 }
2413 }
2414 }
2415
2416 for (const audio_io_handle_t handle : inputsToClose) {
2417 ALOGV("%s closing input %d", __func__, handle);
2418 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002419 }
Eric Laurentd4692962014-05-05 18:13:44 -07002420}
2421
François Gaffie251c7f02018-11-07 10:41:08 +01002422void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002423{
2424 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002425 if (indexMin < 0 || indexMax < 0) {
2426 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2427 return;
2428 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002429 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002430
2431 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002432 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2433 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002434 continue;
2435 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002436 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002437 }
Eric Laurente552edb2014-03-10 17:42:56 -07002438}
2439
Eric Laurente0720872014-03-11 09:30:41 -07002440status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002441 int index,
2442 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002443{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002444 auto attributes = mEngine->getAttributesForStreamType(stream);
Francois Gaffie5992b182020-03-20 14:55:14 +01002445 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2446 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2447 return NO_ERROR;
2448 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002449 ALOGV("%s: stream %s attributes=%s", __func__,
2450 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002451 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002452}
2453
Eric Laurente0720872014-03-11 09:30:41 -07002454status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002455 int *index,
2456 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002457{
François Gaffiec005e562018-11-06 15:04:49 +01002458 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2459 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002460 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002461 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002462 deviceTypes = mEngine->getOutputDevicesForStream(
2463 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002464 }
jiabin12dc6b02019-10-01 09:38:30 -07002465 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002466}
2467
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002468status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002469 int index,
2470 audio_devices_t device)
2471{
2472 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002473 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2474 if (group == VOLUME_GROUP_NONE) {
2475 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002476 return BAD_VALUE;
2477 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002478 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002479 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002480 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002481 VolumeSource vs = toVolumeSource(group);
2482 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2483
2484 status = setVolumeCurveIndex(index, device, curves);
2485 if (status != NO_ERROR) {
2486 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2487 return status;
2488 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002489
jiabin12dc6b02019-10-01 09:38:30 -07002490 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002491 auto curCurvAttrs = curves.getAttributes();
2492 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2493 auto attr = curCurvAttrs.front();
jiabin12dc6b02019-10-01 09:38:30 -07002494 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002495 } else if (!curves.getStreamTypes().empty()) {
2496 auto stream = curves.getStreamTypes().front();
jiabin12dc6b02019-10-01 09:38:30 -07002497 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002498 } else {
2499 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2500 return BAD_VALUE;
2501 }
jiabin12dc6b02019-10-01 09:38:30 -07002502 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2503 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002504
François Gaffiecfe17322018-11-07 13:41:29 +01002505 // update volume on all outputs and streams matching the following:
2506 // - The requested stream (or a stream matching for volume control) is active on the output
2507 // - The device (or devices) selected by the engine for this stream includes
2508 // the requested device
2509 // - For non default requested device, currently selected device on the output is either the
2510 // requested device or one of the devices selected by the engine for this stream
2511 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2512 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002513 for (size_t i = 0; i < mOutputs.size(); i++) {
2514 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07002515 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002516
jiabin12dc6b02019-10-01 09:38:30 -07002517 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2518 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002519 }
François Gaffieed91f582020-01-31 10:35:37 +01002520 if (!(desc->isActive(vs) || isInCall())) {
2521 continue;
2522 }
2523 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2524 curDevices.find(device) == curDevices.end()) {
2525 continue;
2526 }
2527 bool applyVolume = false;
2528 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2529 curSrcDevices.insert(device);
2530 applyVolume = (curSrcDevices.find(
2531 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2532 } else {
2533 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2534 }
2535 if (!applyVolume) {
2536 continue; // next output
2537 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002538 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2539 // If a higher priority strategy is active, and the output is routed to a device with a
2540 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002541 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002542 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002543 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2544 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2545 false /*preferredDevice*/);
2546 if (activeClients.empty()) {
2547 continue;
2548 }
2549 bool isPreempted = false;
2550 bool isHigherPriority = productStrategy < strategy;
2551 for (const auto &client : activeClients) {
2552 if (isHigherPriority && (client->volumeSource() != vs)) {
2553 ALOGV("%s: Strategy=%d (\nrequester:\n"
2554 " group %d, volumeGroup=%d attributes=%s)\n"
2555 " higher priority source active:\n"
2556 " volumeGroup=%d attributes=%s) \n"
2557 " on output %zu, bailing out", __func__, productStrategy,
2558 group, group, toString(attributes).c_str(),
2559 client->volumeSource(), toString(client->attributes()).c_str(), i);
2560 applyVolume = false;
2561 isPreempted = true;
2562 break;
2563 }
2564 // However, continue for loop to ensure no higher prio clients running on output
2565 if (client->volumeSource() == vs) {
2566 applyVolume = true;
2567 }
2568 }
2569 if (isPreempted || applyVolume) {
2570 break;
2571 }
2572 }
2573 if (!applyVolume) {
2574 continue; // next output
2575 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002576 }
François Gaffieed91f582020-01-31 10:35:37 +01002577 //FIXME: workaround for truncated touch sounds
2578 // delayed volume change for system stream to be removed when the problem is
2579 // handled by system UI
2580 status_t volStatus = checkAndSetVolume(
2581 curves, vs, index, desc, curDevices,
2582 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2583 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2584 if (volStatus != NO_ERROR) {
2585 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002586 }
2587 }
François Gaffiecfe17322018-11-07 13:41:29 +01002588 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2589 return status;
2590}
2591
François Gaffieaaac0fd2018-11-22 17:56:39 +01002592status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002593 audio_devices_t device,
2594 IVolumeCurves &volumeCurves)
2595{
2596 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2597 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002598 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2599 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002600 (index > volumeCurves.getVolumeIndexMax())) {
2601 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2602 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2603 return BAD_VALUE;
2604 }
2605 if (!audio_is_output_device(device)) {
2606 return BAD_VALUE;
2607 }
2608
2609 // Force max volume if stream cannot be muted
2610 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2611
François Gaffieaaac0fd2018-11-22 17:56:39 +01002612 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002613 volumeCurves.addCurrentVolumeIndex(device, index);
2614 return NO_ERROR;
2615}
2616
2617status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2618 int &index,
2619 audio_devices_t device)
2620{
2621 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2622 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002623 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002624 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002625 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2626 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002627 }
jiabin12dc6b02019-10-01 09:38:30 -07002628 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002629}
2630
2631status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2632 int &index,
jiabin12dc6b02019-10-01 09:38:30 -07002633 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002634{
jiabin12dc6b02019-10-01 09:38:30 -07002635 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002636 return BAD_VALUE;
2637 }
jiabin12dc6b02019-10-01 09:38:30 -07002638 index = curves.getVolumeIndex(deviceTypes);
2639 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002640 return NO_ERROR;
2641}
2642
2643status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2644 int &index)
2645{
2646 index = getVolumeCurves(attr).getVolumeIndexMin();
2647 return NO_ERROR;
2648}
2649
2650status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2651 int &index)
2652{
2653 index = getVolumeCurves(attr).getVolumeIndexMax();
2654 return NO_ERROR;
2655}
2656
Eric Laurent36829f92017-04-07 19:04:42 -07002657audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002658{
2659 // select one output among several suitable for global effects.
2660 // The priority is as follows:
2661 // 1: An offloaded output. If the effect ends up not being offloadable,
2662 // AudioFlinger will invalidate the track and the offloaded output
2663 // will be closed causing the effect to be moved to a PCM output.
2664 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002665 // 3: The primary output
2666 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002667
François Gaffiec005e562018-11-06 15:04:49 +01002668 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2669 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002670 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002671
Eric Laurent36829f92017-04-07 19:04:42 -07002672 if (outputs.size() == 0) {
2673 return AUDIO_IO_HANDLE_NONE;
2674 }
Eric Laurente552edb2014-03-10 17:42:56 -07002675
Eric Laurent36829f92017-04-07 19:04:42 -07002676 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2677 bool activeOnly = true;
2678
2679 while (output == AUDIO_IO_HANDLE_NONE) {
2680 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2681 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2682 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2683
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002684 for (audio_io_handle_t output : outputs) {
2685 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002686 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002687 continue;
2688 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002689 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2690 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002691 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002692 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002693 }
2694 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002695 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002696 }
2697 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002698 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002699 }
2700 }
2701 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2702 output = outputOffloaded;
2703 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2704 output = outputDeepBuffer;
2705 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2706 output = outputPrimary;
2707 } else {
2708 output = outputs[0];
2709 }
2710 activeOnly = false;
2711 }
2712
2713 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002714 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002715 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2716 mMusicEffectOutput = output;
2717 }
2718
2719 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002720 return output;
2721}
2722
Eric Laurent36829f92017-04-07 19:04:42 -07002723audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2724{
2725 return selectOutputForMusicEffects();
2726}
2727
Eric Laurente0720872014-03-11 09:30:41 -07002728status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002729 audio_io_handle_t io,
2730 uint32_t strategy,
2731 int session,
2732 int id)
2733{
Eric Laurent9b2064c2019-11-22 17:25:04 -08002734 if (session != AUDIO_SESSION_DEVICE) {
2735 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002736 if (index < 0) {
Eric Laurent9b2064c2019-11-22 17:25:04 -08002737 index = mInputs.indexOfKey(io);
2738 if (index < 0) {
2739 ALOGW("registerEffect() unknown io %d", io);
2740 return INVALID_OPERATION;
2741 }
Eric Laurente552edb2014-03-10 17:42:56 -07002742 }
2743 }
François Gaffiec005e562018-11-06 15:04:49 +01002744 return mEffects.registerEffect(desc, io, session, id,
2745 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2746 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002747}
2748
Eric Laurentc241b0d2018-11-28 09:08:49 -08002749status_t AudioPolicyManager::unregisterEffect(int id)
2750{
2751 if (mEffects.getEffect(id) == nullptr) {
2752 return INVALID_OPERATION;
2753 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002754 if (mEffects.isEffectEnabled(id)) {
2755 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2756 setEffectEnabled(id, false);
2757 }
2758 return mEffects.unregisterEffect(id);
2759}
2760
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002761void AudioPolicyManager::cleanUpEffectsForIo(audio_io_handle_t io)
2762{
2763 EffectDescriptorCollection effects = mEffects.getEffectsForIo(io);
2764 for (size_t i = 0; i < effects.size(); i++) {
2765 ALOGW("%s removing stale effect %s, id %d on closed IO %d",
2766 __func__, effects.valueAt(i)->mDesc.name, effects.keyAt(i), io);
2767 unregisterEffect(effects.keyAt(i));
2768 }
2769}
2770
Eric Laurentc241b0d2018-11-28 09:08:49 -08002771status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2772{
2773 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2774 if (effect == nullptr) {
2775 return INVALID_OPERATION;
2776 }
2777
2778 status_t status = mEffects.setEffectEnabled(id, enabled);
2779 if (status == NO_ERROR) {
2780 mInputs.trackEffectEnabled(effect, enabled);
2781 }
2782 return status;
2783}
2784
Eric Laurent6c796322019-04-09 14:13:17 -07002785
2786status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2787{
2788 mEffects.moveEffects(ids, io);
2789 return NO_ERROR;
2790}
2791
Eric Laurentc75307b2015-03-17 15:29:32 -07002792bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2793{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002794 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002795}
2796
2797bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2798{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002799 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002800}
2801
Eric Laurente0720872014-03-11 09:30:41 -07002802bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002803{
2804 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002805 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002806 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002807 return true;
2808 }
2809 }
2810 return false;
2811}
2812
Eric Laurent275e8e92014-11-30 15:14:47 -08002813// Register a list of custom mixes with their attributes and format.
2814// When a mix is registered, corresponding input and output profiles are
2815// added to the remote submix hw module. The profile contains only the
2816// parameters (sampling rate, format...) specified by the mix.
2817// The corresponding input remote submix device is also connected.
2818//
2819// When a remote submix device is connected, the address is checked to select the
2820// appropriate profile and the corresponding input or output stream is opened.
2821//
2822// When capture starts, getInputForAttr() will:
2823// - 1 look for a mix matching the address passed in attribtutes tags if any
2824// - 2 if none found, getDeviceForInputSource() will:
2825// - 2.1 look for a mix matching the attributes source
2826// - 2.2 if none found, default to device selection by policy rules
2827// At this time, the corresponding output remote submix device is also connected
2828// and active playback use cases can be transferred to this mix if needed when reconnecting
2829// after AudioTracks are invalidated
2830//
2831// When playback starts, getOutputForAttr() will:
2832// - 1 look for a mix matching the address passed in attribtutes tags if any
2833// - 2 if none found, look for a mix matching the attributes usage
2834// - 3 if none found, default to device and output selection by policy rules.
2835
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002836status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002837{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002838 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2839 status_t res = NO_ERROR;
2840
2841 sp<HwModule> rSubmixModule;
2842 // examine each mix's route type
2843 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002844 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002845 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2846 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2847 ALOGE("Unsupported Policy Mix %zu of %zu: "
2848 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2849 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002850 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002851 break;
2852 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002853 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2854 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002855 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002856 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2857 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002858 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002859 rSubmixModule = mHwModules.getModuleFromName(
2860 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2861 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002862 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002863 i);
2864 res = INVALID_OPERATION;
2865 break;
2866 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002867 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002868
Eric Laurent97ac8712018-07-27 18:59:02 -07002869 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002870 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002871 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002872 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002873 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2874 } else {
2875 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2876 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002877 }
François Gaffie036e1e92015-03-19 10:16:24 +01002878
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002879 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002880 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002881 res = INVALID_OPERATION;
2882 break;
2883 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002884 audio_config_t outputConfig = mix.mFormat;
2885 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002886 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2887 // stereo and let audio flinger do the channel conversion if needed.
2888 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2889 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabineaf09f02019-08-19 15:08:30 -07002890 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002891 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabineaf09f02019-08-19 15:08:30 -07002892 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002893 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002894
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002895 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002896 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2897 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2898 ALOGE("Failed to set remote submix device available, type %u, address %s",
2899 mix.mDeviceType, address.string());
2900 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002901 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002902 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2903 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002904 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002905 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002906 i, mixes.size(), type, address.string());
2907
2908 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2909 mix.mDeviceType, mix.mDeviceAddress,
2910 String8(), AUDIO_FORMAT_DEFAULT);
2911 if (device == nullptr) {
2912 res = INVALID_OPERATION;
2913 break;
2914 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002915
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002916 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002917 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002919
2920 if (desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002921 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002922 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2923 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002924 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002925 } else {
2926 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002927 }
2928 break;
2929 }
2930 }
2931
2932 if (res != NO_ERROR) {
2933 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002934 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002935 res = INVALID_OPERATION;
2936 break;
2937 } else if (!foundOutput) {
2938 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002939 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002940 res = INVALID_OPERATION;
2941 break;
2942 }
Eric Laurentc722f302014-12-10 11:21:49 -08002943 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002944 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002945 if (res != NO_ERROR) {
2946 unregisterPolicyMixes(mixes);
2947 }
2948 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002949}
2950
2951status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2952{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002953 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002954 status_t res = NO_ERROR;
2955 sp<HwModule> rSubmixModule;
2956 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002957 for (const auto& mix : mixes) {
2958 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002959
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002960 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002961 rSubmixModule = mHwModules.getModuleFromName(
2962 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2963 if (rSubmixModule == 0) {
2964 res = INVALID_OPERATION;
2965 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002966 }
2967 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002968
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002969 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002970
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002971 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002972 res = INVALID_OPERATION;
2973 continue;
2974 }
2975
Kevin Rocard04ed0462019-05-02 17:53:24 -07002976 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
2977 if (getDeviceConnectionState(device, address.string()) ==
2978 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2979 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2980 address.string(), "remote-submix",
2981 AUDIO_FORMAT_DEFAULT);
2982 if (res != OK) {
2983 ALOGE("Error making RemoteSubmix device unavailable for mix "
2984 "with type %d, address %s", device, address.string());
2985 }
2986 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002987 }
jiabineaf09f02019-08-19 15:08:30 -07002988 rSubmixModule->removeOutputProfile(address.c_str());
2989 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002990
Kevin Rocard153f92d2018-12-18 18:33:28 -08002991 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002992 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002993 res = INVALID_OPERATION;
2994 continue;
2995 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002996 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002997 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002998 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002999}
3000
Mikhail Naganov100f0122018-11-29 11:22:16 -08003001void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3002{
3003 size_t i = 0;
3004 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3005 for (const auto& fmt : mManualSurroundFormats) {
3006 if (i++ != 0) dst->append(", ");
3007 std::string sfmt;
3008 FormatConverter::toString(fmt, sfmt);
3009 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3010 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3011 }
3012}
3013
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003014status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
3015 const Vector<AudioDeviceTypeAddr>& devices) {
3016 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
3017 // uid/device affinity is only for output devices
3018 for (size_t i = 0; i < devices.size(); i++) {
3019 if (!audio_is_output_device(devices[i].mType)) {
3020 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
3021 devices[i].mType);
3022 return BAD_VALUE;
3023 }
3024 }
3025 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
3026 if (res == NO_ERROR) {
3027 // reevaluate outputs for all given devices
3028 for (size_t i = 0; i < devices.size(); i++) {
3029 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin5b781412019-11-04 14:10:42 -08003030 devices[i].mType, devices[i].mAddress.c_str(), String8(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003031 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003032 SortedVector<audio_io_handle_t> outputs;
3033 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01003034 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003035 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
jiabin5b781412019-11-04 14:10:42 -08003036 " addr=%s", devices[i].mType, devices[i].mAddress.c_str());
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003037 return INVALID_OPERATION;
3038 }
3039 }
3040 }
3041 return res;
3042}
3043
3044status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3045 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003046 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3047 if (res != NO_ERROR) {
3048 ALOGE("%s() Could not remove all device affinities fo uid = %d",
3049 __FUNCTION__, uid);
3050 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003051 }
3052
3053 return res;
3054}
3055
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003056status_t AudioPolicyManager::setPreferredDeviceForStrategy(product_strategy_t strategy,
3057 const AudioDeviceTypeAddr &device) {
3058 ALOGI("%s() strategy=%d device=%08x addr=%s", __FUNCTION__,
3059 strategy, device.mType, device.mAddress.c_str());
3060 // strategy preferred device is only for output devices
3061 if (!audio_is_output_device(device.mType)) {
3062 ALOGE("%s() device=%08x is NOT an output device", __FUNCTION__, device.mType);
3063 return BAD_VALUE;
3064 }
3065
3066 status_t status = mEngine->setPreferredDeviceForStrategy(strategy, device);
3067 if (status != NO_ERROR) {
3068 ALOGW("Engine could not set preferred device %08x %s for strategy %d",
3069 device.mType, device.mAddress.c_str(), strategy);
3070 return status;
3071 }
3072
3073 checkForDeviceAndOutputChanges();
3074 updateCallAndOutputRouting();
3075
3076 return NO_ERROR;
3077}
3078
3079void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3080{
3081 uint32_t waitMs = 0;
3082 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3083 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3084 waitMs = updateCallRouting(newDevices, delayMs);
3085 }
3086 for (size_t i = 0; i < mOutputs.size(); i++) {
3087 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3088 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3089 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3090 // As done in setDeviceConnectionState, we could also fix default device issue by
3091 // preventing the force re-routing in case of default dev that distinguishes on address.
3092 // Let's give back to engine full device choice decision however.
3093 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
3094 }
3095 if (forceVolumeReeval && !newDevices.isEmpty()) {
3096 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3097 }
3098 }
3099}
3100
3101status_t AudioPolicyManager::removePreferredDeviceForStrategy(product_strategy_t strategy)
3102{
3103 ALOGI("%s() strategy=%d", __FUNCTION__, strategy);
3104
3105 status_t status = mEngine->removePreferredDeviceForStrategy(strategy);
3106 if (status != NO_ERROR) {
3107 ALOGW("Engine could not remove preferred device for strategy %d", strategy);
3108 return status;
3109 }
3110
3111 checkForDeviceAndOutputChanges();
3112 updateCallAndOutputRouting();
3113
3114 return NO_ERROR;
3115}
3116
3117status_t AudioPolicyManager::getPreferredDeviceForStrategy(product_strategy_t strategy,
3118 AudioDeviceTypeAddr &device) {
3119 return mEngine->getPreferredDeviceForStrategy(strategy, device);
3120}
3121
Andy Hungc29d82b2018-10-05 12:23:17 -07003122void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003123{
Andy Hungc29d82b2018-10-05 12:23:17 -07003124 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3125 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003126 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003127 std::string stateLiteral;
3128 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003129 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003130 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3131 "communications", "media", "record", "dock", "system",
3132 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3133 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3134 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003135 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3136 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3137 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3138 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3139 dst->append(" (MANUAL: ");
3140 dumpManualSurroundFormats(dst);
3141 dst->append(")");
3142 }
3143 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003144 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003145 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3146 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
3147 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
3148 mAvailableOutputDevices.dump(dst, String8("Available output"));
3149 mAvailableInputDevices.dump(dst, String8("Available input"));
3150 mHwModulesAll.dump(dst);
3151 mOutputs.dump(dst);
3152 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003153 mEffects.dump(dst);
3154 mAudioPatches.dump(dst);
3155 mPolicyMixes.dump(dst);
3156 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003157
Kevin Rocardb99cc752019-03-21 20:52:24 -07003158 dst->appendFormat(" AllowedCapturePolicies:\n");
3159 for (auto& policy : mAllowedCapturePolicies) {
3160 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3161 }
3162
François Gaffiec005e562018-11-06 15:04:49 +01003163 dst->appendFormat("\nPolicy Engine dump:\n");
3164 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003165}
3166
3167status_t AudioPolicyManager::dump(int fd)
3168{
3169 String8 result;
3170 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003171 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003172 return NO_ERROR;
3173}
3174
Kevin Rocardb99cc752019-03-21 20:52:24 -07003175status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3176{
3177 mAllowedCapturePolicies[uid] = capturePolicy;
3178 return NO_ERROR;
3179}
3180
Eric Laurente552edb2014-03-10 17:42:56 -07003181// This function checks for the parameters which can be offloaded.
3182// This can be enhanced depending on the capability of the DSP and policy
3183// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07003184bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003185{
3186 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003187 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07003188 offloadInfo.sample_rate, offloadInfo.channel_mask,
3189 offloadInfo.format,
3190 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3191 offloadInfo.has_video);
3192
Andy Hung2ddee192015-12-18 17:34:44 -08003193 if (mMasterMono) {
3194 return false; // no offloading if mono is set.
3195 }
3196
Eric Laurente552edb2014-03-10 17:42:56 -07003197 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003198 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3199 ALOGV("offload disabled by audio.offload.disable");
3200 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07003201 }
3202
3203 // Check if stream type is music, then only allow offload as of now.
3204 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3205 {
3206 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3207 return false;
3208 }
3209
3210 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003211 const bool allowOffloadWithVideo =
3212 property_get_bool("audio.offload.video", false /* default_value */);
3213 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07003214 ALOGV("isOffloadSupported: has_video == true, returning false");
3215 return false;
3216 }
3217
3218 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003219 const int min_duration_secs = property_get_int32(
3220 "audio.offload.min.duration.secs", -1 /* default_value */);
3221 if (min_duration_secs >= 0) {
3222 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3223 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3224 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07003225 return false;
3226 }
3227 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3228 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3229 return false;
3230 }
3231
3232 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3233 // creating an offloaded track and tearing it down immediately after start when audioflinger
3234 // detects there is an active non offloadable effect.
3235 // FIXME: We should check the audio session here but we do not have it in this context.
3236 // This may prevent offloading in rare situations where effects are left active by apps
3237 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003238 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003239 return false;
3240 }
3241
3242 // See if there is a profile to support this.
3243 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003244 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003245 offloadInfo.sample_rate,
3246 offloadInfo.format,
3247 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003248 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3249 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07003250 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3251 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003252}
3253
Michael Chana94fbb22018-04-24 14:31:19 +10003254bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3255 const audio_attributes_t& attributes) {
3256 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003257 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003258 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003259 config.sample_rate,
3260 config.format,
3261 config.channel_mask,
3262 output_flags,
3263 true /* directOnly */);
3264 ALOGV("%s() profile %sfound with name: %s, "
3265 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3266 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabineaf09f02019-08-19 15:08:30 -07003267 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003268 config.sample_rate, config.format, config.channel_mask, output_flags);
3269 return (profile != 0);
3270}
3271
Eric Laurent6a94d692014-05-20 11:18:06 -07003272status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3273 audio_port_type_t type,
3274 unsigned int *num_ports,
3275 struct audio_port *ports,
3276 unsigned int *generation)
3277{
3278 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3279 generation == NULL) {
3280 return BAD_VALUE;
3281 }
3282 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3283 if (ports == NULL) {
3284 *num_ports = 0;
3285 }
3286
3287 size_t portsWritten = 0;
3288 size_t portsMax = *num_ports;
3289 *num_ports = 0;
3290 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003291 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3292 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003293 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003294 for (const auto& dev : mAvailableOutputDevices) {
3295 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003296 continue;
3297 }
3298 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003299 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003300 }
3301 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003302 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 }
3304 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003305 for (const auto& dev : mAvailableInputDevices) {
3306 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003307 continue;
3308 }
3309 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003310 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003311 }
3312 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003313 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003314 }
3315 }
3316 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3317 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3318 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3319 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3320 }
3321 *num_ports += mInputs.size();
3322 }
3323 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003324 size_t numOutputs = 0;
3325 for (size_t i = 0; i < mOutputs.size(); i++) {
3326 if (!mOutputs[i]->isDuplicated()) {
3327 numOutputs++;
3328 if (portsWritten < portsMax) {
3329 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3330 }
3331 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003332 }
Eric Laurent84c70242014-06-23 08:46:27 -07003333 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003334 }
3335 }
3336 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003337 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003338 return NO_ERROR;
3339}
3340
Eric Laurent99fcae42018-05-17 16:59:18 -07003341status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003342{
Eric Laurent99fcae42018-05-17 16:59:18 -07003343 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3344 return BAD_VALUE;
3345 }
3346 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3347 if (dev != 0) {
3348 dev->toAudioPort(port);
3349 return NO_ERROR;
3350 }
3351 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3352 if (dev != 0) {
3353 dev->toAudioPort(port);
3354 return NO_ERROR;
3355 }
3356 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3357 if (out != 0) {
3358 out->toAudioPort(port);
3359 return NO_ERROR;
3360 }
3361 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3362 if (in != 0) {
3363 in->toAudioPort(port);
3364 return NO_ERROR;
3365 }
3366 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003367}
3368
François Gaffiead447b72019-11-18 15:50:22 +01003369status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3370 audio_patch_handle_t *handle,
3371 uid_t uid, uint32_t delayMs,
3372 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003373{
François Gaffiead447b72019-11-18 15:50:22 +01003374 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003375 if (handle == NULL || patch == NULL) {
3376 return BAD_VALUE;
3377 }
François Gaffiead447b72019-11-18 15:50:22 +01003378 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003379
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003380 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003381 return BAD_VALUE;
3382 }
3383 // only one source per audio patch supported for now
3384 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003385 return INVALID_OPERATION;
3386 }
Eric Laurent874c42872014-08-08 15:13:39 -07003387
3388 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003389 return INVALID_OPERATION;
3390 }
Eric Laurent874c42872014-08-08 15:13:39 -07003391 for (size_t i = 0; i < patch->num_sinks; i++) {
3392 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3393 return INVALID_OPERATION;
3394 }
3395 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003396
3397 sp<AudioPatch> patchDesc;
3398 ssize_t index = mAudioPatches.indexOfKey(*handle);
3399
François Gaffiead447b72019-11-18 15:50:22 +01003400 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3401 patch->sources[0].role,
3402 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003403#if LOG_NDEBUG == 0
3404 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffiead447b72019-11-18 15:50:22 +01003405 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3406 patch->sinks[i].role,
3407 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003408 }
3409#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003410
3411 if (index >= 0) {
3412 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003413 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3414 __func__, mUidCached, patchDesc->getUid(), uid);
3415 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003416 return INVALID_OPERATION;
3417 }
3418 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003419 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003420 }
3421
3422 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003423 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003424 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003425 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003426 return BAD_VALUE;
3427 }
Eric Laurent84c70242014-06-23 08:46:27 -07003428 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3429 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003430 if (patchDesc != 0) {
3431 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffiead447b72019-11-18 15:50:22 +01003432 ALOGV("%s source id differs for patch current id %d new id %d",
3433 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003434 return BAD_VALUE;
3435 }
3436 }
Eric Laurent874c42872014-08-08 15:13:39 -07003437 DeviceVector devices;
3438 for (size_t i = 0; i < patch->num_sinks; i++) {
3439 // Only support mix to devices connection
3440 // TODO add support for mix to mix connection
3441 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003442 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003443 return INVALID_OPERATION;
3444 }
3445 sp<DeviceDescriptor> devDesc =
3446 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3447 if (devDesc == 0) {
François Gaffiead447b72019-11-18 15:50:22 +01003448 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003449 return BAD_VALUE;
3450 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003451
François Gaffie11d30102018-11-02 16:09:09 +01003452 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003453 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003454 NULL, // updatedSamplingRate
3455 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003456 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003457 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003458 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003459 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffiead447b72019-11-18 15:50:22 +01003460 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003461 return INVALID_OPERATION;
3462 }
3463 devices.add(devDesc);
3464 }
3465 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003466 return INVALID_OPERATION;
3467 }
Eric Laurent874c42872014-08-08 15:13:39 -07003468
Eric Laurent6a94d692014-05-20 11:18:06 -07003469 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003470 ALOGV("%s setting device %s on output %d",
3471 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003472 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003473 index = mAudioPatches.indexOfKey(*handle);
3474 if (index >= 0) {
3475 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003476 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003477 }
3478 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003479 patchDesc->setUid(uid);
3480 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003481 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003482 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003483 return INVALID_OPERATION;
3484 }
3485 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3486 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3487 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003488 // only one sink supported when connecting an input device to a mix
3489 if (patch->num_sinks > 1) {
3490 return INVALID_OPERATION;
3491 }
François Gaffie53615e22015-03-19 09:24:12 +01003492 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003493 if (inputDesc == NULL) {
3494 return BAD_VALUE;
3495 }
3496 if (patchDesc != 0) {
3497 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3498 return BAD_VALUE;
3499 }
3500 }
François Gaffie11d30102018-11-02 16:09:09 +01003501 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003502 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003503 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003504 return BAD_VALUE;
3505 }
3506
François Gaffie11d30102018-11-02 16:09:09 +01003507 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003508 patch->sinks[0].sample_rate,
3509 NULL, /*updatedSampleRate*/
3510 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003511 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003512 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003513 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003514 // FIXME for the parameter type,
3515 // and the NONE
3516 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003517 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003518 return INVALID_OPERATION;
3519 }
3520 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003521 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003522 device->toString().c_str(), inputDesc->mIoHandle);
3523 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003524 index = mAudioPatches.indexOfKey(*handle);
3525 if (index >= 0) {
3526 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003527 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003528 }
3529 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003530 patchDesc->setUid(uid);
3531 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003532 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003533 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003534 return INVALID_OPERATION;
3535 }
3536 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3537 // device to device connection
3538 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003539 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003540 return BAD_VALUE;
3541 }
3542 }
François Gaffie11d30102018-11-02 16:09:09 +01003543 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003544 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003545 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003546 return BAD_VALUE;
3547 }
Eric Laurent874c42872014-08-08 15:13:39 -07003548
Eric Laurent6a94d692014-05-20 11:18:06 -07003549 //update source and sink with our own data as the data passed in the patch may
3550 // be incomplete.
François Gaffiead447b72019-11-18 15:50:22 +01003551 PatchBuilder patchBuilder;
3552 audio_port_config sourcePortConfig = {};
3553 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3554 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003555
Eric Laurent874c42872014-08-08 15:13:39 -07003556 for (size_t i = 0; i < patch->num_sinks; i++) {
3557 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003558 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003559 return INVALID_OPERATION;
3560 }
François Gaffie11d30102018-11-02 16:09:09 +01003561 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003562 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003563 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003564 return BAD_VALUE;
3565 }
François Gaffiead447b72019-11-18 15:50:22 +01003566 audio_port_config sinkPortConfig = {};
3567 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3568 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003569
Eric Laurent3bcf8592015-04-03 12:13:24 -07003570 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003571 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003572 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003573 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffiead447b72019-11-18 15:50:22 +01003574 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3575 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003576 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3577 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffiead447b72019-11-18 15:50:22 +01003578 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3579 (sourceDesc != nullptr &&
3580 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003581 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003582 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003583 return INVALID_OPERATION;
3584 }
François Gaffiead447b72019-11-18 15:50:22 +01003585 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3586 if (sourceDesc != nullptr) {
3587 // take care of dynamic routing for SwOutput selection,
3588 audio_attributes_t attributes = sourceDesc->attributes();
3589 audio_stream_type_t stream = sourceDesc->stream();
3590 audio_attributes_t resultAttr;
3591 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3592 config.sample_rate = sourceDesc->config().sample_rate;
3593 config.channel_mask = sourceDesc->config().channel_mask;
3594 config.format = sourceDesc->config().format;
3595 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3596 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3597 bool isRequestedDeviceForExclusiveUse = false;
3598 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputs;
3599 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3600 &stream, sourceDesc->uid(), &config, &flags,
3601 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3602 &secondaryOutputs);
3603 if (output == AUDIO_IO_HANDLE_NONE) {
3604 ALOGV("%s no output for device %s",
3605 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003606 return INVALID_OPERATION;
3607 }
François Gaffiead447b72019-11-18 15:50:22 +01003608 } else {
3609 SortedVector<audio_io_handle_t> outputs =
3610 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3611 // if the sink device is reachable via an opened output stream, request to
3612 // go via this output stream by adding a second source to the patch
3613 // description
3614 output = selectOutput(outputs);
3615 }
3616 if (output != AUDIO_IO_HANDLE_NONE) {
3617 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3618 if (outputDesc->isDuplicated()) {
3619 ALOGV("%s output for device %s is duplicated",
3620 __FUNCTION__, sinkDevice->toString().c_str());
3621 return INVALID_OPERATION;
3622 }
3623 audio_port_config srcMixPortConfig = {};
3624 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3625 if (sourceDesc != nullptr) {
3626 sourceDesc->setSwOutput(outputDesc);
3627 }
3628 // for volume control, we may need a valid stream
3629 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3630 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3631 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003632 }
Eric Laurent83b88082014-06-20 18:31:16 -07003633 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003634 }
3635 // TODO: check from routing capabilities in config file and other conflicting patches
3636
François Gaffiead447b72019-11-18 15:50:22 +01003637 status_t status = installPatch(
3638 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003639 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01003640 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003641 return INVALID_OPERATION;
3642 }
3643 } else {
3644 return BAD_VALUE;
3645 }
3646 } else {
3647 return BAD_VALUE;
3648 }
3649 return NO_ERROR;
3650}
3651
3652status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3653 uid_t uid)
3654{
3655 ALOGV("releaseAudioPatch() patch %d", handle);
3656
3657 ssize_t index = mAudioPatches.indexOfKey(handle);
3658
3659 if (index < 0) {
3660 return BAD_VALUE;
3661 }
3662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003663 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3664 __func__, mUidCached, patchDesc->getUid(), uid);
3665 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003666 return INVALID_OPERATION;
3667 }
François Gaffiead447b72019-11-18 15:50:22 +01003668 return releaseAudioPatchInternal(handle);
3669}
Eric Laurent6a94d692014-05-20 11:18:06 -07003670
François Gaffiead447b72019-11-18 15:50:22 +01003671status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3672 uint32_t delayMs)
3673{
3674 ALOGV("%s patch %d", __func__, handle);
3675 if (mAudioPatches.indexOfKey(handle) < 0) {
3676 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3677 return BAD_VALUE;
3678 }
3679 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003680 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffiead447b72019-11-18 15:50:22 +01003681 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003682 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003683 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003684 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003685 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003686 return BAD_VALUE;
3687 }
3688
François Gaffie11d30102018-11-02 16:09:09 +01003689 setOutputDevices(outputDesc,
3690 getNewOutputDevices(outputDesc, true /*fromCache*/),
3691 true,
3692 0,
3693 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003694 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3695 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003696 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003697 if (inputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003698 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003699 return BAD_VALUE;
3700 }
3701 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003702 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003703 true,
3704 NULL);
3705 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003706 status_t status =
3707 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
3708 ALOGV("%s patch panel returned %d patchHandle %d",
3709 __func__, status, patchDesc->getAfHandle());
3710 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07003711 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003712 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie3b173542020-04-06 17:39:47 +02003713 // SW Bridge
3714 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
3715 sp<SwAudioOutputDescriptor> outputDesc =
3716 mOutputs.getOutputFromId(patch->sources[1].id);
3717 if (outputDesc == NULL) {
3718 ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
3719 return BAD_VALUE;
3720 }
3721 // Reset handle so that setOutputDevice will force new AF patch to reach the sink
3722 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
3723 setOutputDevices(outputDesc,
3724 getNewOutputDevices(outputDesc, true /*fromCache*/),
3725 true, /*force*/
3726 0,
3727 NULL);
3728 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003729 } else {
3730 return BAD_VALUE;
3731 }
3732 } else {
3733 return BAD_VALUE;
3734 }
3735 return NO_ERROR;
3736}
3737
3738status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3739 struct audio_patch *patches,
3740 unsigned int *generation)
3741{
François Gaffie53615e22015-03-19 09:24:12 +01003742 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003743 return BAD_VALUE;
3744 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003745 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003746 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003747}
3748
Eric Laurente1715a42014-05-20 11:30:42 -07003749status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003750{
Eric Laurente1715a42014-05-20 11:30:42 -07003751 ALOGV("setAudioPortConfig()");
3752
3753 if (config == NULL) {
3754 return BAD_VALUE;
3755 }
3756 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3757 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003758 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3759 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003760 }
3761
Eric Laurenta121f902014-06-03 13:32:54 -07003762 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003763 if (config->type == AUDIO_PORT_TYPE_MIX) {
3764 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003765 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003766 if (outputDesc == NULL) {
3767 return BAD_VALUE;
3768 }
Eric Laurent84c70242014-06-23 08:46:27 -07003769 ALOG_ASSERT(!outputDesc->isDuplicated(),
3770 "setAudioPortConfig() called on duplicated output %d",
3771 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003772 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003773 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003774 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003775 if (inputDesc == NULL) {
3776 return BAD_VALUE;
3777 }
Eric Laurenta121f902014-06-03 13:32:54 -07003778 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003779 } else {
3780 return BAD_VALUE;
3781 }
3782 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3783 sp<DeviceDescriptor> deviceDesc;
3784 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3785 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3786 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3787 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3788 } else {
3789 return BAD_VALUE;
3790 }
3791 if (deviceDesc == NULL) {
3792 return BAD_VALUE;
3793 }
Eric Laurenta121f902014-06-03 13:32:54 -07003794 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003795 } else {
3796 return BAD_VALUE;
3797 }
3798
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003799 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003800 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3801 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003802 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003803 audioPortConfig->toAudioPortConfig(&newConfig, config);
3804 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003805 }
Eric Laurenta121f902014-06-03 13:32:54 -07003806 if (status != NO_ERROR) {
3807 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003808 }
Eric Laurente1715a42014-05-20 11:30:42 -07003809
3810 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003811}
3812
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003813void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3814{
Eric Laurentd60560a2015-04-10 11:31:20 -07003815 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003816 clearAudioPatches(uid);
3817 clearSessionRoutes(uid);
3818}
3819
Eric Laurent6a94d692014-05-20 11:18:06 -07003820void AudioPolicyManager::clearAudioPatches(uid_t uid)
3821{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003822 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffiead447b72019-11-18 15:50:22 +01003824 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003825 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003826 }
3827 }
3828}
3829
François Gaffiec005e562018-11-06 15:04:49 +01003830void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003831{
François Gaffiec005e562018-11-06 15:04:49 +01003832 // Take the first attributes following the product strategy as it is used to retrieve the routed
3833 // device. All attributes wihin a strategy follows the same "routing strategy"
3834 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
3835 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01003836 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003837 for (size_t j = 0; j < mOutputs.size(); j++) {
3838 if (mOutputs.keyAt(j) == ouptutToSkip) {
3839 continue;
3840 }
3841 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01003842 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003843 continue;
3844 }
3845 // If the default device for this strategy is on another output mix,
3846 // invalidate all tracks in this strategy to force re connection.
3847 // Otherwise select new device on the output mix.
3848 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01003849 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
3850 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003851 }
3852 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003853 setOutputDevices(
3854 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003855 }
3856 }
3857}
3858
3859void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3860{
3861 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01003862 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003863 for (size_t i = 0; i < mOutputs.size(); i++) {
3864 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003865 for (const auto& client : outputDesc->getClientIterable()) {
3866 if (client->hasPreferredDevice() && client->uid() == uid) {
3867 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01003868 auto clientStrategy = client->strategy();
3869 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
3870 end(affectedStrategies)) {
3871 continue;
3872 }
3873 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003874 }
3875 }
3876 }
3877 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003878 for (const auto& strategy : affectedStrategies) {
3879 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003880 }
3881
3882 // remove input routes associated with this uid
3883 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003884 for (size_t i = 0; i < mInputs.size(); i++) {
3885 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003886 for (const auto& client : inputDesc->getClientIterable()) {
3887 if (client->hasPreferredDevice() && client->uid() == uid) {
3888 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3889 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003890 }
3891 }
3892 }
3893 // reroute inputs if necessary
3894 SortedVector<audio_io_handle_t> inputsToClose;
3895 for (size_t i = 0; i < mInputs.size(); i++) {
3896 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003897 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003898 inputsToClose.add(inputDesc->mIoHandle);
3899 }
3900 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003901 for (const auto& input : inputsToClose) {
3902 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003903 }
3904}
3905
Eric Laurentd60560a2015-04-10 11:31:20 -07003906void AudioPolicyManager::clearAudioSources(uid_t uid)
3907{
3908 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003909 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3910 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003911 stopAudioSource(mAudioSources.keyAt(i));
3912 }
3913 }
3914}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003915
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003916status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3917 audio_io_handle_t *ioHandle,
3918 audio_devices_t *device)
3919{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003920 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3921 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003922 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01003923 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003924
François Gaffiedf372692015-03-19 10:43:27 +01003925 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003926}
3927
Eric Laurentd60560a2015-04-10 11:31:20 -07003928status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003929 const audio_attributes_t *attributes,
3930 audio_port_handle_t *portId,
3931 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003932{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003933 ALOGV("%s", __FUNCTION__);
3934 *portId = AUDIO_PORT_HANDLE_NONE;
3935
3936 if (source == NULL || attributes == NULL || portId == NULL) {
3937 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3938 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003939 return BAD_VALUE;
3940 }
3941
Eric Laurentd60560a2015-04-10 11:31:20 -07003942 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3943 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003944 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3945 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003946 return INVALID_OPERATION;
3947 }
3948
François Gaffie11d30102018-11-02 16:09:09 +01003949 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003950 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003951 String8(source->ext.device.address),
3952 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003953 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003954 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003955 return BAD_VALUE;
3956 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003957
jiabindff2a4f2019-09-10 14:29:54 -07003958 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003959
François Gaffieaaac0fd2018-11-22 17:56:39 +01003960 sp<SourceClientDescriptor> sourceDesc =
François Gaffiead447b72019-11-18 15:50:22 +01003961 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003962 mEngine->getStreamTypeForAttributes(*attributes),
3963 mEngine->getProductStrategyForAttributes(*attributes),
3964 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003965
3966 status_t status = connectAudioSource(sourceDesc);
3967 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003968 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003969 }
3970 return status;
3971}
3972
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003973status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003974{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003975 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003976
3977 // make sure we only have one patch per source.
3978 disconnectAudioSource(sourceDesc);
3979
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003980 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01003981 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003982
François Gaffiec005e562018-11-06 15:04:49 +01003983 DeviceVector sinkDevices =
3984 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
3985 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01003986 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3987 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3988 __FUNCTION__, sinkDevice->toString().c_str());
François Gaffiead447b72019-11-18 15:50:22 +01003989 PatchBuilder patchBuilder;
3990 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
3991 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
3992 status_t status =
3993 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
3994 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
3995 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
3996 return INVALID_OPERATION;
3997 }
3998 sourceDesc->setPatchHandle(handle);
3999 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4000 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4001 if (swOutput != 0) {
4002 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004003 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004004 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004005 }
François Gaffiead447b72019-11-18 15:50:22 +01004006 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004007 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffiead447b72019-11-18 15:50:22 +01004008 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004009 }
François Gaffiead447b72019-11-18 15:50:22 +01004010 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004011 uint32_t delayMs = 0;
François Gaffiead447b72019-11-18 15:50:22 +01004012 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004013 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004014 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4015 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004016 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004017 if (delayMs != 0) {
4018 usleep(delayMs * 1000);
4019 }
François Gaffiead447b72019-11-18 15:50:22 +01004020 } else {
4021 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4022 if (hwOutputDesc != 0) {
4023 // create Hwoutput and add to mHwOutputs
4024 } else {
4025 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4026 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004027 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004028 return NO_ERROR;
François Gaffiead447b72019-11-18 15:50:22 +01004029
4030FailureSourceActive:
4031 swOutput->stop();
4032 releaseOutput(sourceDesc->portId());
4033FailureSourceAdded:
4034 sourceDesc->setSwOutput(nullptr);
4035FailureReleasePatch:
4036 releaseAudioPatchInternal(handle);
4037 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004038}
4039
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004040status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004041{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004042 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4043 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004044 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004045 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004046 return BAD_VALUE;
4047 }
4048 status_t status = disconnectAudioSource(sourceDesc);
4049
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004050 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004051 return status;
4052}
4053
Andy Hung2ddee192015-12-18 17:34:44 -08004054status_t AudioPolicyManager::setMasterMono(bool mono)
4055{
4056 if (mMasterMono == mono) {
4057 return NO_ERROR;
4058 }
4059 mMasterMono = mono;
4060 // if enabling mono we close all offloaded devices, which will invalidate the
4061 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4062 // for recreating the new AudioTrack as non-offloaded PCM.
4063 //
4064 // If disabling mono, we leave all tracks as is: we don't know which clients
4065 // and tracks are able to be recreated as offloaded. The next "song" should
4066 // play back offloaded.
4067 if (mMasterMono) {
4068 Vector<audio_io_handle_t> offloaded;
4069 for (size_t i = 0; i < mOutputs.size(); ++i) {
4070 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4071 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4072 offloaded.push(desc->mIoHandle);
4073 }
4074 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004075 for (const auto& handle : offloaded) {
4076 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004077 }
4078 }
4079 // update master mono for all remaining outputs
4080 for (size_t i = 0; i < mOutputs.size(); ++i) {
4081 updateMono(mOutputs.keyAt(i));
4082 }
4083 return NO_ERROR;
4084}
4085
4086status_t AudioPolicyManager::getMasterMono(bool *mono)
4087{
4088 *mono = mMasterMono;
4089 return NO_ERROR;
4090}
4091
Eric Laurentac9cef52017-06-09 15:46:26 -07004092float AudioPolicyManager::getStreamVolumeDB(
4093 audio_stream_type_t stream, int index, audio_devices_t device)
4094{
jiabin12dc6b02019-10-01 09:38:30 -07004095 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004096}
4097
jiabin81772902018-04-02 17:52:27 -07004098status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4099 audio_format_t *surroundFormats,
4100 bool *surroundFormatsEnabled,
4101 bool reported)
4102{
4103 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4104 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4105 return BAD_VALUE;
4106 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004107 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4108 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004109
4110 size_t formatsWritten = 0;
4111 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004112 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004113 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004114 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004115 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004116 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4117 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4118 FormatVector supportedFormats =
4119 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
4120 for (size_t j = 0; j < supportedFormats.size(); j++) {
4121 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
4122 formats.insert(supportedFormats[j]);
4123 } else {
4124 for (const auto& pair : mConfig.getSurroundFormats()) {
4125 if (pair.second.count(supportedFormats[j]) != 0) {
4126 formats.insert(pair.first);
4127 break;
4128 }
4129 }
4130 }
4131 }
jiabin81772902018-04-02 17:52:27 -07004132 }
4133 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004134 for (const auto& pair : mConfig.getSurroundFormats()) {
4135 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004136 }
4137 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004138 *numSurroundFormats = formats.size();
4139 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4140 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004141 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004142 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004143 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004144 bool formatEnabled = true;
4145 switch (forceUse) {
4146 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4147 formatEnabled = mManualSurroundFormats.count(format) != 0;
4148 break;
4149 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4150 formatEnabled = false;
4151 break;
4152 default: // AUTO or ALWAYS => true
4153 break;
jiabin81772902018-04-02 17:52:27 -07004154 }
4155 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4156 }
jiabin81772902018-04-02 17:52:27 -07004157 }
4158 return NO_ERROR;
4159}
4160
4161status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4162{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004163 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004164 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4165 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004166 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004167 return BAD_VALUE;
4168 }
4169
Mikhail Naganov100f0122018-11-29 11:22:16 -08004170 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4171 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004172 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004173 return INVALID_OPERATION;
4174 }
4175
Mikhail Naganov100f0122018-11-29 11:22:16 -08004176 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004177 return NO_ERROR;
4178 }
4179
Mikhail Naganov100f0122018-11-29 11:22:16 -08004180 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004181 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004182 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004183 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004184 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004185 }
4186 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004187 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004188 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004189 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004190 }
4191 }
4192
4193 sp<SwAudioOutputDescriptor> outputDesc;
4194 bool profileUpdated = false;
jiabin12dc6b02019-10-01 09:38:30 -07004195 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4196 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004197 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4198 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004199 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004200 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004201 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4202 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4203 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004204 name.c_str(),
4205 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004206 if (status != NO_ERROR) {
4207 continue;
4208 }
4209 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4210 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4211 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004212 name.c_str(),
4213 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004214 profileUpdated |= (status == NO_ERROR);
4215 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004216 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin12dc6b02019-10-01 09:38:30 -07004217 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004218 AUDIO_DEVICE_IN_HDMI);
4219 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4220 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004221 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004222 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004223 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4224 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4225 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004226 name.c_str(),
4227 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004228 if (status != NO_ERROR) {
4229 continue;
4230 }
4231 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4232 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4233 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004234 name.c_str(),
4235 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004236 profileUpdated |= (status == NO_ERROR);
4237 }
4238
jiabin81772902018-04-02 17:52:27 -07004239 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004240 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004241 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004242 }
4243
4244 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4245}
4246
Eric Laurentf32108e2018-10-04 17:22:04 -07004247void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004248{
Eric Laurent4eb58f12018-12-07 16:41:02 -08004249 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004250 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004251 mInputs.valueAt(i)->setAppState(uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004252 }
4253}
4254
jiabin6012f912018-11-02 17:06:30 -07004255bool AudioPolicyManager::isHapticPlaybackSupported()
4256{
4257 for (const auto& hwModule : mHwModules) {
4258 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4259 for (const auto &outProfile : outputProfiles) {
4260 struct audio_port audioPort;
4261 outProfile->toAudioPort(&audioPort);
4262 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4263 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4264 return true;
4265 }
4266 }
4267 }
4268 }
4269 return false;
4270}
4271
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004272status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004273{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004274 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffiead447b72019-11-18 15:50:22 +01004275 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4276 if (swOutput != 0) {
4277 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004278 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004279 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004280 }
François Gaffiead447b72019-11-18 15:50:22 +01004281 releaseOutput(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004282 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004283 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004284 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004285 // close Hwoutput and remove from mHwOutputs
4286 } else {
4287 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4288 }
4289 }
François Gaffiead447b72019-11-18 15:50:22 +01004290 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004291}
4292
François Gaffiec005e562018-11-06 15:04:49 +01004293sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4294 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004295{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004296 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004297 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004298 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004299 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004300 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4301 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004302 source = sourceDesc;
4303 break;
4304 }
4305 }
4306 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004307}
4308
Eric Laurente552edb2014-03-10 17:42:56 -07004309// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004310// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004311// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004312uint32_t AudioPolicyManager::nextAudioPortGeneration()
4313{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004314 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004315}
4316
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004317static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4318 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004319 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004320 status_t ret;
4321
Cheney Ni00ce33d2018-11-01 06:30:37 +08004322 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
Cheney Nie5985452019-02-24 01:39:15 +08004323 if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
4324 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4325 // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
4326 // the legacy hardware module for A2DP and hearing aid.
4327 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4328 } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4329 // A2DP offload supported but disabled: try to use special XML file
Cheney Ni6851adb2018-11-01 06:30:37 +08004330 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4331 }
Cheney Nie5985452019-02-24 01:39:15 +08004332 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
4333 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
Petri Gyntherf497f292018-04-17 18:46:10 -07004334 }
4335 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4336
4337 for (const char* fileName : fileNames) {
Mikhail Naganovedc0ae12020-04-14 14:47:01 -07004338 for (const auto& path : audio_get_configuration_paths()) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004339 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
Mikhail Naganovedc0ae12020-04-14 14:47:01 -07004340 "%s/%s", path.c_str(), fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004341 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004342 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004343 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004344 return ret;
4345 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004346 }
4347 }
4348 return ret;
4349}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004350
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004351AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4352 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004353 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004354 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004355 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004356 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004357 mA2dpSuspended(false),
Mikhail Naganov560095b2020-03-05 16:28:57 -08004358 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004359 mAudioPortGeneration(1),
4360 mBeaconMuteRefCount(0),
4361 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004362 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004363 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004364 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004365 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004366{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004367}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004368
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004369AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4370 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4371{
4372 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004373}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004374
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004375void AudioPolicyManager::loadConfig() {
4376 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004377 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004378 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004379 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004380}
4381
4382status_t AudioPolicyManager::initialize() {
Mikhail Naganove13c6792019-05-14 10:32:51 -07004383 {
4384 auto engLib = EngineLibrary::load(
4385 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4386 if (!engLib) {
4387 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4388 return NO_INIT;
4389 }
4390 mEngine = engLib->createEngine();
4391 if (mEngine == nullptr) {
4392 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4393 return NO_INIT;
4394 }
François Gaffie2110e042015-03-24 08:41:51 +01004395 }
4396 mEngine->setObserver(this);
4397 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004398 if (status != NO_ERROR) {
4399 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4400 return status;
4401 }
François Gaffie2110e042015-03-24 08:41:51 +01004402
Mikhail Naganov560095b2020-03-05 16:28:57 -08004403 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004404 // open all output streams needed to access attached devices
Mikhail Naganova30ec142020-03-24 09:32:34 -07004405 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004406
Eric Laurent3a4311c2014-03-17 12:00:47 -07004407 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004408 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4409 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4410 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004411 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004412 }
jiabin9ff780e2018-03-19 18:19:52 -07004413 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004414 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabin6713a382019-09-12 16:29:15 -07004415 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004416 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004417 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004418 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004419 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004420 }
4421 }
4422 }
Eric Laurente552edb2014-03-10 17:42:56 -07004423
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004424 if (mPrimaryOutput == 0) {
4425 ALOGE("Failed to open primary output");
4426 status = NO_INIT;
4427 }
Eric Laurente552edb2014-03-10 17:42:56 -07004428
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004429 // Silence ALOGV statements
4430 property_set("log.tag." LOG_TAG, "D");
4431
Eric Laurente552edb2014-03-10 17:42:56 -07004432 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004433 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004434}
4435
Eric Laurente0720872014-03-11 09:30:41 -07004436AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004437{
Eric Laurente552edb2014-03-10 17:42:56 -07004438 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004439 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004440 }
4441 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004442 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004443 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004444 mAvailableOutputDevices.clear();
4445 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004446 mOutputs.clear();
4447 mInputs.clear();
4448 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004449 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004450 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004451}
4452
Eric Laurente0720872014-03-11 09:30:41 -07004453status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004454{
Eric Laurent87ffa392015-05-22 10:32:38 -07004455 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004456}
4457
Eric Laurente552edb2014-03-10 17:42:56 -07004458// ---
4459
Mikhail Naganov560095b2020-03-05 16:28:57 -08004460void AudioPolicyManager::onNewAudioModulesAvailable()
4461{
Mikhail Naganova30ec142020-03-24 09:32:34 -07004462 DeviceVector newDevices;
4463 onNewAudioModulesAvailableInt(&newDevices);
4464 if (!newDevices.empty()) {
4465 nextAudioPortGeneration();
4466 mpClientInterface->onAudioPortListUpdate();
4467 }
4468}
4469
4470void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4471{
Mikhail Naganov560095b2020-03-05 16:28:57 -08004472 for (const auto& hwModule : mHwModulesAll) {
4473 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4474 continue;
4475 }
4476 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4477 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4478 ALOGW("could not open HW module %s", hwModule->getName());
4479 continue;
4480 }
4481 mHwModules.push_back(hwModule);
4482 // open all output streams needed to access attached devices
4483 // except for direct output streams that are only opened when they are actually
4484 // required by an app.
4485 // This also validates mAvailableOutputDevices list
4486 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4487 if (!outProfile->canOpenNewIo()) {
4488 ALOGE("Invalid Output profile max open count %u for profile %s",
4489 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4490 continue;
4491 }
4492 if (!outProfile->hasSupportedDevices()) {
4493 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4494 continue;
4495 }
4496 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4497 mTtsOutputAvailable = true;
4498 }
4499
4500 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4501 continue;
4502 }
4503 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4504 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4505 sp<DeviceDescriptor> supportedDevice = 0;
4506 if (supportedDevices.contains(mDefaultOutputDevice)) {
4507 supportedDevice = mDefaultOutputDevice;
4508 } else {
4509 // choose first device present in profile's SupportedDevices also part of
4510 // mAvailableOutputDevices.
4511 if (availProfileDevices.isEmpty()) {
4512 continue;
4513 }
4514 supportedDevice = availProfileDevices.itemAt(0);
4515 }
4516 if (!mOutputDevicesAll.contains(supportedDevice)) {
4517 continue;
4518 }
4519 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4520 mpClientInterface);
4521 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4522 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4523 AUDIO_STREAM_DEFAULT,
4524 AUDIO_OUTPUT_FLAG_NONE, &output);
4525 if (status != NO_ERROR) {
4526 ALOGW("Cannot open output stream for devices %s on hw module %s",
4527 supportedDevice->toString().c_str(), hwModule->getName());
4528 continue;
4529 }
4530 for (const auto &device : availProfileDevices) {
4531 // give a valid ID to an attached device once confirmed it is reachable
4532 if (!device->isAttached()) {
4533 device->attach(hwModule);
4534 mAvailableOutputDevices.add(device);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004535 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004536 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4537 }
4538 }
4539 if (mPrimaryOutput == 0 &&
4540 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4541 mPrimaryOutput = outputDesc;
4542 }
4543 addOutput(output, outputDesc);
4544 setOutputDevices(outputDesc,
4545 DeviceVector(supportedDevice),
4546 true,
4547 0,
4548 NULL);
4549 }
4550 // open input streams needed to access attached devices to validate
4551 // mAvailableInputDevices list
4552 for (const auto& inProfile : hwModule->getInputProfiles()) {
4553 if (!inProfile->canOpenNewIo()) {
4554 ALOGE("Invalid Input profile max open count %u for profile %s",
4555 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4556 continue;
4557 }
4558 if (!inProfile->hasSupportedDevices()) {
4559 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4560 continue;
4561 }
4562 // chose first device present in profile's SupportedDevices also part of
4563 // available input devices
4564 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4565 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4566 if (availProfileDevices.isEmpty()) {
4567 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4568 continue;
4569 }
4570 sp<AudioInputDescriptor> inputDesc =
4571 new AudioInputDescriptor(inProfile, mpClientInterface);
4572
4573 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4574 status_t status = inputDesc->open(nullptr,
4575 availProfileDevices.itemAt(0),
4576 AUDIO_SOURCE_MIC,
4577 AUDIO_INPUT_FLAG_NONE,
4578 &input);
4579 if (status != NO_ERROR) {
4580 ALOGW("Cannot open input stream for device %s on hw module %s",
4581 availProfileDevices.toString().c_str(),
4582 hwModule->getName());
4583 continue;
4584 }
4585 for (const auto &device : availProfileDevices) {
4586 // give a valid ID to an attached device once confirmed it is reachable
4587 if (!device->isAttached()) {
4588 device->attach(hwModule);
4589 device->importAudioPortAndPickAudioProfile(inProfile, true);
4590 mAvailableInputDevices.add(device);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004591 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004592 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4593 }
4594 }
4595 inputDesc->close();
4596 }
4597 }
4598}
4599
Eric Laurent98e38192018-02-15 18:31:53 -08004600void AudioPolicyManager::addOutput(audio_io_handle_t output,
4601 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004602{
Eric Laurent1c333e22014-05-20 10:48:17 -07004603 mOutputs.add(output, outputDesc);
jiabin12dc6b02019-10-01 09:38:30 -07004604 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004605 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004606 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004608}
4609
François Gaffie53615e22015-03-19 09:24:12 +01004610void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4611{
4612 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004613 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004614}
4615
Eric Laurent98e38192018-02-15 18:31:53 -08004616void AudioPolicyManager::addInput(audio_io_handle_t input,
4617 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004618{
Eric Laurent1c333e22014-05-20 10:48:17 -07004619 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004620 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004621}
Eric Laurente552edb2014-03-10 17:42:56 -07004622
François Gaffie11d30102018-11-02 16:09:09 +01004623status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004624 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004625 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004626{
François Gaffie11d30102018-11-02 16:09:09 +01004627 audio_devices_t deviceType = device->type();
jiabin6713a382019-09-12 16:29:15 -07004628 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004629 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004630
François Gaffie11d30102018-11-02 16:09:09 +01004631 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004632 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004633 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004634 }
Eric Laurente552edb2014-03-10 17:42:56 -07004635
Eric Laurent3b73df72014-03-11 09:06:29 -07004636 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004637 // first list already open outputs that can be routed to this device
4638 for (size_t i = 0; i < mOutputs.size(); i++) {
4639 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004640 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07004641 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004642 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4643 mOutputs.keyAt(i), device->toString().c_str());
4644 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004645 }
4646 }
4647 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004648 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004649 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004650 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4651 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004652 if (profile->supportsDevice(device)) {
4653 profiles.add(profile);
4654 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4655 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004656 }
4657 }
4658 }
4659
Eric Laurent7b279bb2015-12-14 10:18:23 -08004660 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004661
Eric Laurente552edb2014-03-10 17:42:56 -07004662 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004663 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004664 return BAD_VALUE;
4665 }
4666
4667 // open outputs for matching profiles if needed. Direct outputs are also opened to
4668 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4669 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004670 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004671
4672 // nothing to do if one output is already opened for this profile
4673 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004674 for (j = 0; j < outputs.size(); j++) {
4675 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004676 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004677 // matching profile: save the sample rates, format and channel masks supported
4678 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004679 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07004680 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004681 }
Eric Laurente552edb2014-03-10 17:42:56 -07004682 break;
4683 }
4684 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004685 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004686 continue;
4687 }
4688
Eric Laurent3974e3b2017-12-07 17:58:43 -08004689 if (!profile->canOpenNewIo()) {
4690 ALOGW("Max Output number %u already opened for this profile %s",
4691 profile->maxOpenCount, profile->getTagName().c_str());
4692 continue;
4693 }
4694
Eric Laurent83efe1c2017-07-09 16:51:08 -07004695 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabineaf09f02019-08-19 15:08:30 -07004696 deviceType, address.string(), profile.get(), profile->getName().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004697 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004698 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004699 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004700 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004701
Eric Laurentfe231122017-11-17 17:48:06 -08004702 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004703 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004704 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004705 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004706 mpClientInterface->setParameters(output, String8(param));
4707 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004708 }
François Gaffie11d30102018-11-02 16:09:09 +01004709 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004710 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004711 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004712 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004713 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004714 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004715 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004716 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004717 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4718 profile->pickAudioProfile(
4719 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004720 config.offload_info.sample_rate = config.sample_rate;
4721 config.offload_info.channel_mask = config.channel_mask;
4722 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004723
François Gaffie11d30102018-11-02 16:09:09 +01004724 status_t status = desc->open(&config, DeviceVector(device),
4725 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004726 AUDIO_OUTPUT_FLAG_NONE, &output);
4727 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004728 output = AUDIO_IO_HANDLE_NONE;
4729 }
Eric Laurentd4692962014-05-05 18:13:44 -07004730 }
4731
Eric Laurentcf2c0212014-07-25 16:20:43 -07004732 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004733 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004734 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004735 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004736 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix)
4737 == NO_ERROR) {
François Gaffieb141c522018-03-12 11:47:40 +01004738 policyMix->setOutput(desc);
Mikhail Naganovbfac5832019-03-05 16:55:28 -08004739 desc->mPolicyMix = policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004740 } else {
4741 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004742 address.string());
4743 }
François Gaffie036e1e92015-03-19 10:16:24 +01004744
Eric Laurent87ffa392015-05-22 10:32:38 -07004745 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4746 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004747 // no duplicated output for direct outputs and
4748 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004749 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004750
Eric Laurentd4692962014-05-05 18:13:44 -07004751 //TODO: configure audio effect output stage here
4752
4753 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004754 sp<SwAudioOutputDescriptor> dupOutputDesc =
4755 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4756 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4757 &duplicatedOutput);
4758 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004759 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004760 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004761 } else {
4762 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004763 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004764 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004765 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004767 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004768 }
Eric Laurente552edb2014-03-10 17:42:56 -07004769 }
4770 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004771 } else {
4772 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004773 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004774 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004775 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004776 profiles.removeAt(profile_index);
4777 profile_index--;
4778 } else {
4779 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004780 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004781 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07004782 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004783 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004784
François Gaffie11d30102018-11-02 16:09:09 +01004785 if (device_distinguishes_on_address(deviceType)) {
4786 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4787 device->toString().c_str());
4788 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4789 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004790 }
Eric Laurente552edb2014-03-10 17:42:56 -07004791 ALOGV("checkOutputsForDevice(): adding output %d", output);
4792 }
4793 }
4794
4795 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004796 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004797 return BAD_VALUE;
4798 }
Eric Laurentd4692962014-05-05 18:13:44 -07004799 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004800 // check if one opened output is not needed any more after disconnecting one device
4801 for (size_t i = 0; i < mOutputs.size(); i++) {
4802 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004803 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004804 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004805 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07004806 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004807 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004808 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004809 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4810 mOutputs.keyAt(i));
4811 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004812 }
Eric Laurente552edb2014-03-10 17:42:56 -07004813 }
4814 }
Eric Laurentd4692962014-05-05 18:13:44 -07004815 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004816 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004817 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4818 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004819 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004820 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004821 "clearing direct output profile %zu on module %s",
4822 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004823 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004824 }
4825 }
4826 }
4827 }
4828 return NO_ERROR;
4829}
4830
François Gaffie11d30102018-11-02 16:09:09 +01004831status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07004832 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07004833{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004834 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004835
François Gaffie11d30102018-11-02 16:09:09 +01004836 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004837 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004838 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004839 }
4840
Eric Laurentd4692962014-05-05 18:13:44 -07004841 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07004842 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004843 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004844 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004845 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004846 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004847 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004848 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004849
François Gaffie11d30102018-11-02 16:09:09 +01004850 if (profile->supportsDevice(device)) {
4851 profiles.add(profile);
4852 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4853 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004854 }
4855 }
4856 }
4857
Eric Laurent0dd51852019-04-19 18:18:58 -07004858 if (profiles.isEmpty()) {
4859 ALOGW("%s: No input profile available for device %s",
4860 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004861 return BAD_VALUE;
4862 }
4863
4864 // open inputs for matching profiles if needed. Direct inputs are also opened to
4865 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4866 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4867
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004869
Eric Laurentd4692962014-05-05 18:13:44 -07004870 // nothing to do if one input is already opened for this profile
4871 size_t input_index;
4872 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4873 desc = mInputs.valueAt(input_index);
4874 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004875 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07004876 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004877 }
Eric Laurentd4692962014-05-05 18:13:44 -07004878 break;
4879 }
4880 }
4881 if (input_index != mInputs.size()) {
4882 continue;
4883 }
4884
Eric Laurent3974e3b2017-12-07 17:58:43 -08004885 if (!profile->canOpenNewIo()) {
4886 ALOGW("Max Input number %u already opened for this profile %s",
4887 profile->maxOpenCount, profile->getTagName().c_str());
4888 continue;
4889 }
4890
Eric Laurentfe231122017-11-17 17:48:06 -08004891 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004892 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004893 status_t status = desc->open(nullptr,
4894 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004895 AUDIO_SOURCE_MIC,
4896 AUDIO_INPUT_FLAG_NONE,
4897 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004898
Eric Laurentcf2c0212014-07-25 16:20:43 -07004899 if (status == NO_ERROR) {
jiabin6713a382019-09-12 16:29:15 -07004900 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004901 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004902 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004903 mpClientInterface->setParameters(input, String8(param));
4904 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004905 }
François Gaffie11d30102018-11-02 16:09:09 +01004906 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004907 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004908 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004909 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004910 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004911 }
4912
Eric Laurent0dd51852019-04-19 18:18:58 -07004913 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004914 addInput(input, desc);
4915 }
4916 } // endif input != 0
4917
Eric Laurentcf2c0212014-07-25 16:20:43 -07004918 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004919 ALOGW("%s could not open input for device %s", __func__,
4920 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004921 profiles.removeAt(profile_index);
4922 profile_index--;
4923 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004924 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07004925 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004926 }
Eric Laurentd4692962014-05-05 18:13:44 -07004927 ALOGV("checkInputsForDevice(): adding input %d", input);
4928 }
4929 } // end scan profiles
4930
4931 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004932 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004933 return BAD_VALUE;
4934 }
4935 } else {
4936 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07004937 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004938 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004939 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004940 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004941 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004942 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004943 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004944 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4945 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004946 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004947 }
4948 }
4949 }
4950 } // end disconnect
4951
4952 return NO_ERROR;
4953}
4954
4955
Eric Laurente0720872014-03-11 09:30:41 -07004956void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004957{
4958 ALOGV("closeOutput(%d)", output);
4959
François Gaffie1c878552018-11-22 16:53:21 +01004960 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
4961 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004962 ALOGW("closeOutput() unknown output %d", output);
4963 return;
4964 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07004965 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01004966 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08004967
Eric Laurente552edb2014-03-10 17:42:56 -07004968 // look for duplicated outputs connected to the output being removed.
4969 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01004970 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
4971 if (dupOutput->isDuplicated() &&
4972 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
4973 sp<SwAudioOutputDescriptor> remainingOutput =
4974 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07004975 // As all active tracks on duplicated output will be deleted,
4976 // and as they were also referenced on the other output, the reference
4977 // count for their stream type must be adjusted accordingly on
4978 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01004979 const bool wasActive = remainingOutput->isActive();
4980 // Note: no-op on the closing output where all clients has already been set inactive
4981 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08004982 // stop() will be a no op if the output is still active but is needed in case all
4983 // active streams refcounts where cleared above
4984 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01004985 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004986 }
Eric Laurente552edb2014-03-10 17:42:56 -07004987 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4988 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4989
4990 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004991 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004992 }
4993 }
4994
Eric Laurent05b90f82014-08-27 15:32:29 -07004995 nextAudioPortGeneration();
4996
François Gaffie1c878552018-11-22 16:53:21 +01004997 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004998 if (index >= 0) {
4999 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005000 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5001 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005002 mAudioPatches.removeItemsAt(index);
5003 mpClientInterface->onAudioPatchListUpdate();
5004 }
5005
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005006 if (closingOutputWasActive) {
5007 closingOutput->stop();
5008 }
François Gaffie1c878552018-11-22 16:53:21 +01005009 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005010
François Gaffie53615e22015-03-19 09:24:12 +01005011 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005012 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005013
5014 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5015 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005016 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005017 bool directOutputOpen = false;
5018 for (size_t i = 0; i < mOutputs.size(); i++) {
5019 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5020 directOutputOpen = true;
5021 break;
5022 }
5023 }
5024 if (!directOutputOpen) {
5025 ALOGV("no direct outputs open, reset MSD patch");
5026 setMsdPatch();
5027 }
5028 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07005029
5030 cleanUpEffectsForIo(output);
Eric Laurent05b90f82014-08-27 15:32:29 -07005031}
5032
5033void AudioPolicyManager::closeInput(audio_io_handle_t input)
5034{
5035 ALOGV("closeInput(%d)", input);
5036
5037 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5038 if (inputDesc == NULL) {
5039 ALOGW("closeInput() unknown input %d", input);
5040 return;
5041 }
5042
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005044
François Gaffie11d30102018-11-02 16:09:09 +01005045 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005046 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005047 if (index >= 0) {
5048 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005049 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5050 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005051 mAudioPatches.removeItemsAt(index);
5052 mpClientInterface->onAudioPatchListUpdate();
5053 }
5054
Eric Laurentfe231122017-11-17 17:48:06 -08005055 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005056 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005057
François Gaffie11d30102018-11-02 16:09:09 +01005058 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5059 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005060 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
5061 SoundTrigger::setCaptureState(false);
5062 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07005063
5064 cleanUpEffectsForIo(input);
Eric Laurente552edb2014-03-10 17:42:56 -07005065}
5066
François Gaffie11d30102018-11-02 16:09:09 +01005067SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5068 const DeviceVector &devices,
5069 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005070{
5071 SortedVector<audio_io_handle_t> outputs;
5072
François Gaffie11d30102018-11-02 16:09:09 +01005073 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005074 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005075 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005076 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005077 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005078 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin12dc6b02019-10-01 09:38:30 -07005079 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005080 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005081 outputs.add(openOutputs.keyAt(i));
5082 }
5083 }
5084 return outputs;
5085}
5086
Mikhail Naganov37977152018-07-11 15:54:44 -07005087void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5088{
5089 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5090 // output is suspended before any tracks are moved to it
5091 checkA2dpSuspend();
5092 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005093 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005094 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005095 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005096 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005097 setMsdPatch();
5098 }
Mikhail Naganov37977152018-07-11 15:54:44 -07005099}
5100
François Gaffiec005e562018-11-06 15:04:49 +01005101bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5102 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005103{
François Gaffiec005e562018-11-06 15:04:49 +01005104 return mEngine->getProductStrategyForAttributes(lAttr) ==
5105 mEngine->getProductStrategyForAttributes(rAttr);
5106}
5107
5108void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5109{
5110 auto psId = mEngine->getProductStrategyForAttributes(attr);
5111
5112 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5113 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07005114
François Gaffie11d30102018-11-02 16:09:09 +01005115 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5116 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005117
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005118 // also take into account external policy-related changes: add all outputs which are
5119 // associated with policies in the "before" and "after" output vectors
François Gaffiec005e562018-11-06 15:04:49 +01005120 ALOGVV("%s(): policy related outputs", __func__);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005121 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005122 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005123 if (desc != 0 && desc->mPolicyMix != NULL) {
5124 srcOutputs.add(desc->mIoHandle);
5125 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
5126 }
5127 }
5128 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005129 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005130 if (desc != 0 && desc->mPolicyMix != NULL) {
5131 dstOutputs.add(desc->mIoHandle);
5132 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
5133 }
5134 }
5135
François Gaffiec005e562018-11-06 15:04:49 +01005136 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005137 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5138 // audio from invalidated tracks will be rendered when unmuting
5139 uint32_t maxLatency = 0;
5140 for (audio_io_handle_t srcOut : srcOutputs) {
5141 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
5142 if (desc != 0 && maxLatency < desc->latency()) {
5143 maxLatency = desc->latency();
5144 }
5145 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005146 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005147 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005148 std::to_string(srcOutputs[0]).c_str(),
5149 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005150 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005151 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005152 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
François Gaffiec005e562018-11-06 15:04:49 +01005153 if (desc != 0 && desc->isStrategyActive(psId)) {
5154 setStrategyMute(psId, true, desc);
5155 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005156 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005157 }
François Gaffiec005e562018-11-06 15:04:49 +01005158 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005159 if (source != 0){
5160 connectAudioSource(source);
5161 }
Eric Laurente552edb2014-03-10 17:42:56 -07005162 }
5163
François Gaffiec005e562018-11-06 15:04:49 +01005164 // Move effects associated to this stream from previous output to new output
5165 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005166 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005167 }
François Gaffiec005e562018-11-06 15:04:49 +01005168 // Move tracks associated to this stream (and linked) from previous output to new output
5169 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5170 mpClientInterface->invalidateStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005171 }
5172 }
5173}
5174
Eric Laurente0720872014-03-11 09:30:41 -07005175void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
François Gaffiec005e562018-11-06 15:04:49 +01005177 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5178 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5179 checkOutputForAttributes(attributes);
5180 }
Eric Laurente552edb2014-03-10 17:42:56 -07005181}
5182
Kevin Rocard153f92d2018-12-18 18:33:28 -08005183void AudioPolicyManager::checkSecondaryOutputs() {
5184 std::set<audio_stream_type_t> streamsToInvalidate;
5185 for (size_t i = 0; i < mOutputs.size(); i++) {
5186 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5187 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005188 sp<SwAudioOutputDescriptor> desc;
5189 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
Kevin Rocard94114a22019-04-01 19:38:23 -07005190 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5191 client->flags(), desc, &secondaryDescs);
5192 if (status != OK ||
5193 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005194 client->getSecondaryOutputs().end(),
5195 secondaryDescs.begin(), secondaryDescs.end())) {
5196 streamsToInvalidate.insert(client->stream());
5197 }
5198 }
5199 }
5200 for (audio_stream_type_t stream : streamsToInvalidate) {
5201 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5202 mpClientInterface->invalidateStream(stream);
5203 }
5204}
5205
Eric Laurente0720872014-03-11 09:30:41 -07005206void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005207{
François Gaffie53615e22015-03-19 09:24:12 +01005208 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005209 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005210 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005211 return;
5212 }
5213
Eric Laurent3a4311c2014-03-17 12:00:47 -07005214 bool isScoConnected =
jiabin12dc6b02019-10-01 09:38:30 -07005215 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5216 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurentf732e072016-08-03 19:30:28 -07005217
5218 // if suspended, restore A2DP output if:
5219 // ((SCO device is NOT connected) ||
5220 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
5221 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005222 //
Eric Laurentf732e072016-08-03 19:30:28 -07005223 // if not suspended, suspend A2DP output if:
5224 // (SCO device is connected) &&
5225 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
5226 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005227 //
5228 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005229 if (!isScoConnected ||
5230 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
5231 AUDIO_POLICY_FORCE_BT_SCO) &&
5232 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
5233 AUDIO_POLICY_FORCE_BT_SCO) &&
5234 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005235 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005236
5237 mpClientInterface->restoreOutput(a2dpOutput);
5238 mA2dpSuspended = false;
5239 }
5240 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005241 if (isScoConnected &&
5242 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
5243 AUDIO_POLICY_FORCE_BT_SCO) ||
5244 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
5245 AUDIO_POLICY_FORCE_BT_SCO) ||
5246 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005247 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005248
5249 mpClientInterface->suspendOutput(a2dpOutput);
5250 mA2dpSuspended = true;
5251 }
5252 }
5253}
5254
François Gaffie11d30102018-11-02 16:09:09 +01005255DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5256 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005257{
François Gaffie11d30102018-11-02 16:09:09 +01005258 DeviceVector devices;
5259
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005260 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 if (index >= 0) {
5262 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005263 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005264 ALOGV("%s device %s forced by patch %d", __func__,
5265 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5266 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 }
5268 }
5269
Dean Wheatley514b4312020-06-17 21:45:00 +10005270 // Do not retrieve engine device for outputs through MSD
5271 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5272 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5273 return outputDesc->devices();
5274 }
5275
Eric Laurent97ac8712018-07-27 18:59:02 -07005276 // Honor explicit routing requests only if no client using default routing is active on this
5277 // input: a specific app can not force routing for other apps by setting a preferred device.
5278 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005279 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005280 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005281 if (device != nullptr) {
5282 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005283 }
5284
François Gaffiea807ef92018-11-05 10:44:33 +01005285 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5286 // of setForceUse / Default Bus device here
5287 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5288 if (device != nullptr) {
5289 return DeviceVector(device);
5290 }
5291
François Gaffiec005e562018-11-06 15:04:49 +01005292 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5293 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5294 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005295
François Gaffiec005e562018-11-06 15:04:49 +01005296 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005297 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5298 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005299 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005300 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5301 outputDesc->isStrategyActive(productStrategy)) {
5302 // Retrieval of devices for voice DL is done on primary output profile, cannot
5303 // check the route (would force modifying configuration file for this profile)
5304 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5305 break;
5306 }
Eric Laurente552edb2014-03-10 17:42:56 -07005307 }
François Gaffiec005e562018-11-06 15:04:49 +01005308 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005309 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005310}
5311
François Gaffie11d30102018-11-02 16:09:09 +01005312sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5313 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005314{
François Gaffie11d30102018-11-02 16:09:09 +01005315 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005316
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005317 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 if (index >= 0) {
5319 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005320 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005321 ALOGV("getNewInputDevice() device %s forced by patch %d",
5322 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5323 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005324 }
5325 }
5326
Eric Laurent97ac8712018-07-27 18:59:02 -07005327 // Honor explicit routing requests only if no client using default routing is active on this
5328 // input: a specific app can not force routing for other apps by setting a preferred device.
5329 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005330 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5331 if (device != nullptr) {
5332 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005333 }
5334
Eric Laurentdc95a252018-04-12 12:46:56 -07005335 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005336 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005337 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5338 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5339 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005340 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005341 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005342 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005343 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005344
Eric Laurente552edb2014-03-10 17:42:56 -07005345 return device;
5346}
5347
Eric Laurent794fde22016-03-11 09:50:45 -08005348bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5349 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005350 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005351}
5352
Eric Laurente0720872014-03-11 09:30:41 -07005353audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005354 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005355 // getOutputDevicesForStream's behavior for invalid streams.
5356 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5357 // device for music stream), but we want to return the empty set.
5358 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 return AUDIO_DEVICE_NONE;
5360 }
François Gaffie11d30102018-11-02 16:09:09 +01005361 DeviceVector activeDevices;
5362 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01005363 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5364 curStream = (audio_stream_type_t) (curStream + 1)) {
5365 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005366 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 }
François Gaffiec005e562018-11-06 15:04:49 +01005368 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005369 devices.merge(curDevices);
5370 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005371 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005372 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005373 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005374 }
5375 }
Eric Laurente552edb2014-03-10 17:42:56 -07005376 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005377
Eric Laurentb0688d62018-08-14 15:49:18 -07005378 // Favor devices selected on active streams if any to report correct device in case of
5379 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005380 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005381 devices = activeDevices;
5382 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005383 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5384 and doesn't really need to.*/
jiabin12dc6b02019-10-01 09:38:30 -07005385 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005386 if (!speakerSafeDevices.isEmpty()) {
jiabin12dc6b02019-10-01 09:38:30 -07005387 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005388 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005389 }
jiabin12dc6b02019-10-01 09:38:30 -07005390 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5391 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005392}
5393
Eric Laurente0720872014-03-11 09:30:41 -07005394void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005395 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005396 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005397 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005398 updateDevicesAndOutputs();
5399 break;
5400 default:
5401 break;
5402 }
5403}
5404
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005405uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005406
5407 // skip beacon mute management if a dedicated TTS output is available
5408 if (mTtsOutputAvailable) {
5409 return 0;
5410 }
5411
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005412 switch(event) {
5413 case STARTING_OUTPUT:
5414 mBeaconMuteRefCount++;
5415 break;
5416 case STOPPING_OUTPUT:
5417 if (mBeaconMuteRefCount > 0) {
5418 mBeaconMuteRefCount--;
5419 }
5420 break;
5421 case STARTING_BEACON:
5422 mBeaconPlayingRefCount++;
5423 break;
5424 case STOPPING_BEACON:
5425 if (mBeaconPlayingRefCount > 0) {
5426 mBeaconPlayingRefCount--;
5427 }
5428 break;
5429 }
5430
5431 if (mBeaconMuteRefCount > 0) {
5432 // any playback causes beacon to be muted
5433 return setBeaconMute(true);
5434 } else {
5435 // no other playback: unmute when beacon starts playing, mute when it stops
5436 return setBeaconMute(mBeaconPlayingRefCount == 0);
5437 }
5438}
5439
5440uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5441 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5442 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5443 // keep track of muted state to avoid repeating mute/unmute operations
5444 if (mBeaconMuted != mute) {
5445 // mute/unmute AUDIO_STREAM_TTS on all outputs
5446 ALOGV("\t muting %d", mute);
5447 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005448 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005449 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005450 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07005451 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005452 const uint32_t latency = desc->latency() * 2;
5453 if (latency > maxLatency) {
5454 maxLatency = latency;
5455 }
5456 }
5457 mBeaconMuted = mute;
5458 return maxLatency;
5459 }
5460 return 0;
5461}
5462
Eric Laurente0720872014-03-11 09:30:41 -07005463void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005464{
François Gaffiec005e562018-11-06 15:04:49 +01005465 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005466 mPreviousOutputs = mOutputs;
5467}
5468
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005469uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005470 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005471 uint32_t delayMs)
5472{
5473 // mute/unmute strategies using an incompatible device combination
5474 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5475 // if unmuting, unmute only after the specified delay
5476 if (outputDesc->isDuplicated()) {
5477 return 0;
5478 }
5479
5480 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005481 DeviceVector devices = outputDesc->devices();
5482 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005483
François Gaffiec005e562018-11-06 15:04:49 +01005484 auto productStrategies = mEngine->getOrderedProductStrategies();
5485 for (const auto &productStrategy : productStrategies) {
5486 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5487 DeviceVector curDevices =
5488 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5489 curDevices = curDevices.filter(outputDesc->supportedDevices());
5490 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005491 bool doMute = false;
5492
François Gaffiec005e562018-11-06 15:04:49 +01005493 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005494 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005495 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5496 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005497 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005498 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005499 }
Eric Laurent99401132014-05-07 19:48:15 -07005500 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005501 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005502 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005503 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005504 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005505 continue;
5506 }
François Gaffiec005e562018-11-06 15:04:49 +01005507 ALOGVV("%s() %s (curDevice %s)", __func__,
5508 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5509 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5510 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005511 if (mute) {
5512 // FIXME: should not need to double latency if volume could be applied
5513 // immediately by the audioflinger mixer. We must account for the delay
5514 // between now and the next time the audioflinger thread for this output
5515 // will process a buffer (which corresponds to one buffer size,
5516 // usually 1/2 or 1/4 of the latency).
5517 if (muteWaitMs < desc->latency() * 2) {
5518 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005519 }
5520 }
5521 }
5522 }
5523 }
5524 }
5525
Eric Laurent99401132014-05-07 19:48:15 -07005526 // temporary mute output if device selection changes to avoid volume bursts due to
5527 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005528 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005529 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5530 // temporary mute duration is conservatively set to 4 times the reported latency
5531 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5532 if (muteWaitMs < tempMuteWaitMs) {
5533 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005534 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005535 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5536 // make sure that we do not start the temporary mute period too early in case of
5537 // delayed device change
5538 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5539 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005540 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005541 }
5542 }
5543
Eric Laurente552edb2014-03-10 17:42:56 -07005544 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5545 if (muteWaitMs > delayMs) {
5546 muteWaitMs -= delayMs;
5547 usleep(muteWaitMs * 1000);
5548 return muteWaitMs;
5549 }
5550 return 0;
5551}
5552
François Gaffie11d30102018-11-02 16:09:09 +01005553uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5554 const DeviceVector &devices,
5555 bool force,
5556 int delayMs,
5557 audio_patch_handle_t *patchHandle,
5558 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005559{
François Gaffie11d30102018-11-02 16:09:09 +01005560 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005561 uint32_t muteWaitMs;
5562
5563 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005564 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5565 nullptr /* patchHandle */, requiresMuteCheck);
5566 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5567 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005568 return muteWaitMs;
5569 }
Eric Laurente552edb2014-03-10 17:42:56 -07005570
5571 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005572 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005573 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005574
François Gaffie11d30102018-11-02 16:09:09 +01005575 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005576 // output profile or if new device is not supported AND previous device(s) is(are) still
5577 // available (otherwise reset device must be done on the output)
5578 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5579 !mAvailableOutputDevices.filter(prevDevices).empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005580 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5581 return 0;
5582 }
Eric Laurente552edb2014-03-10 17:42:56 -07005583
François Gaffie11d30102018-11-02 16:09:09 +01005584 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5585
5586 if (!filteredDevices.isEmpty()) {
5587 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005588 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005589
5590 // if the outputs are not materially active, there is no need to mute.
5591 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005592 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005593 } else {
5594 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5595 muteWaitMs = 0;
5596 }
Eric Laurente552edb2014-03-10 17:42:56 -07005597
5598 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005599 // the requested device is AUDIO_DEVICE_NONE
5600 // OR the requested device is the same as current device
5601 // AND force is not specified
5602 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005603 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005604 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005605 !force && outputDesc->getPatchHandle() != 0) {
5606 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5607 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005608 return muteWaitMs;
5609 }
5610
François Gaffie11d30102018-11-02 16:09:09 +01005611 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005612
Eric Laurente552edb2014-03-10 17:42:56 -07005613 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005614 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005615 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005616 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005617 PatchBuilder patchBuilder;
5618 patchBuilder.addSource(outputDesc);
5619 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5620 for (const auto &filteredDevice : filteredDevices) {
5621 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005622 }
5623
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005624 // Add half reported latency to delayMs when muteWaitMs is null in order
5625 // to avoid disordered sequence of muting volume and changing devices.
5626 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5627 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005628 }
Eric Laurente552edb2014-03-10 17:42:56 -07005629
5630 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005631 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005632
5633 return muteWaitMs;
5634}
5635
Eric Laurentc75307b2015-03-17 15:29:32 -07005636status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005637 int delayMs,
5638 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005639{
Eric Laurent6a94d692014-05-20 11:18:06 -07005640 ssize_t index;
5641 if (patchHandle) {
5642 index = mAudioPatches.indexOfKey(*patchHandle);
5643 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005644 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005645 }
5646 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005647 return INVALID_OPERATION;
5648 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005649 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005650 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005651 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005652 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01005653 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005654 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005655 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005656 return status;
5657}
5658
5659status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005660 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005661 bool force,
5662 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005663{
5664 status_t status = NO_ERROR;
5665
Eric Laurent1f2f2232014-06-02 12:01:23 -07005666 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005667 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5668 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005669
François Gaffie11d30102018-11-02 16:09:09 +01005670 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005671 PatchBuilder patchBuilder;
5672 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005673 // AUDIO_SOURCE_HOTWORD is for internal use only:
5674 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005675 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5676 auto result = usecase;
5677 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5678 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5679 }
5680 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005681 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005682 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005683 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005684 }
5685 }
5686 return status;
5687}
5688
Eric Laurent6a94d692014-05-20 11:18:06 -07005689status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5690 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005691{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005692 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005693 ssize_t index;
5694 if (patchHandle) {
5695 index = mAudioPatches.indexOfKey(*patchHandle);
5696 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005697 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005698 }
5699 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005700 return INVALID_OPERATION;
5701 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005702 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005703 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005704 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005705 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01005706 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005707 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005708 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005709 return status;
5710}
5711
François Gaffie11d30102018-11-02 16:09:09 +01005712sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005713 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005714 audio_format_t& format,
5715 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005716 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005717{
5718 // Choose an input profile based on the requested capture parameters: select the first available
5719 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005720 //
5721 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5722 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005723
Glenn Kasten730b9262018-03-29 15:01:26 -07005724 sp<IOProfile> firstInexact;
5725 uint32_t updatedSamplingRate = 0;
5726 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5727 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005728 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005729 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005730 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005731 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005732 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005733 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005734 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005735 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005736 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005737 &channelMask /*updatedChannelMask*/,
5738 // FIXME ugly cast
5739 (audio_output_flags_t) flags,
5740 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005741 return profile;
5742 }
François Gaffie11d30102018-11-02 16:09:09 +01005743 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005744 samplingRate,
5745 &updatedSamplingRate,
5746 format,
5747 &updatedFormat,
5748 channelMask,
5749 &updatedChannelMask,
5750 // FIXME ugly cast
5751 (audio_output_flags_t) flags,
5752 false /*exactMatchRequiredForInputFlags*/)) {
5753 firstInexact = profile;
5754 }
5755
Eric Laurente552edb2014-03-10 17:42:56 -07005756 }
5757 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005758 if (firstInexact != nullptr) {
5759 samplingRate = updatedSamplingRate;
5760 format = updatedFormat;
5761 channelMask = updatedChannelMask;
5762 return firstInexact;
5763 }
Eric Laurente552edb2014-03-10 17:42:56 -07005764 return NULL;
5765}
5766
François Gaffieaaac0fd2018-11-22 17:56:39 +01005767float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
5768 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005769 int index,
jiabin12dc6b02019-10-01 09:38:30 -07005770 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07005771{
jiabin12dc6b02019-10-01 09:38:30 -07005772 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005773
5774 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5775 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5776 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5777 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01005778 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5779 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
5780 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
5781 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005782 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005783
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005784 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01005785 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
5786 mOutputs.isActive(ringVolumeSrc, 0)) {
5787 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin12dc6b02019-10-01 09:38:30 -07005788 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005789 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005790 }
5791
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005792 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01005793 if ((volumeSource != callVolumeSrc && (isInCall() ||
5794 mOutputs.isActiveLocally(callVolumeSrc))) &&
5795 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
5796 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
5797 volumeSource == alarmVolumeSrc ||
5798 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
5799 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5800 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005801 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01005802 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin12dc6b02019-10-01 09:38:30 -07005803 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005804 const float maxVoiceVolDb =
jiabin12dc6b02019-10-01 09:38:30 -07005805 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005806 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07005807 // FIXME: Workaround for call screening applications until a proper audio mode is defined
5808 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
5809 // programmatically muted.
5810 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
5811 // 0. We don't want to cap volume when the system has programmatically muted the voice call
5812 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005813 bool exemptFromCapping =
5814 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
5815 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07005816 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
5817 volumeSource, volumeDb);
5818 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01005819 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
5820 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
5821 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005822 }
5823 }
Eric Laurente552edb2014-03-10 17:42:56 -07005824 // if a headset is connected, apply the following rules to ring tones and notifications
5825 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005826 // - always attenuate notifications volume by 6dB
5827 // - attenuate ring tones volume by 6dB unless music is not playing and
5828 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005829 // - if music is playing, always limit the volume to current music volume,
5830 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin12dc6b02019-10-01 09:38:30 -07005831 if (!Intersection(deviceTypes,
5832 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
5833 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
5834 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01005835 ((volumeSource == alarmVolumeSrc ||
5836 volumeSource == ringVolumeSrc) ||
5837 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
5838 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
5839 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5840 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
5841 curves.canBeMuted()) {
5842
Eric Laurente552edb2014-03-10 17:42:56 -07005843 // when the phone is ringing we must consider that music could have been paused just before
5844 // by the music application and behave as if music was active if the last music track was
5845 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005846 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005847 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01005848 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin12dc6b02019-10-01 09:38:30 -07005849 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01005850 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
5851 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01005852 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin12dc6b02019-10-01 09:38:30 -07005853 float musicVolDb = computeVolume(musicCurves,
5854 musicVolumeSrc,
5855 musicCurves.getVolumeIndex(musicDevice),
5856 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005857 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5858 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
5859 if (volumeDb > minVolDb) {
5860 volumeDb = minVolDb;
5861 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07005862 }
jiabin12dc6b02019-10-01 09:38:30 -07005863 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
5864 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005865 // on A2DP, also ensure notification volume is not too low compared to media when
5866 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01005867 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01005868 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin12dc6b02019-10-01 09:38:30 -07005869 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
5870 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005871 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5872 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005873 }
5874 }
jiabin12dc6b02019-10-01 09:38:30 -07005875 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01005876 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01005877 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005878 }
5879 }
5880
François Gaffie43c73442018-11-08 08:21:55 +01005881 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07005882}
5883
Eric Laurent3839bc02018-07-10 18:33:34 -07005884int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005885 VolumeSource fromVolumeSource,
5886 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07005887{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005888 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005889 return srcIndex;
5890 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005891 auto &srcCurves = getVolumeCurves(fromVolumeSource);
5892 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005893 float minSrc = (float)srcCurves.getVolumeIndexMin();
5894 float maxSrc = (float)srcCurves.getVolumeIndexMax();
5895 float minDst = (float)dstCurves.getVolumeIndexMin();
5896 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07005897
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005898 // preserve mute request or correct range
5899 if (srcIndex < minSrc) {
5900 if (srcIndex == 0) {
5901 return 0;
5902 }
5903 srcIndex = minSrc;
5904 } else if (srcIndex > maxSrc) {
5905 srcIndex = maxSrc;
5906 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005907 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5908}
5909
François Gaffieaaac0fd2018-11-22 17:56:39 +01005910status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
5911 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005912 int index,
5913 const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07005914 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005915 int delayMs,
5916 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005917{
François Gaffieaaac0fd2018-11-22 17:56:39 +01005918 // do not change actual attributes volume if the attributes is muted
5919 if (outputDesc->isMuted(volumeSource)) {
5920 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
5921 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07005922 return NO_ERROR;
5923 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005924 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5925 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
5926 bool isVoiceVolSrc = callVolSrc == volumeSource;
5927 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
5928
François Gaffie2110e042015-03-24 08:41:51 +01005929 audio_policy_forced_cfg_t forceUseForComm =
5930 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005931 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01005932 // if sco and call follow same curves, bypass forceUseForComm
5933 if ((callVolSrc != btScoVolSrc) &&
5934 ((isVoiceVolSrc && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5935 (isBtScoVolSrc && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO))) {
5936 ALOGV("%s cannot set volume group %d volume with force use = %d for comm", __func__,
5937 volumeSource, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005938 return INVALID_OPERATION;
5939 }
jiabin12dc6b02019-10-01 09:38:30 -07005940 if (deviceTypes.empty()) {
5941 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005942 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005943
jiabin12dc6b02019-10-01 09:38:30 -07005944 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
5945 if (outputDesc->isFixedVolume(deviceTypes) ||
HW Leeda7581e2018-05-22 18:31:34 +08005946 // Force VoIP volume to max for bluetooth SCO
jiabin12dc6b02019-10-01 09:38:30 -07005947
5948 ((isVoiceVolSrc || isBtScoVolSrc) &&
5949 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005950 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005951 }
jiabin12dc6b02019-10-01 09:38:30 -07005952 outputDesc->setVolume(
5953 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07005954
François Gaffieaaac0fd2018-11-22 17:56:39 +01005955 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07005956 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07005957 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01005958 if (isVoiceVolSrc) {
5959 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07005960 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07005961 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07005962 }
Eric Laurent18fba842016-03-31 14:41:26 -07005963 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005964 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5965 mLastVoiceVolume = voiceVolume;
5966 }
5967 }
Eric Laurente552edb2014-03-10 17:42:56 -07005968 return NO_ERROR;
5969}
5970
Eric Laurentc75307b2015-03-17 15:29:32 -07005971void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07005972 const DeviceTypeSet& deviceTypes,
5973 int delayMs,
5974 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005975{
Francois Gaffie5992b182020-03-20 14:55:14 +01005976 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01005977 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
5978 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
5979 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin12dc6b02019-10-01 09:38:30 -07005980 curves.getVolumeIndex(deviceTypes),
5981 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005982 }
5983}
5984
François Gaffiec005e562018-11-06 15:04:49 +01005985void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
5986 bool on,
5987 const sp<AudioOutputDescriptor>& outputDesc,
5988 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07005989 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07005990{
François Gaffieaaac0fd2018-11-22 17:56:39 +01005991 std::vector<VolumeSource> sourcesToMute;
5992 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
5993 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
5994 toString(attributes).c_str(), on, outputDesc->getId());
5995 VolumeSource source = toVolumeSource(attributes);
5996 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
5997 sourcesToMute.push_back(source);
5998 }
Eric Laurente552edb2014-03-10 17:42:56 -07005999 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006000 for (auto source : sourcesToMute) {
jiabin12dc6b02019-10-01 09:38:30 -07006001 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006002 }
6003
Eric Laurente552edb2014-03-10 17:42:56 -07006004}
6005
François Gaffieaaac0fd2018-11-22 17:56:39 +01006006void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6007 bool on,
6008 const sp<AudioOutputDescriptor>& outputDesc,
6009 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006010 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006011{
jiabin12dc6b02019-10-01 09:38:30 -07006012 if (deviceTypes.empty()) {
6013 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006014 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006015 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006016 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006017 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006018 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006019 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6020 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6021 AUDIO_POLICY_FORCE_NONE))) {
jiabin12dc6b02019-10-01 09:38:30 -07006022 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006023 }
6024 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006025 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6026 // ignored
6027 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006028 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006029 if (!outputDesc->isMuted(volumeSource)) {
6030 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006031 return;
6032 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006033 if (outputDesc->decMuteCount(volumeSource) == 0) {
6034 checkAndSetVolume(curves, volumeSource,
jiabin12dc6b02019-10-01 09:38:30 -07006035 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006036 outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006037 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006038 delayMs);
6039 }
6040 }
6041}
6042
François Gaffie53615e22015-03-19 09:24:12 +01006043bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6044{
François Gaffiec005e562018-11-06 15:04:49 +01006045 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006046 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6047 return true;
6048 }
6049
6050 // has known usage?
6051 switch (paa->usage) {
6052 case AUDIO_USAGE_UNKNOWN:
6053 case AUDIO_USAGE_MEDIA:
6054 case AUDIO_USAGE_VOICE_COMMUNICATION:
6055 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6056 case AUDIO_USAGE_ALARM:
6057 case AUDIO_USAGE_NOTIFICATION:
6058 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6059 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6060 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6061 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6062 case AUDIO_USAGE_NOTIFICATION_EVENT:
6063 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6064 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6065 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6066 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006067 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006068 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006069 break;
6070 default:
6071 return false;
6072 }
6073 return true;
6074}
6075
François Gaffie2110e042015-03-24 08:41:51 +01006076audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6077{
6078 return mEngine->getForceUse(usage);
6079}
6080
6081bool AudioPolicyManager::isInCall()
6082{
6083 return isStateInCall(mEngine->getPhoneState());
6084}
6085
6086bool AudioPolicyManager::isStateInCall(int state)
6087{
6088 return is_state_in_call(state);
6089}
6090
Eric Laurentd60560a2015-04-10 11:31:20 -07006091void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6092{
6093 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006094 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6095 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6096 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6097 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006098 }
6099 }
6100
6101 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6102 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6103 bool release = false;
6104 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6105 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6106 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6107 source->ext.device.type == deviceDesc->type()) {
6108 release = true;
6109 }
6110 }
6111 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6112 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6113 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6114 sink->ext.device.type == deviceDesc->type()) {
6115 release = true;
6116 }
6117 }
6118 if (release) {
François Gaffiead447b72019-11-18 15:50:22 +01006119 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6120 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006121 }
6122 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006123
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006124 mInputs.clearSessionRoutesForDevice(deviceDesc);
6125
Francois Gaffie716e1432019-01-14 16:58:59 +01006126 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006127}
6128
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006129void AudioPolicyManager::modifySurroundFormats(
6130 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006131 std::unordered_set<audio_format_t> enforcedSurround(
6132 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006133 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6134 for (const auto& pair : mConfig.getSurroundFormats()) {
6135 allSurround.insert(pair.first);
6136 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6137 }
Phil Burk09bc4612016-02-24 15:58:15 -08006138
6139 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6140 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006141 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006142 // This is the resulting set of formats depending on the surround mode:
6143 // 'all surround' = allSurround
6144 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6145 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6146 // 'manual surround' = mManualSurroundFormats
6147 // AUTO: formats v 'enforced surround'
6148 // ALWAYS: formats v 'all surround' v 'enforced surround'
6149 // NEVER: formats ^ 'non-surround'
6150 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006151
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006152 std::unordered_set<audio_format_t> formatSet;
6153 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6154 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006155 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006156 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006157 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006158 formatSet.insert(*formatIter);
6159 }
6160 }
6161 } else {
6162 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6163 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006164 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006165
jiabin81772902018-04-02 17:52:27 -07006166 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006167 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006168 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6169 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6170 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006171 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006172 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6173 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6174 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006175 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006176 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006177 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006178 for (const auto& format : formatSet) {
jiabin4562b3b2019-07-29 10:13:34 -07006179 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006180 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006181}
6182
jiabin4562b3b2019-07-29 10:13:34 -07006183void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6184 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006185 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6186 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6187
6188 // If NEVER, then remove support for channelMasks > stereo.
6189 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin4562b3b2019-07-29 10:13:34 -07006190 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6191 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006192 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6193 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin4562b3b2019-07-29 10:13:34 -07006194 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006195 } else {
jiabin4562b3b2019-07-29 10:13:34 -07006196 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006197 }
6198 }
jiabin81772902018-04-02 17:52:27 -07006199 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6200 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6201 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006202 bool supports5dot1 = false;
6203 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006204 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006205 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6206 supports5dot1 = true;
6207 break;
6208 }
6209 }
6210 // If not then add 5.1 support.
6211 if (!supports5dot1) {
jiabin4562b3b2019-07-29 10:13:34 -07006212 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006213 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006214 }
Phil Burk09bc4612016-02-24 15:58:15 -08006215 }
6216}
6217
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006218void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006219 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006220 AudioProfileVector &profiles)
6221{
6222 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006223 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006224
François Gaffie112b0af2015-11-19 16:13:25 +01006225 // Format MUST be checked first to update the list of AudioProfile
6226 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006227 reply = mpClientInterface->getParameters(
6228 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006229 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006230 AudioParameter repliedParameters(reply);
6231 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006232 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006233 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6234 return;
6235 }
Phil Burk09bc4612016-02-24 15:58:15 -08006236 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006237 if (device == AUDIO_DEVICE_OUT_HDMI
6238 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006239 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006240 }
jiabinb9733bc2019-09-10 14:27:34 -07006241 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006242 }
François Gaffie112b0af2015-11-19 16:13:25 +01006243
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006244 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin4562b3b2019-07-29 10:13:34 -07006245 ChannelMaskSet channelMasks;
6246 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006247 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006248 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006249
6250 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006251 reply = mpClientInterface->getParameters(
6252 ioHandle,
6253 requestedParameters.toString() + ";" +
6254 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006255 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006256 AudioParameter repliedParameters(reply);
6257 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006258 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006259 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006260 }
6261 }
6262 if (profiles.hasDynamicChannelsFor(format)) {
6263 reply = mpClientInterface->getParameters(ioHandle,
6264 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006265 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006266 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006267 AudioParameter repliedParameters(reply);
6268 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006269 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006270 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006271 if (device == AUDIO_DEVICE_OUT_HDMI
6272 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006273 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006274 }
François Gaffie112b0af2015-11-19 16:13:25 +01006275 }
6276 }
jiabinb9733bc2019-09-10 14:27:34 -07006277 addDynamicAudioProfileAndSort(
6278 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006279 }
6280}
Eric Laurentd60560a2015-04-10 11:31:20 -07006281
Mikhail Naganovdc769682018-05-04 15:34:08 -07006282status_t AudioPolicyManager::installPatch(const char *caller,
6283 audio_patch_handle_t *patchHandle,
6284 AudioIODescriptorInterface *ioDescriptor,
6285 const struct audio_patch *patch,
6286 int delayMs)
6287{
6288 ssize_t index = mAudioPatches.indexOfKey(
6289 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6290 *patchHandle : ioDescriptor->getPatchHandle());
6291 sp<AudioPatch> patchDesc;
6292 status_t status = installPatch(
6293 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6294 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01006295 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006296 }
6297 return status;
6298}
6299
6300status_t AudioPolicyManager::installPatch(const char *caller,
6301 ssize_t index,
6302 audio_patch_handle_t *patchHandle,
6303 const struct audio_patch *patch,
6304 int delayMs,
6305 uid_t uid,
6306 sp<AudioPatch> *patchDescPtr)
6307{
6308 sp<AudioPatch> patchDesc;
6309 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6310 if (index >= 0) {
6311 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006312 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006313 }
6314
6315 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6316 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6317 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6318 if (status == NO_ERROR) {
6319 if (index < 0) {
6320 patchDesc = new AudioPatch(patch, uid);
François Gaffiead447b72019-11-18 15:50:22 +01006321 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006322 } else {
6323 patchDesc->mPatch = *patch;
6324 }
François Gaffiead447b72019-11-18 15:50:22 +01006325 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006326 if (patchHandle) {
François Gaffiead447b72019-11-18 15:50:22 +01006327 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006328 }
6329 nextAudioPortGeneration();
6330 mpClientInterface->onAudioPatchListUpdate();
6331 }
6332 if (patchDescPtr) *patchDescPtr = patchDesc;
6333 return status;
6334}
6335
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006336} // namespace android