blob: beaa979b02126be0d97bdf1b63b5d72abbc1de9d [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>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganovedc0ae12020-04-14 14:47:01 -070051#include <system/audio_config.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
jiabin4562b3b2019-07-29 10:13:34 -070077template <typename T>
78bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
79{
80 if (left.size() != right.size()) {
81 return false;
82 }
83 for (size_t index = 0; index < right.size(); index++) {
84 if (left[index] != right[index]) {
85 return false;
86 }
87 }
88 return true;
89}
90
91template <typename T>
92bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
93{
94 return !(left == right);
95}
96
Eric Laurente552edb2014-03-10 17:42:56 -070097// ----------------------------------------------------------------------------
98// AudioPolicyInterface implementation
99// ----------------------------------------------------------------------------
100
Eric Laurente0720872014-03-11 09:30:41 -0700101status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800102 audio_policy_dev_state_t state,
103 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800104 const char *device_name,
105 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700106{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800107 status_t status = setDeviceConnectionStateInt(device, state, device_address,
108 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800109 nextAudioPortGeneration();
110 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800111}
112
François Gaffie11d30102018-11-02 16:09:09 +0100113void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
114 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200115{
jiabin6713a382019-09-12 16:29:15 -0700116 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200117 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovbb3b1602019-07-08 15:28:43 -0700118 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100119 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200120 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
121}
122
François Gaffie11d30102018-11-02 16:09:09 +0100123status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800124 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800125 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800126 const char *device_name,
127 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800128{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800129 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
130 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700131
132 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100133 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700134
François Gaffie11d30102018-11-02 16:09:09 +0100135 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800136 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100137 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganova30ec142020-03-24 09:32:34 -0700138 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
139}
Paul McLeane743a472015-01-28 11:07:31 -0800140
Mikhail Naganova30ec142020-03-24 09:32:34 -0700141status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
142 audio_policy_dev_state_t state)
143{
Eric Laurente552edb2014-03-10 17:42:56 -0700144 // handle output devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700145 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700146 SortedVector <audio_io_handle_t> outputs;
147
François Gaffie11d30102018-11-02 16:09:09 +0100148 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149
Eric Laurente552edb2014-03-10 17:42:56 -0700150 // save a copy of the opened output descriptors before any output is opened or closed
151 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
152 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700153 switch (state)
154 {
155 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800156 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700157 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100158 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700159 return INVALID_OPERATION;
160 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800161 ALOGV("%s() connecting device %s format %x",
Mikhail Naganova30ec142020-03-24 09:32:34 -0700162 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700163
Eric Laurente552edb2014-03-10 17:42:56 -0700164 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200165 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700166 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700167 }
168
François Gaffie44481e72016-04-20 07:49:57 +0200169 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
170 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100171 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200172
François Gaffie11d30102018-11-02 16:09:09 +0100173 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
174 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200175
Francois Gaffie716e1432019-01-14 16:58:59 +0100176 mHwModules.cleanUpForDevice(device);
177
François Gaffie11d30102018-11-02 16:09:09 +0100178 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700179 return INVALID_OPERATION;
180 }
François Gaffie2110e042015-03-24 08:41:51 +0100181
jiabin1c4794b2020-05-05 10:08:05 -0700182 // Populate encapsulation information when a output device is connected.
183 device->setEncapsulationInfoFromHal(mpClientInterface);
184
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700185 // outputs should never be empty here
186 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
187 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100188 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800189
Eric Laurent3ae5f312015-02-03 17:12:08 -0800190 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700192 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700193 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100194 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700195 return INVALID_OPERATION;
196 }
197
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700199
Paul McLeane743a472015-01-28 11:07:31 -0800200 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100201 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700202
Eric Laurente552edb2014-03-10 17:42:56 -0700203 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100204 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700205
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100206 mOutputs.clearSessionRoutesForDevice(device);
207
François Gaffie11d30102018-11-02 16:09:09 +0100208 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100209
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800210 // Reset active device codec
211 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
212
Eric Laurente552edb2014-03-10 17:42:56 -0700213 } break;
214
215 default:
François Gaffie11d30102018-11-02 16:09:09 +0100216 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700217 return BAD_VALUE;
218 }
219
Eric Laurent736a1022019-03-27 18:28:46 -0700220 // Propagate device availability to Engine
221 setEngineDeviceConnectionState(device, state);
222
Eric Laurentae970022019-01-29 14:25:04 -0800223 // No need to evaluate playback routing when connecting a remote submix
224 // output device used by a dynamic policy of type recorder as no
225 // playback use case is affected.
226 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganova30ec142020-03-24 09:32:34 -0700227 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800228 for (audio_io_handle_t output : outputs) {
229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800230 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
231 if (policyMix != nullptr
232 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganova30ec142020-03-24 09:32:34 -0700233 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800234 doCheckForDeviceAndOutputChanges = false;
235 break;
236 }
237 }
238 }
239
240 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700241 // outputs must be closed after checkOutputForAllStrategies() is executed
242 if (!outputs.isEmpty()) {
243 for (audio_io_handle_t output : outputs) {
244 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100245 // close unused outputs after device disconnection or direct outputs that have
246 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700247 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
248 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800249 (desc->mDirectOpenCount == 0))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700250 closeOutput(output);
251 }
Eric Laurente552edb2014-03-10 17:42:56 -0700252 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700253 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
254 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800257 };
258
259 if (doCheckForDeviceAndOutputChanges) {
260 checkForDeviceAndOutputChanges(checkCloseOutputs);
261 } else {
262 checkCloseOutputs();
263 }
Eric Laurente552edb2014-03-10 17:42:56 -0700264
Eric Laurent87ffa392015-05-22 10:32:38 -0700265 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
267 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700268 }
François Gaffie11d30102018-11-02 16:09:09 +0100269 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700270 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700271 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
272 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100273 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700274 // do not force device change on duplicated output because if device is 0, it will
275 // also force a device 0 for the two outputs it is duplicated to which may override
276 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100277 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100278 && !desc->isDuplicated()
Mikhail Naganova30ec142020-03-24 09:32:34 -0700279 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700280 // always force when disconnecting (a non-duplicated device)
281 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100282 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 }
Eric Laurente552edb2014-03-10 17:42:56 -0700284 }
285
Eric Laurentd60560a2015-04-10 11:31:20 -0700286 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100287 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700288 }
289
Eric Laurent72aa32f2014-05-30 18:51:48 -0700290 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700291 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700292 } // end if is output device
293
Eric Laurente552edb2014-03-10 17:42:56 -0700294 // handle input devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700295 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100296 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700297 switch (state)
298 {
299 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700300 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700301 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100302 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700303 return INVALID_OPERATION;
304 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700305
306 if (mAvailableInputDevices.add(device) < 0) {
307 return NO_MEMORY;
308 }
309
François Gaffie44481e72016-04-20 07:49:57 +0200310 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
311 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100312 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200313
Eric Laurent0dd51852019-04-19 18:18:58 -0700314 if (checkInputsForDevice(device, state) != NO_ERROR) {
315 mAvailableInputDevices.remove(device);
316
François Gaffie11d30102018-11-02 16:09:09 +0100317 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100318
319 mHwModules.cleanUpForDevice(device);
320
Eric Laurentd4692962014-05-05 18:13:44 -0700321 return INVALID_OPERATION;
322 }
323
Eric Laurentd4692962014-05-05 18:13:44 -0700324 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700325
326 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700327 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100329 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700330 return INVALID_OPERATION;
331 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700332
François Gaffie11d30102018-11-02 16:09:09 +0100333 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700334
335 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100336 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700337
François Gaffie11d30102018-11-02 16:09:09 +0100338 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700339
340 checkInputsForDevice(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700341 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700342
343 default:
François Gaffie11d30102018-11-02 16:09:09 +0100344 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700345 return BAD_VALUE;
346 }
347
Eric Laurent736a1022019-03-27 18:28:46 -0700348 // Propagate device availability to Engine
349 setEngineDeviceConnectionState(device, state);
350
Eric Laurent0dd51852019-04-19 18:18:58 -0700351 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700352 // As the input device list can impact the output device selection, update
353 // getDeviceForStrategy() cache
354 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700355
Eric Laurent87ffa392015-05-22 10:32:38 -0700356 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100357 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
358 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700359 }
360
Eric Laurentd60560a2015-04-10 11:31:20 -0700361 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100362 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700363 }
364
Eric Laurentb52c1522014-05-20 11:27:36 -0700365 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700366 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700367 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700368
François Gaffie11d30102018-11-02 16:09:09 +0100369 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700370 return BAD_VALUE;
371}
372
Eric Laurent736a1022019-03-27 18:28:46 -0700373void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
374 audio_policy_dev_state_t state) {
375
376 // the Engine does not have to know about remote submix devices used by dynamic audio policies
377 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
378 return;
379 }
380 mEngine->setDeviceConnectionState(device, state);
381}
382
383
Eric Laurente0720872014-03-11 09:30:41 -0700384audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100385 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700386{
Eric Laurent634b7142016-04-20 13:48:02 -0700387 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800388 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
389 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700390 (strlen(device_address) != 0)/*matchAddress*/);
391
392 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100393 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700394 device, device_address);
395 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
396 }
François Gaffie53615e22015-03-19 09:24:12 +0100397
Eric Laurent3a4311c2014-03-17 12:00:47 -0700398 DeviceVector *deviceVector;
399
Eric Laurente552edb2014-03-10 17:42:56 -0700400 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700402 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 deviceVector = &mAvailableInputDevices;
404 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100405 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700407 }
Eric Laurent634b7142016-04-20 13:48:02 -0700408
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800409 return (deviceVector->getDevice(
410 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700411 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800412}
413
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800414status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
415 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800416 const char *device_name,
417 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800418{
419 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700420 String8 reply;
421 AudioParameter param;
422 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800423
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800424 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
425 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800426
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800427 // connect/disconnect only 1 device at a time
428 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
429
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800430 // Check if the device is currently connected
jiabin12dc6b02019-10-01 09:38:30 -0700431 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800432 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800433 // Nothing to do: device is not connected
434 return NO_ERROR;
435 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800436 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800437
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700438 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800439 // configure codecs.
440 // Handle two specific cases by sending a set parameter to
441 // configure A2DP codecs. No need to toggle device state.
442 // Case 1: A2DP active device switches from primary to primary
443 // module
444 // Case 2: A2DP device config changes on primary module.
jiabin12dc6b02019-10-01 09:38:30 -0700445 if (audio_is_a2dp_out_device(device)) {
446 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800447 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
448 if (availablePrimaryOutputDevices().contains(devDesc) &&
449 (module != 0 && module->getHandle() == primaryHandle)) {
450 reply = mpClientInterface->getParameters(
451 AUDIO_IO_HANDLE_NONE,
452 String8(AudioParameter::keyReconfigA2dpSupported));
453 AudioParameter repliedParameters(reply);
454 repliedParameters.getInt(
455 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
456 if (isReconfigA2dpSupported) {
457 const String8 key(AudioParameter::keyReconfigA2dp);
458 param.add(key, String8("true"));
459 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
460 devDesc->setEncodedFormat(encodedFormat);
461 return NO_ERROR;
462 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700463 }
464 }
cnx421bd2dcc42020-07-11 14:58:44 +0800465 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
466 for (size_t i = 0; i < mOutputs.size(); i++) {
467 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
468 // mute media strategies and delay device switch by the largest
469 // This avoid sending the music tail into the earpiece or headset.
470 setStrategyMute(musicStrategy, true, desc);
471 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
472 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
473 nullptr, true /*fromCache*/).types());
474 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800475 // Toggle the device state: UNAVAILABLE -> AVAILABLE
476 // This will force reading again the device configuration
477 status = setDeviceConnectionState(device,
478 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800479 device_address, device_name,
480 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800481 if (status != NO_ERROR) {
482 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
483 status);
484 return status;
485 }
486
487 status = setDeviceConnectionState(device,
488 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800489 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800490 if (status != NO_ERROR) {
491 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
492 status);
493 return status;
494 }
495
496 return NO_ERROR;
497}
498
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800499status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
500 std::vector<audio_format_t> *formats)
501{
502 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800503 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800504 std::unordered_set<audio_format_t> formatSet;
505 sp<HwModule> primaryModule =
506 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Lata5b023eb2019-07-03 11:20:36 -0700507 if (primaryModule == nullptr) {
508 ALOGE("%s() unable to get primary module", __func__);
509 return NO_INIT;
510 }
jiabin12dc6b02019-10-01 09:38:30 -0700511 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
512 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800513 for (const auto& device : declaredDevices) {
514 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800515 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800516 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800517 return status;
518}
519
François Gaffie11d30102018-11-02 16:09:09 +0100520uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700521{
522 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100523 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700524 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700525
jiabin12dc6b02019-10-01 09:38:30 -0700526 if(!hasPrimaryOutput() ||
527 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700528 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700529 }
François Gaffie11d30102018-11-02 16:09:09 +0100530 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
531
Francois Gaffie716e1432019-01-14 16:58:59 +0100532 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100533 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100534 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100535
536 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100537 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700538
539 // release existing RX patch if any
540 if (mCallRxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100541 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700542 mCallRxPatch.clear();
543 }
544 // release TX patch if any
545 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100546 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 mCallTxPatch.clear();
548 }
549
François Gaffie9eb18552018-11-05 10:33:26 +0100550 auto telephonyRxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700551 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100552 auto telephonyTxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700553 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100554 // retrieve Rx Source and Tx Sink device descriptors
555 sp<DeviceDescriptor> rxSourceDevice =
556 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
557 String8(),
558 AUDIO_FORMAT_DEFAULT);
559 sp<DeviceDescriptor> txSinkDevice =
560 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
561 String8(),
562 AUDIO_FORMAT_DEFAULT);
563
564 // RX and TX Telephony device are declared by Primary Audio HAL
565 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
566 (telephonyRxModule->getHalVersionMajor() >= 3)) {
567 if (rxSourceDevice == 0 || txSinkDevice == 0) {
568 // RX / TX Telephony device(s) is(are) not currently available
569 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
570 return muteWaitMs;
571 }
François Gaffiead447b72019-11-18 15:50:22 +0100572 // createAudioPatchInternal now supports both HW / SW bridging
573 createRxPatch = true;
574 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100575 } else {
576 // If the RX device is on the primary HW module, then use legacy routing method for
577 // voice calls via setOutputDevice() on primary output.
578 // Otherwise, create two audio patches for TX and RX path.
579 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
580 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700581 // If the TX device is also on the primary HW module, setOutputDevice() will take care
582 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100583 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
584 (txSinkDevice != 0);
585 }
586 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
587 // Otherwise, create two audio patches for TX and RX path.
588 if (!createRxPatch) {
589 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700590 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100591 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800592
593 // If the TX device is on the primary HW module but RX device is
594 // on other HW module, SinkMetaData of telephony input should handle it
595 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700596 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700597 if (createTxPatch) { // create TX path audio patch
François Gaffiead447b72019-11-18 15:50:22 +0100598 // terminate active capture if on the same HW module as the call TX source device
599 // FIXME: would be better to refine to only inputs whose profile connects to the
600 // call TX device but this information is not in the audio patch and logic here must be
601 // symmetric to the one in startInput()
602 for (const auto& activeDesc : mInputs.getActiveInputs()) {
603 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
604 closeActiveClients(activeDesc);
605 }
606 }
François Gaffie9eb18552018-11-05 10:33:26 +0100607 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800608 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700609
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800610 return muteWaitMs;
611}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700612
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800613sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100614 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700615 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616
François Gaffie11d30102018-11-02 16:09:09 +0100617 if (device == nullptr) {
618 return nullptr;
619 }
François Gaffiead447b72019-11-18 15:50:22 +0100620
François Gaffieafd4cea2019-11-18 15:50:22 +0100621 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800622 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100623 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800624 addSource(mAvailableInputDevices.getDevice(
625 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800626 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100627 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800628 addSink(mAvailableOutputDevices.getDevice(
629 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800630 }
631
François Gaffiead447b72019-11-18 15:50:22 +0100632 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
633 status_t status =
634 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
635 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
636 if (status != NO_ERROR || index < 0) {
637 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
638 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800639 }
François Gaffiead447b72019-11-18 15:50:22 +0100640 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800641}
642
Mikhail Naganov100f0122018-11-29 11:22:16 -0800643bool AudioPolicyManager::isDeviceOfModule(
644 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
645 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
646 if (module != 0) {
647 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
648 .indexOf(devDesc) != NAME_NOT_FOUND
649 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
650 .indexOf(devDesc) != NAME_NOT_FOUND;
651 }
652 return false;
653}
654
Eric Laurente0720872014-03-11 09:30:41 -0700655void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700656{
657 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100658 // store previous phone state for management of sonification strategy below
659 int oldState = mEngine->getPhoneState();
660
661 if (mEngine->setPhoneState(state) != NO_ERROR) {
662 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700663 return;
664 }
François Gaffie2110e042015-03-24 08:41:51 +0100665 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700666 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700667 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700668 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800669 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700670 }
671
François Gaffie2110e042015-03-24 08:41:51 +0100672 /**
673 * Switching to or from incall state or switching between telephony and VoIP lead to force
674 * routing command.
675 */
Eric Laurent74b71512019-11-06 17:21:57 -0800676 bool force = ((isStateInCall(oldState) != isStateInCall(state))
677 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700678
679 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700680 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700681
Eric Laurente552edb2014-03-10 17:42:56 -0700682 int delayMs = 0;
683 if (isStateInCall(state)) {
684 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100685 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
686 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700687 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700688 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700689 // mute media and sonification strategies and delay device switch by the largest
690 // latency of any output where either strategy is active.
691 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100692 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
693 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
694 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700695 (delayMs < (int)desc->latency()*2)) {
696 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700697 }
François Gaffiec005e562018-11-06 15:04:49 +0100698 setStrategyMute(musicStrategy, true, desc);
699 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
700 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
701 nullptr, true /*fromCache*/).types());
702 setStrategyMute(sonificationStrategy, true, desc);
703 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
704 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
705 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700706 }
707 }
708
Eric Laurent87ffa392015-05-22 10:32:38 -0700709 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100710 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700711 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100712 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700713 // force routing command to audio hardware when ending call
714 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100715 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
716 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700717 }
Eric Laurente552edb2014-03-10 17:42:56 -0700718
Eric Laurent87ffa392015-05-22 10:32:38 -0700719 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100720 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700721 } else if (oldState == AUDIO_MODE_IN_CALL) {
722 if (mCallRxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100723 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700724 mCallRxPatch.clear();
725 }
726 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100727 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700728 mCallTxPatch.clear();
729 }
François Gaffie11d30102018-11-02 16:09:09 +0100730 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700731 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100732 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700734 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700735
736 // reevaluate routing on all outputs in case tracks have been started during the call
737 for (size_t i = 0; i < mOutputs.size(); i++) {
738 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100739 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700740 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100741 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700742 }
743 }
744
Eric Laurente552edb2014-03-10 17:42:56 -0700745 if (isStateInCall(state)) {
746 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700747 // force reevaluating accessibility routing when call starts
748 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750
751 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100752 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
753 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700754}
755
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700756audio_mode_t AudioPolicyManager::getPhoneState() {
757 return mEngine->getPhoneState();
758}
759
Eric Laurente0720872014-03-11 09:30:41 -0700760void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100761 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700762{
François Gaffie2110e042015-03-24 08:41:51 +0100763 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700764 if (config == mEngine->getForceUse(usage)) {
765 return;
766 }
Eric Laurente552edb2014-03-10 17:42:56 -0700767
François Gaffie2110e042015-03-24 08:41:51 +0100768 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
769 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
770 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700771 }
François Gaffie2110e042015-03-24 08:41:51 +0100772 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
773 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
774 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700775
776 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700777 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800778
Eric Laurent22fcda22019-05-17 16:28:47 -0700779 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
780 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
781 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
782 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
783 }
784
Eric Laurentdc462862016-07-19 12:29:53 -0700785 //FIXME: workaround for truncated touch sounds
786 // to be removed when the problem is handled by system UI
787 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700788 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
789 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
790 }
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -0700791
792 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurentcca11ce2020-11-25 15:31:27 +0100793 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700794}
795
Eric Laurente0720872014-03-11 09:30:41 -0700796void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700797{
798 ALOGV("setSystemProperty() property %s, value %s", property, value);
799}
800
Michael Chana94fbb22018-04-24 14:31:19 +1000801// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
802// search to profiles for direct outputs.
803sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100804 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000805 uint32_t samplingRate,
806 audio_format_t format,
807 audio_channel_mask_t channelMask,
808 audio_output_flags_t flags,
809 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700810{
Michael Chana94fbb22018-04-24 14:31:19 +1000811 if (directOnly) {
812 // only retain flags that will drive the direct output profile selection
813 // if explicitly requested
814 static const uint32_t kRelevantFlags =
815 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lata97a47182019-07-03 11:15:33 -0700816 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000817 flags =
818 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
819 }
Eric Laurent861a6282015-05-18 15:40:16 -0700820
821 sp<IOProfile> profile;
822
Mikhail Naganovd4120142017-12-06 15:49:22 -0800823 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800824 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100825 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700826 samplingRate, NULL /*updatedSamplingRate*/,
827 format, NULL /*updatedFormat*/,
828 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700829 flags)) {
830 continue;
831 }
832 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100833 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700834 continue;
835 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800836 // reject profiles if connected device does not support codec
jiabin12dc6b02019-10-01 09:38:30 -0700837 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800838 continue;
839 }
Michael Chana94fbb22018-04-24 14:31:19 +1000840 if (!directOnly) return curProfile;
841 // when searching for direct outputs, if several profiles are compatible, give priority
842 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100843 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700844 continue;
845 }
846 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100847 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700848 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700849 }
Eric Laurente552edb2014-03-10 17:42:56 -0700850 }
851 }
Eric Laurent861a6282015-05-18 15:40:16 -0700852 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700853}
854
Eric Laurentf4e63452017-11-06 19:31:46 +0000855audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700856{
François Gaffiec005e562018-11-06 15:04:49 +0100857 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800858
859 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
860 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
861 // format, flags, etc. This may result in some discrepancy for functions that utilize
862 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
863 // and AudioSystem::getOutputSamplingRate().
864
François Gaffie11d30102018-11-02 16:09:09 +0100865 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700866 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700867
François Gaffie11d30102018-11-02 16:09:09 +0100868 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
869 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000870 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871}
872
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700873status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
874 const audio_attributes_t *srcAttr,
875 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700876{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700877 if (srcAttr != NULL) {
878 if (!isValidAttributes(srcAttr)) {
879 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
880 __func__,
881 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
882 srcAttr->tags);
883 return BAD_VALUE;
884 }
885 *dstAttr = *srcAttr;
886 } else {
887 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
888 ALOGE("%s: invalid stream type", __func__);
889 return BAD_VALUE;
890 }
François Gaffiec005e562018-11-06 15:04:49 +0100891 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700892 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700893
894 // Only honor audibility enforced when required. The client will be
895 // forced to reconnect if the forced usage changes.
896 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganove3b59ac2020-10-01 15:08:13 -0700897 dstAttr->flags = static_cast<audio_flags_mask_t>(
898 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700899 }
900
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700901 return NO_ERROR;
902}
903
Kevin Rocard153f92d2018-12-18 18:33:28 -0800904status_t AudioPolicyManager::getOutputForAttrInt(
905 audio_attributes_t *resultAttr,
906 audio_io_handle_t *output,
907 audio_session_t session,
908 const audio_attributes_t *attr,
909 audio_stream_type_t *stream,
910 uid_t uid,
911 const audio_config_t *config,
912 audio_output_flags_t *flags,
913 audio_port_handle_t *selectedDeviceId,
914 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700915 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800916 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700917{
François Gaffiec005e562018-11-06 15:04:49 +0100918 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100919 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100920 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100921 const sp<DeviceDescriptor> requestedDevice =
922 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
923
Eric Laurent8a1095a2019-11-08 14:44:16 -0800924 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700925 status_t status = getAudioAttributes(resultAttr, attr, *stream);
926 if (status != NO_ERROR) {
927 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700928 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700929 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganove3b59ac2020-10-01 15:08:13 -0700930 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700931 }
François Gaffiec005e562018-11-06 15:04:49 +0100932 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700933
François Gaffiec005e562018-11-06 15:04:49 +0100934 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
935 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700936
Kevin Rocard153f92d2018-12-18 18:33:28 -0800937 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
938 // otherwise, fallback to the dynamic policies, if none match, query the engine.
939 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700940 sp<AudioPolicyMix> primaryMix;
941 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700942 if (status != OK) {
943 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800944 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700945
Kevin Rocard153f92d2018-12-18 18:33:28 -0800946 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700947 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800948
949 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700950 if ((usePrimaryOutputFromPolicyMixes
951 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800952 && !audio_is_linear_pcm(config->format)) {
953 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800954 return BAD_VALUE;
955 }
956 if (usePrimaryOutputFromPolicyMixes) {
François Gaffiec005e562018-11-06 15:04:49 +0100957 sp<DeviceDescriptor> deviceDesc =
Eric Laurentc529cf62020-04-17 18:19:10 -0700958 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
959 primaryMix->mDeviceAddress,
François Gaffiec005e562018-11-06 15:04:49 +0100960 AUDIO_FORMAT_DEFAULT);
Eric Laurentc529cf62020-04-17 18:19:10 -0700961 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -0700962 if (deviceDesc != nullptr
963 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700964 audio_io_handle_t newOutput;
965 status = openDirectOutput(
966 *stream, session, config,
967 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
968 DeviceVector(deviceDesc), &newOutput);
969 if (status != NO_ERROR) {
970 policyDesc = nullptr;
971 } else {
972 policyDesc = mOutputs.valueFor(newOutput);
973 primaryMix->setOutput(policyDesc);
974 }
975 }
976 if (policyDesc != nullptr) {
977 policyDesc->mPolicyMix = primaryMix;
978 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -0800979 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -0800980
Jean-Michel Trivif41599b2020-01-07 14:22:08 -0800981 ALOGV("getOutputForAttr() returns output %d", *output);
982 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
983 *outputType = API_OUT_MIX_PLAYBACK;
984 } else {
985 *outputType = API_OUTPUT_LEGACY;
986 }
987 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -0800988 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700989 }
François Gaffiec005e562018-11-06 15:04:49 +0100990 // Virtual sources must always be dynamicaly or explicitly routed
991 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
992 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
993 return BAD_VALUE;
994 }
995 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
996 // in order to let the choice of the order to future vendor engine
997 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700998
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700999 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001000 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001001 }
1002
Nadav Barb2f18162018-07-18 13:01:53 +03001003 // Set incall music only if device was explicitly set, and fallback to the device which is
1004 // chosen by the engine if not.
1005 // FIXME: provide a more generic approach which is not device specific and move this back
1006 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001007 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin12dc6b02019-10-01 09:38:30 -07001008 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001009 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001010 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001011 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001012 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001013 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001014 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001015 }
1016 }
1017
François Gaffiec005e562018-11-06 15:04:49 +01001018 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1019 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1020 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001021
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001022 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001023 if (!msdDevices.isEmpty()) {
1024 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001025 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1026 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1027 ALOGV("%s() Using MSD devices %s instead of devices %s",
1028 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1029 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001030 } else {
1031 *output = AUDIO_IO_HANDLE_NONE;
1032 }
1033 }
1034 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001035 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001036 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001037 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001038 if (*output == AUDIO_IO_HANDLE_NONE) {
1039 return INVALID_OPERATION;
1040 }
Paul McLeanaa981192015-03-21 09:55:15 -07001041
François Gaffiec005e562018-11-06 15:04:49 +01001042 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001043
Eric Laurent8a1095a2019-11-08 14:44:16 -08001044 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1045 *outputType = API_OUTPUT_TELEPHONY_TX;
1046 } else {
1047 *outputType = API_OUTPUT_LEGACY;
1048 }
1049
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001050 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1051
1052 return NO_ERROR;
1053}
1054
1055status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1056 audio_io_handle_t *output,
1057 audio_session_t session,
1058 audio_stream_type_t *stream,
1059 uid_t uid,
1060 const audio_config_t *config,
1061 audio_output_flags_t *flags,
1062 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001063 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001064 std::vector<audio_io_handle_t> *secondaryOutputs,
1065 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001066{
1067 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1068 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1069 return INVALID_OPERATION;
1070 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001071 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001072 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001073 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001074 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001075 const sp<DeviceDescriptor> requestedDevice =
1076 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1077
1078 // Prevent from storing invalid requested device id in clients
1079 const audio_port_handle_t sanitizedRequestedPortId =
1080 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1081 *selectedDeviceId = sanitizedRequestedPortId;
1082
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001083 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001084 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001085 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001086 if (status != NO_ERROR) {
1087 return status;
1088 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001089 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001090 if (secondaryOutputs != nullptr) {
1091 for (auto &secondaryMix : secondaryMixes) {
1092 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1093 if (outputDesc != nullptr &&
1094 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1095 secondaryOutputs->push_back(outputDesc->mIoHandle);
1096 weakSecondaryOutputDescs.push_back(outputDesc);
1097 }
1098 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001099 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001100
Eric Laurent8fc147b2018-07-22 19:13:55 -07001101 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001102 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001103 .format = config->format,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001104 };
jiabindff2a4f2019-09-10 14:29:54 -07001105 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001106
Eric Laurentc209fe42020-06-05 18:11:23 -07001107 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001108 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001109 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001110 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001111 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001112 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001113 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001114 std::move(weakSecondaryOutputDescs),
1115 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001116 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001117
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001118 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1119 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001120
Eric Laurente83b55d2014-11-14 10:06:21 -08001121 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001122}
1123
Eric Laurentc529cf62020-04-17 18:19:10 -07001124status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1125 audio_session_t session,
1126 const audio_config_t *config,
1127 audio_output_flags_t flags,
1128 const DeviceVector &devices,
1129 audio_io_handle_t *output) {
1130
1131 *output = AUDIO_IO_HANDLE_NONE;
1132
1133 // skip direct output selection if the request can obviously be attached to a mixed output
1134 // and not explicitly requested
1135 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1136 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1137 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1138 return NAME_NOT_FOUND;
1139 }
1140
1141 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1142 // This prevents creating an offloaded track and tearing it down immediately after start
1143 // when audioflinger detects there is an active non offloadable effect.
1144 // FIXME: We should check the audio session here but we do not have it in this context.
1145 // This may prevent offloading in rare situations where effects are left active by apps
1146 // in the background.
1147 sp<IOProfile> profile;
1148 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1149 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1150 profile = getProfileForOutput(
1151 devices, config->sample_rate, config->format, config->channel_mask,
1152 flags, true /* directOnly */);
1153 }
1154
1155 if (profile == nullptr) {
1156 return NAME_NOT_FOUND;
1157 }
1158
1159 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1160 for (size_t i = 0; i < mOutputs.size(); i++) {
1161 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1162 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1163 // reuse direct output if currently open by the same client
1164 // and configured with same parameters
1165 if ((config->sample_rate == desc->getSamplingRate()) &&
1166 (config->format == desc->getFormat()) &&
1167 (config->channel_mask == desc->getChannelMask()) &&
1168 (session == desc->mDirectClientSession)) {
1169 desc->mDirectOpenCount++;
1170 ALOGI("%s reusing direct output %d for session %d", __func__,
1171 mOutputs.keyAt(i), session);
1172 *output = mOutputs.keyAt(i);
1173 return NO_ERROR;
1174 }
1175 }
1176 }
1177
1178 if (!profile->canOpenNewIo()) {
1179 return NAME_NOT_FOUND;
1180 }
1181
1182 sp<SwAudioOutputDescriptor> outputDesc =
1183 new SwAudioOutputDescriptor(profile, mpClientInterface);
1184
1185 String8 address = getFirstDeviceAddress(devices);
1186
1187 // MSD patch may be using the only output stream that can service this request. Release
1188 // MSD patch to prioritize this request over any active output on MSD.
1189 AudioPatchCollection msdPatches = getMsdPatches();
1190 for (size_t i = 0; i < msdPatches.size(); i++) {
1191 const auto& patch = msdPatches[i];
1192 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1193 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1194 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1195 devices.containsDeviceWithType(sink->ext.device.type) &&
1196 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1197 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1198 releaseAudioPatch(patch->getHandle(), mUidCached);
1199 break;
1200 }
1201 }
1202 }
1203
1204 status_t status = outputDesc->open(config, devices, stream, flags, output);
1205
1206 // only accept an output with the requested parameters
1207 if (status != NO_ERROR ||
1208 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1209 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1210 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1211 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1212 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1213 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1214 config->channel_mask, outputDesc->getChannelMask());
1215 if (*output != AUDIO_IO_HANDLE_NONE) {
1216 outputDesc->close();
1217 }
1218 // fall back to mixer output if possible when the direct output could not be open
1219 if (audio_is_linear_pcm(config->format) &&
1220 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1221 return NAME_NOT_FOUND;
1222 }
1223 *output = AUDIO_IO_HANDLE_NONE;
1224 return BAD_VALUE;
1225 }
1226 outputDesc->mDirectOpenCount = 1;
1227 outputDesc->mDirectClientSession = session;
1228
1229 addOutput(*output, outputDesc);
1230 mPreviousOutputs = mOutputs;
1231 ALOGV("%s returns new direct output %d", __func__, *output);
1232 mpClientInterface->onAudioPortListUpdate();
1233 return NO_ERROR;
1234}
1235
François Gaffie11d30102018-11-02 16:09:09 +01001236audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1237 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001238 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001239 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001240 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001241 audio_output_flags_t *flags,
1242 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001243{
Andy Hungc88b0642018-04-27 15:42:35 -07001244 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001245
jiabine375d412019-02-26 12:54:53 -08001246 // Discard haptic channel mask when forcing muting haptic channels.
1247 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganove3b59ac2020-10-01 15:08:13 -07001248 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1249 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001250
Eric Laurente552edb2014-03-10 17:42:56 -07001251 // open a direct output if required by specified parameters
1252 //force direct flag if offload flag is set: offloading implies a direct output stream
1253 // and all common behaviors are driven by checking only the direct flag
1254 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001255 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1256 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001257 }
Nadav Bar766fb022018-01-07 12:18:03 +02001258 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1259 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001260 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001261 // only allow deep buffering for music stream type
1262 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001263 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001264 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001265 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001266 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1267 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001268 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001269 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001270 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001271 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001272 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001273 audio_is_linear_pcm(config->format) &&
1274 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001275 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001276 AUDIO_OUTPUT_FLAG_DIRECT);
1277 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001278 }
Eric Laurente552edb2014-03-10 17:42:56 -07001279
Eric Laurentc529cf62020-04-17 18:19:10 -07001280 audio_config_t directConfig = *config;
1281 directConfig.channel_mask = channelMask;
1282 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1283 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001284 return output;
1285 }
1286
Eric Laurent14cbfca2016-03-17 09:42:16 -07001287 // A request for HW A/V sync cannot fallback to a mixed output because time
1288 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001289 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001290 return AUDIO_IO_HANDLE_NONE;
1291 }
1292
Eric Laurente552edb2014-03-10 17:42:56 -07001293 // ignoring channel mask due to downmix capability in mixer
1294
1295 // open a non direct output
1296
1297 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001298 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001299 // get which output is suitable for the specified stream. The actual
1300 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001301 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001302
Eric Laurent8838a382014-09-08 16:44:28 -07001303 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001304 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabine375d412019-02-26 12:54:53 -08001305 output = selectOutput(outputs, *flags, config->format, channelMask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001306 }
François Gaffie11d30102018-11-02 16:09:09 +01001307 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001308 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001309 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001310
Eric Laurente552edb2014-03-10 17:42:56 -07001311 return output;
1312}
1313
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001314sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001315 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1316 mAvailableInputDevices);
1317 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1318}
1319
1320DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1321 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1322 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001323}
1324
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001325const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1326 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001327 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1328 if (msdModule != 0) {
1329 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1330 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1331 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1332 const struct audio_port_config *source = &patch->mPatch.sources[j];
1333 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1334 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffiead447b72019-11-18 15:50:22 +01001335 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001336 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001337 }
1338 }
1339 }
1340 return msdPatches;
1341}
1342
François Gaffie11d30102018-11-02 16:09:09 +01001343status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001344 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1345{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001346 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001347 if (msdModule == nullptr) {
1348 ALOGE("%s() unable to get MSD module", __func__);
1349 return NO_INIT;
1350 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001351 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001353 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001354 return NO_INIT;
1355 }
1356 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1357 if (inputProfiles.isEmpty()) {
1358 ALOGE("%s() no input profiles for MSD module", __func__);
1359 return NO_INIT;
1360 }
1361 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1362 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001363 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001364 return NO_INIT;
1365 }
1366 AudioProfileVector msdProfiles;
1367 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1368 for (const auto &inProfile : inputProfiles) {
1369 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabinb9733bc2019-09-10 14:27:34 -07001370 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001371 }
1372 }
1373 AudioProfileVector deviceProfiles;
1374 for (const auto &outProfile : outputProfiles) {
1375 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabinb9733bc2019-09-10 14:27:34 -07001376 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001377 }
1378 }
1379 struct audio_config_base bestSinkConfig;
jiabinb9733bc2019-09-10 14:27:34 -07001380 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001381 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabinb9733bc2019-09-10 14:27:34 -07001382 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001383 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001384 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1385 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001386 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387 }
1388 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1389 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1390 sinkConfig->format = bestSinkConfig.format;
1391 // For encoded streams force direct flag to prevent downstream mixing.
1392 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1393 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001394 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1395 // For formats compatible with IEC61937 encapsulation, assume that
1396 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1397 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1398 // raw and IEC61937 framed streams.
1399 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1400 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1401 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001402 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1403 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1404 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1405 sourceConfig->format = bestSinkConfig.format;
1406 // Copy input stream directly without any processing (e.g. resampling).
1407 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1408 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1409 if (hwAvSync) {
1410 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1411 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1412 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1413 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1414 }
1415 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1416 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1417 sinkConfig->config_mask |= config_mask;
1418 sourceConfig->config_mask |= config_mask;
1419 return NO_ERROR;
1420}
1421
François Gaffie11d30102018-11-02 16:09:09 +01001422PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001423{
1424 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001425 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001426 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1427 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1428 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1429 // For now, we just forcefully try with HwAvSync first.
1430 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1431 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1432 getBestMsdAudioProfileFor(
1433 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1434 if (res == NO_ERROR) {
1435 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1436 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1437 }
1438 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1439 " supporting PCM format conversion.", __func__);
1440 return patchBuilder;
1441}
1442
François Gaffie11d30102018-11-02 16:09:09 +01001443status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1444 sp<DeviceDescriptor> device = outputDevice;
1445 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001446 // Use media strategy for unspecified output device. This should only
1447 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1448 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001449 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1450 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001451 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1452 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001453 }
François Gaffie11d30102018-11-02 16:09:09 +01001454 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1455 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001456 const struct audio_patch* patch = patchBuilder.patch();
1457 const AudioPatchCollection msdPatches = getMsdPatches();
1458 if (!msdPatches.isEmpty()) {
1459 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1460 "The current MSD prototype only supports one output patch");
1461 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1462 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1463 return NO_ERROR;
1464 }
François Gaffiead447b72019-11-18 15:50:22 +01001465 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001466 }
1467 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1468 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1469 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1470 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001471 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1472 device->toString().c_str(), patch->sources[0].format,
1473 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001474 return status;
1475}
1476
Eric Laurente0720872014-03-11 09:30:41 -07001477audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001478 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001479 audio_format_t format,
1480 audio_channel_mask_t channelMask,
1481 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001482{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001483 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1484 "%s called with format %#x", __func__, format);
1485
1486 // Flags disqualifying an output: the match must happen before calling selectOutput()
1487 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1488 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1489
1490 // Flags expressing a functional request: must be honored in priority over
1491 // other criteria
1492 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1493 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1494 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1495 // Flags expressing a performance request: have lower priority than serving
1496 // requested sampling rate or channel mask
1497 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1498 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1499 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1500
1501 const audio_output_flags_t functionalFlags =
1502 (audio_output_flags_t)(flags & kFunctionalFlags);
1503 const audio_output_flags_t performanceFlags =
1504 (audio_output_flags_t)(flags & kPerformanceFlags);
1505
1506 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1507
Eric Laurente552edb2014-03-10 17:42:56 -07001508 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001509 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001510 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001511 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001512 // 2: the output with the highest number of requested functional flags
1513 // 3: the output supporting the exact channel mask
1514 // 4: the output with a higher channel count than requested
1515 // 5: the output with a higher sampling rate than requested
1516 // 6: the output with the highest number of requested performance flags
1517 // 7: the output with the bit depth the closest to the requested one
1518 // 8: the primary output
1519 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001520
Eric Laurent16c66dd2019-05-01 17:54:10 -07001521 // matching criteria values in priority order for best matching output so far
1522 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001523
Eric Laurent16c66dd2019-05-01 17:54:10 -07001524 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1525 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1526 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001527
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001528 for (audio_io_handle_t output : outputs) {
1529 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001530 // matching criteria values in priority order for current output
1531 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001532
Eric Laurent16c66dd2019-05-01 17:54:10 -07001533 if (outputDesc->isDuplicated()) {
1534 continue;
1535 }
1536 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1537 continue;
1538 }
Eric Laurent8838a382014-09-08 16:44:28 -07001539
Eric Laurent16c66dd2019-05-01 17:54:10 -07001540 // If haptic channel is specified, use the haptic output if present.
1541 // When using haptic output, same audio format and sample rate are required.
1542 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabineaf09f02019-08-19 15:08:30 -07001543 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001544 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1545 continue;
1546 }
1547 if (outputHapticChannelCount >= hapticChannelCount
jiabineaf09f02019-08-19 15:08:30 -07001548 && format == outputDesc->getFormat()
1549 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001550 currentMatchCriteria[0] = outputHapticChannelCount;
1551 }
1552
1553 // functional flags match
1554 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1555
1556 // channel mask and channel count match
jiabineaf09f02019-08-19 15:08:30 -07001557 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1558 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001559 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1560 channelCount <= outputChannelCount) {
1561 if ((audio_channel_mask_get_representation(channelMask) ==
jiabineaf09f02019-08-19 15:08:30 -07001562 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1563 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001564 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001565 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001566 currentMatchCriteria[3] = outputChannelCount;
1567 }
1568
1569 // sampling rate match
1570 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabineaf09f02019-08-19 15:08:30 -07001571 samplingRate <= outputDesc->getSamplingRate()) {
1572 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001573 }
1574
1575 // performance flags match
1576 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1577
1578 // format match
1579 if (format != AUDIO_FORMAT_INVALID) {
1580 currentMatchCriteria[6] =
jiabindff2a4f2019-09-10 14:29:54 -07001581 PolicyAudioPort::kFormatDistanceMax -
1582 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001583 }
1584
1585 // primary output match
1586 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1587
1588 // compare match criteria by priority then value
1589 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1590 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1591 bestMatchCriteria = currentMatchCriteria;
1592 bestOutput = output;
1593
1594 std::stringstream result;
1595 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1596 std::ostream_iterator<int>(result, " "));
1597 ALOGV("%s new bestOutput %d criteria %s",
1598 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001599 }
1600 }
1601
Eric Laurent16c66dd2019-05-01 17:54:10 -07001602 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001603}
1604
Eric Laurent8fc147b2018-07-22 19:13:55 -07001605status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001606{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001607 ALOGV("%s portId %d", __FUNCTION__, portId);
1608
1609 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1610 if (outputDesc == 0) {
1611 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001612 return BAD_VALUE;
1613 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001614 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001615
Eric Laurent8fc147b2018-07-22 19:13:55 -07001616 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001617 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001618
Eric Laurent733ce942017-12-07 12:18:25 -08001619 status_t status = outputDesc->start();
1620 if (status != NO_ERROR) {
1621 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001622 }
1623
Eric Laurent97ac8712018-07-27 18:59:02 -07001624 uint32_t delayMs;
1625 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001626
1627 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001628 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001629 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001630 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001631 if (delayMs != 0) {
1632 usleep(delayMs * 1000);
1633 }
1634
1635 return status;
1636}
1637
Eric Laurent97ac8712018-07-27 18:59:02 -07001638status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1639 const sp<TrackClientDescriptor>& client,
1640 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001641{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001642 // cannot start playback of STREAM_TTS if any other output is being used
1643 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001644
1645 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001646 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001647 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001648 auto clientStrategy = client->strategy();
1649 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001650 if (stream == AUDIO_STREAM_TTS) {
1651 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001652 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001653 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001654 return INVALID_OPERATION;
1655 } else {
1656 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1657 }
1658 } else {
1659 // some playback other than beacon starts
1660 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1661 }
1662
Eric Laurent77305a62016-07-25 16:39:22 -07001663 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001664 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001665 bool force = !outputDesc->isActive() &&
1666 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001667
François Gaffie11d30102018-11-02 16:09:09 +01001668 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001669 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001670 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001671 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001672 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001673 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001674 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001675 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001676 } else {
1677 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001678 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001679 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1680 AUDIO_FORMAT_DEFAULT);
1681 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1682 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001683 }
1684
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001685 // requiresMuteCheck is false when we can bypass mute strategy.
1686 // It covers a common case when there is no materially active audio
1687 // and muting would result in unnecessary delay and dropped audio.
1688 const uint32_t outputLatencyMs = outputDesc->latency();
1689 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1690
Eric Laurente552edb2014-03-10 17:42:56 -07001691 // increment usage count for this stream on the requested output:
1692 // NOTE that the usage count is the same for duplicated output and hardware output which is
1693 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001694 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001695
1696 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001697 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1698 client->isPreferredDeviceForExclusiveUse()) {
1699 // Preferred device may be exclusive, use only if no other active clients on this output
1700 devices = DeviceVector(
1701 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1702 } else {
1703 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1704 }
François Gaffie11d30102018-11-02 16:09:09 +01001705 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001706 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001707 }
1708 }
Eric Laurente552edb2014-03-10 17:42:56 -07001709
François Gaffiec005e562018-11-06 15:04:49 +01001710 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001711 selectOutputForMusicEffects();
1712 }
1713
François Gaffie1c878552018-11-22 16:53:21 +01001714 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001715 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001716 if (devices.isEmpty()) {
1717 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001718 }
François Gaffiec005e562018-11-06 15:04:49 +01001719 bool shouldWait =
1720 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1721 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1722 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001723 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001724 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001725 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001726 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001727 // An output has a shared device if
1728 // - managed by the same hw module
1729 // - supports the currently selected device
1730 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001731 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001732
Eric Laurent77305a62016-07-25 16:39:22 -07001733 // force a device change if any other output is:
1734 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001735 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001736 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001737 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001738 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001739 // change the device currently selected by the other output.
1740 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001741 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001742 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001743 force = true;
1744 }
1745 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001746 // a notification so that audio focus effect can propagate, or that a mute/unmute
1747 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001748 const uint32_t latencyMs = desc->latency();
1749 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1750
1751 if (shouldWait && isActive && (waitMs < latencyMs)) {
1752 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001753 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001754
1755 // Require mute check if another output is on a shared device
1756 // and currently active to have proper drain and avoid pops.
1757 // Note restoring AudioTracks onto this output needs to invoke
1758 // a volume ramp if there is no mute.
1759 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001760 }
1761 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001762
1763 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001764 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001765
Eric Laurente552edb2014-03-10 17:42:56 -07001766 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001767 auto &curves = getVolumeCurves(client->attributes());
1768 checkAndSetVolume(curves, client->volumeSource(),
1769 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001770 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001771 outputDesc->devices().types(), 0 /*delay*/,
1772 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001773
1774 // update the outputs if starting an output with a stream that can affect notification
1775 // routing
1776 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001777
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001778 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001779 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001780 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1781 }
Eric Laurentdc462862016-07-19 12:29:53 -07001782
1783 if (waitMs > muteWaitMs) {
1784 *delayMs = waitMs - muteWaitMs;
1785 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001786
1787 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1788 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1789 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1790 // change occurs after the MixerThread starts and causes a stream volume
1791 // glitch.
1792 //
1793 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001794 }
Eric Laurentdc462862016-07-19 12:29:53 -07001795
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001796 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin12dc6b02019-10-01 09:38:30 -07001797 mEngine->getForceUse(
1798 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001799 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001800 }
1801
Eric Laurent97ac8712018-07-27 18:59:02 -07001802 // Automatically enable the remote submix input when output is started on a re routing mix
1803 // of type MIX_TYPE_RECORDERS
jiabin12dc6b02019-10-01 09:38:30 -07001804 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1805 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001806 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1807 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1808 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001809 "remote-submix",
1810 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001811 }
1812
Eric Laurente552edb2014-03-10 17:42:56 -07001813 return NO_ERROR;
1814}
1815
Eric Laurent8fc147b2018-07-22 19:13:55 -07001816status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001817{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001818 ALOGV("%s portId %d", __FUNCTION__, portId);
1819
1820 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1821 if (outputDesc == 0) {
1822 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001823 return BAD_VALUE;
1824 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001825 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001826
Eric Laurent97ac8712018-07-27 18:59:02 -07001827 ALOGV("stopOutput() output %d, stream %d, session %d",
1828 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001829
Eric Laurent97ac8712018-07-27 18:59:02 -07001830 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001831
Eric Laurent733ce942017-12-07 12:18:25 -08001832 if (status == NO_ERROR ) {
1833 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001834 }
1835 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001836}
1837
Eric Laurent97ac8712018-07-27 18:59:02 -07001838status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1839 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001840{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001841 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001842 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001843 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001844
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001845 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1846
François Gaffie1c878552018-11-22 16:53:21 +01001847 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1848 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001849 // Automatically disable the remote submix input when output is stopped on a
1850 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001851 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin12dc6b02019-10-01 09:38:30 -07001852 if (isSingleDeviceType(
1853 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001854 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001855 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001856 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1857 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001858 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001859 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001860 }
1861 }
1862 bool forceDeviceUpdate = false;
1863 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001864 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001865 forceDeviceUpdate = true;
1866 }
1867
Eric Laurente552edb2014-03-10 17:42:56 -07001868 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001869 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001870
Eric Laurente552edb2014-03-10 17:42:56 -07001871 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001872 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001873 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001874 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001875 // delay the device switch by twice the latency because stopOutput() is executed when
1876 // the track stop() command is received and at that time the audio track buffer can
1877 // still contain data that needs to be drained. The latency only covers the audio HAL
1878 // and kernel buffers. Also the latency does not always include additional delay in the
1879 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001880 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001881
1882 // force restoring the device selection on other active outputs if it differs from the
1883 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001884 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001885 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001886 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001887 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001888 desc->isActive() &&
1889 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001890 (newDevices != desc->devices())) {
1891 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1892 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001893
François Gaffie11d30102018-11-02 16:09:09 +01001894 setOutputDevices(desc, newDevices2, force, delayMs);
1895
Eric Laurent57de36c2016-09-28 16:59:11 -07001896 // re-apply device specific volume if not done by setOutputDevice()
1897 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001898 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001899 }
Eric Laurente552edb2014-03-10 17:42:56 -07001900 }
1901 }
1902 // update the outputs if stopping one with a stream that can affect notification routing
1903 handleNotificationRoutingForStream(stream);
1904 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001905
1906 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1907 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001908 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001909 }
1910
François Gaffiec005e562018-11-06 15:04:49 +01001911 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001912 selectOutputForMusicEffects();
1913 }
Eric Laurente552edb2014-03-10 17:42:56 -07001914 return NO_ERROR;
1915 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001916 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001917 return INVALID_OPERATION;
1918 }
1919}
1920
Eric Laurent8fc147b2018-07-22 19:13:55 -07001921void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001922{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001923 ALOGV("%s portId %d", __FUNCTION__, portId);
1924
1925 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1926 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001927 // If an output descriptor is closed due to a device routing change,
1928 // then there are race conditions with releaseOutput from tracks
1929 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1930 // destroyed shortly thereafter.
1931 //
1932 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001933 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001934 return;
1935 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001936
1937 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001938
Eric Laurent8fc147b2018-07-22 19:13:55 -07001939 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1940 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001941 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001942 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001943 return;
1944 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001945 if (--outputDesc->mDirectOpenCount == 0) {
1946 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001947 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001948 }
1949 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001950 // stopOutput() needs to be successfully called before releaseOutput()
1951 // otherwise there may be inaccurate stream reference counts.
1952 // This is checked in outputDesc->removeClient below.
1953 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001954}
1955
Eric Laurentcaf7f482014-11-25 17:50:47 -08001956status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1957 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001958 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001959 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001960 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001961 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001962 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001963 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001964 input_type_t *inputType,
1965 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001966{
François Gaffiec005e562018-11-06 15:04:49 +01001967 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1968 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1969 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001970
Eric Laurentad2e7b92017-09-14 20:06:42 -07001971 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001972 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001973 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001974 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001975 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976 sp<AudioInputDescriptor> inputDesc;
1977 sp<RecordClientDescriptor> clientDesc;
1978 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001979 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001980
1981 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1982 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1983 return INVALID_OPERATION;
1984 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001985
Francois Gaffie716e1432019-01-14 16:58:59 +01001986 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1987 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001988 }
1989
Paul McLean466dc8e2015-04-17 13:15:36 -06001990 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001991 sp<DeviceDescriptor> explicitRoutingDevice =
1992 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001993
Eric Laurentad2e7b92017-09-14 20:06:42 -07001994 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1995 // possible
1996 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1997 *input != AUDIO_IO_HANDLE_NONE) {
1998 ssize_t index = mInputs.indexOfKey(*input);
1999 if (index < 0) {
2000 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2001 status = BAD_VALUE;
2002 goto error;
2003 }
2004 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002005 RecordClientVector clients = inputDesc->getClientsForSession(session);
2006 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002007 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2008 status = BAD_VALUE;
2009 goto error;
2010 }
2011 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2012 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002013 // corresponds to a new client and is only permitted from the same UID.
2014 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002015 if (clients.size() > 1) {
2016 for (const auto& client : clients) {
2017 // The client map is ordered by key values (portId) and portIds are allocated
2018 // incrementaly. So the first client in this list is the one opened by audio flinger
2019 // when the mmap stream is created and should be ignored as it does not correspond
2020 // to an actual client
2021 if (client == *clients.cbegin()) {
2022 continue;
2023 }
2024 if (uid != client->uid() && !client->isSilenced()) {
2025 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2026 uid, client->portId(), client->uid());
2027 status = INVALID_OPERATION;
2028 goto error;
2029 }
Eric Laurent331679c2018-04-16 17:03:16 -07002030 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002031 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002032 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002033 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002034
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002036 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002037 }
2038
2039 *input = AUDIO_IO_HANDLE_NONE;
2040 *inputType = API_INPUT_INVALID;
2041
Francois Gaffie716e1432019-01-14 16:58:59 +01002042 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002043
Francois Gaffie716e1432019-01-14 16:58:59 +01002044 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2045 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2046 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002047 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002048 ALOGW("%s could not find input mix for attr %s",
2049 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002050 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002051 }
jiabinc1de2df2019-05-07 14:26:40 -07002052 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2053 String8(attr->tags + strlen("addr=")),
2054 AUDIO_FORMAT_DEFAULT);
2055 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002056 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002057 __func__, attributes.source, attributes.tags);
2058 status = BAD_VALUE;
2059 goto error;
2060 }
2061
Kevin Rocard25f9b052019-02-27 15:08:54 -08002062 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2063 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2064 } else {
2065 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2066 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002067 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002068 if (explicitRoutingDevice != nullptr) {
2069 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002070 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002071 // Prevent from storing invalid requested device id in clients
2072 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002073 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002074 }
François Gaffie11d30102018-11-02 16:09:09 +01002075 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002076 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002077 status = BAD_VALUE;
2078 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002079 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002080 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002081 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2082 // there is an external policy, but this input is attached to a mix of recorders,
2083 // meaning it receives audio injected into the framework, so the recorder doesn't
2084 // know about it and is therefore considered "legacy"
2085 *inputType = API_INPUT_LEGACY;
2086 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002087 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002088 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002089 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002090 } else {
2091 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002092 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002093
Eric Laurent599c7582015-12-07 18:05:55 -08002094 }
2095
François Gaffiec005e562018-11-06 15:04:49 +01002096 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002097 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002098 status = INVALID_OPERATION;
2099 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002100 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002101
Eric Laurent8f42ea12018-08-08 09:08:25 -07002102exit:
2103
François Gaffiec005e562018-11-06 15:04:49 +01002104 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2105 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002106
Francois Gaffie716e1432019-01-14 16:58:59 +01002107 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002108 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabindff2a4f2019-09-10 14:29:54 -07002109 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002110
Mikhail Naganov2996f672019-04-18 12:29:59 -07002111 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002112 requestedDeviceId, attributes.source, flags,
2113 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002114 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002115 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002116
2117 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2118 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002119
Eric Laurent599c7582015-12-07 18:05:55 -08002120 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002121
2122error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002123 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002124}
2125
2126
François Gaffie11d30102018-11-02 16:09:09 +01002127audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002128 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002129 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002130 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002131 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002132 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002133{
2134 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002135 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002136 bool isSoundTrigger = false;
2137
François Gaffiec005e562018-11-06 15:04:49 +01002138 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002139 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2140 if (index >= 0) {
2141 input = mSoundTriggerSessions.valueFor(session);
2142 isSoundTrigger = true;
2143 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2144 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2145 } else {
2146 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002147 }
François Gaffiec005e562018-11-06 15:04:49 +01002148 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002149 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002150 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002151 }
2152
Andy Hungf129b032015-04-07 13:45:50 -07002153 // find a compatible input profile (not necessarily identical in parameters)
2154 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002155 // sampling rate and flags may be updated by getInputProfile
2156 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2157 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002158 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002159 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002160 audio_input_flags_t profileFlags = flags;
2161 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002162 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002163 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002164 profileFlags);
2165 if (profile != 0) {
2166 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002167 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2168 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002169 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2170 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2171 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002172 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2173 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2174 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002175 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002176 }
Eric Laurente552edb2014-03-10 17:42:56 -07002177 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002178 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002179 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002180 if (samplingRate == 0) {
2181 samplingRate = profileSamplingRate;
2182 }
Eric Laurente552edb2014-03-10 17:42:56 -07002183
Eric Laurent322b4d22015-04-03 15:57:54 -07002184 if (profile->getModuleHandle() == 0) {
2185 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002186 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002187 }
2188
Eric Laurent3974e3b2017-12-07 17:58:43 -08002189 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002190 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002191 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002192 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002193 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002194 continue;
2195 }
2196 // if sound trigger, reuse input if used by other sound trigger on same session
2197 // else
2198 // reuse input if active client app is not in IDLE state
2199 //
2200 RecordClientVector clients = desc->clientsList();
2201 bool doClose = false;
2202 for (const auto& client : clients) {
2203 if (isSoundTrigger != client->isSoundTrigger()) {
2204 continue;
2205 }
2206 if (client->isSoundTrigger()) {
2207 if (session == client->session()) {
2208 return desc->mIoHandle;
2209 }
2210 continue;
2211 }
2212 if (client->active() && client->appState() != APP_STATE_IDLE) {
2213 return desc->mIoHandle;
2214 }
2215 doClose = true;
2216 }
2217 if (doClose) {
2218 closeInput(desc->mIoHandle);
2219 } else {
2220 i++;
2221 }
2222 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002223 }
2224
Eric Laurentfe231122017-11-17 17:48:06 -08002225 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002226
Eric Laurentfe231122017-11-17 17:48:06 -08002227 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2228 lConfig.sample_rate = profileSamplingRate;
2229 lConfig.channel_mask = profileChannelMask;
2230 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002231
François Gaffie11d30102018-11-02 16:09:09 +01002232 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002233
2234 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002235 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002236 (profileSamplingRate != lConfig.sample_rate) ||
2237 !audio_formats_match(profileFormat, lConfig.format) ||
2238 (profileChannelMask != lConfig.channel_mask)) {
2239 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002240 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002241 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002242 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002243 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002244 }
Eric Laurent599c7582015-12-07 18:05:55 -08002245 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002246 }
2247
Eric Laurentc722f302014-12-10 11:21:49 -08002248 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002249
Eric Laurent599c7582015-12-07 18:05:55 -08002250 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002251 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002252
Eric Laurent599c7582015-12-07 18:05:55 -08002253 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002254}
2255
Eric Laurent4eb58f12018-12-07 16:41:02 -08002256status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002257{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002258 ALOGV("%s portId %d", __FUNCTION__, portId);
2259
2260 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2261 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002262 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent717bc282020-08-21 17:10:39 -07002263 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002264 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002265 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002266 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002267 if (client->active()) {
2268 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2269 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002270 }
2271
Eric Laurent8f42ea12018-08-08 09:08:25 -07002272 audio_session_t session = client->session();
2273
Eric Laurent4eb58f12018-12-07 16:41:02 -08002274 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002275
Eric Laurent4eb58f12018-12-07 16:41:02 -08002276 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002277
Eric Laurent4eb58f12018-12-07 16:41:02 -08002278 status_t status = inputDesc->start();
2279 if (status != NO_ERROR) {
2280 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002283 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002284 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002285 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002286
Eric Laurent8f42ea12018-08-08 09:08:25 -07002287 // indicate active capture to sound trigger service if starting capture from a mic on
2288 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002289 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002290 if (device != nullptr) {
2291 status = setInputDevice(input, device, true /* force */);
2292 } else {
2293 ALOGW("%s no new input device can be found for descriptor %d",
2294 __FUNCTION__, inputDesc->getId());
2295 status = BAD_VALUE;
2296 }
Eric Laurente552edb2014-03-10 17:42:56 -07002297
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002298 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002299 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002300 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002301 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002302 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2303 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002304 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002305 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002306
François Gaffie11d30102018-11-02 16:09:09 +01002307 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2308 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002309 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002310 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002311 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002312
Eric Laurent8f42ea12018-08-08 09:08:25 -07002313 // automatically enable the remote submix output when input is started if not
2314 // used by a policy mix of type MIX_TYPE_RECORDERS
2315 // For remote submix (a virtual device), we open only one input per capture request.
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("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002318 if (policyMix == nullptr) {
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;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002322 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002323 if (address != "") {
2324 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2325 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002326 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002327 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002328 }
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002329 } else if (status != NO_ERROR) {
2330 // Restore client activity state.
2331 inputDesc->setClientActive(client, false);
2332 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002333 }
2334
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002335 ALOGV("%s input %d source = %d status = %d exit",
2336 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002337
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002338 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002339}
2340
Eric Laurent8fc147b2018-07-22 19:13:55 -07002341status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002342{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002343 ALOGV("%s portId %d", __FUNCTION__, portId);
2344
2345 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2346 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002347 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002348 return BAD_VALUE;
2349 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002350 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002351 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002352 if (!client->active()) {
2353 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002354 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002355 }
2356
Eric Laurent8f42ea12018-08-08 09:08:25 -07002357 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002358
Eric Laurent8f42ea12018-08-08 09:08:25 -07002359 inputDesc->stop();
2360 if (inputDesc->isActive()) {
2361 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2362 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002363 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002364 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002365 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002366 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2367 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002368 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002369 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002370
2371 // automatically disable the remote submix output when input is stopped if not
2372 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002373 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002374 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002375 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002376 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002377 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2378 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002379 }
2380 if (address != "") {
2381 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2382 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002383 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002384 }
2385 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002386 resetInputDevice(input);
2387
2388 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2389 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002390 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2391 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002392 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002393 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002394 }
2395 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002396 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002397 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002398}
2399
Eric Laurent8fc147b2018-07-22 19:13:55 -07002400void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002401{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002402 ALOGV("%s portId %d", __FUNCTION__, portId);
2403
2404 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2405 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002406 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002407 return;
2408 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002409 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002410 audio_io_handle_t input = inputDesc->mIoHandle;
2411
Eric Laurent8f42ea12018-08-08 09:08:25 -07002412 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002413
Andy Hung39efb7a2018-09-26 15:39:28 -07002414 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002415
Andy Hung39efb7a2018-09-26 15:39:28 -07002416 if (inputDesc->getClientCount() > 0) {
2417 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002418 return;
2419 }
2420
Eric Laurent05b90f82014-08-27 15:32:29 -07002421 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002422 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002423 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002424}
2425
Eric Laurent8f42ea12018-08-08 09:08:25 -07002426void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002427{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002428 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002429
2430 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002431 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002432 }
2433}
2434
Eric Laurent8f42ea12018-08-08 09:08:25 -07002435void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2436{
2437 stopInput(portId);
2438 releaseInput(portId);
2439}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002440
Eric Laurent0dd51852019-04-19 18:18:58 -07002441void AudioPolicyManager::checkCloseInputs() {
2442 // After connecting or disconnecting an input device, close input if:
2443 // - it has no client (was just opened to check profile) OR
2444 // - none of its supported devices are connected anymore OR
2445 // - one of its clients cannot be routed to one of its supported
2446 // devices anymore. Otherwise update device selection
2447 std::vector<audio_io_handle_t> inputsToClose;
2448 for (size_t i = 0; i < mInputs.size(); i++) {
2449 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2450 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002451 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002452 inputsToClose.push_back(mInputs.keyAt(i));
2453 } else {
2454 bool close = false;
2455 for (const auto& client : input->clientsList()) {
2456 sp<DeviceDescriptor> device =
2457 mEngine->getInputDeviceForAttributes(client->attributes());
2458 if (!input->supportedDevices().contains(device)) {
2459 close = true;
2460 break;
2461 }
2462 }
2463 if (close) {
2464 inputsToClose.push_back(mInputs.keyAt(i));
2465 } else {
2466 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2467 }
2468 }
2469 }
2470
2471 for (const audio_io_handle_t handle : inputsToClose) {
2472 ALOGV("%s closing input %d", __func__, handle);
2473 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002474 }
Eric Laurentd4692962014-05-05 18:13:44 -07002475}
2476
François Gaffie251c7f02018-11-07 10:41:08 +01002477void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002478{
2479 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002480 if (indexMin < 0 || indexMax < 0) {
2481 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2482 return;
2483 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002484 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002485
2486 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002487 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2488 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002489 continue;
2490 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002491 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002492 }
Eric Laurente552edb2014-03-10 17:42:56 -07002493}
2494
Eric Laurente0720872014-03-11 09:30:41 -07002495status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002496 int index,
2497 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002498{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002499 auto attributes = mEngine->getAttributesForStreamType(stream);
Francois Gaffie5992b182020-03-20 14:55:14 +01002500 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2501 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2502 return NO_ERROR;
2503 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002504 ALOGV("%s: stream %s attributes=%s", __func__,
2505 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002506 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002507}
2508
Eric Laurente0720872014-03-11 09:30:41 -07002509status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002510 int *index,
2511 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002512{
François Gaffiec005e562018-11-06 15:04:49 +01002513 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2514 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002515 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002516 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002517 deviceTypes = mEngine->getOutputDevicesForStream(
2518 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002519 }
jiabin12dc6b02019-10-01 09:38:30 -07002520 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002521}
2522
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002523status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002524 int index,
2525 audio_devices_t device)
2526{
2527 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002528 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2529 if (group == VOLUME_GROUP_NONE) {
2530 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002531 return BAD_VALUE;
2532 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002533 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002534 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002535 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002536 VolumeSource vs = toVolumeSource(group);
2537 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2538
2539 status = setVolumeCurveIndex(index, device, curves);
2540 if (status != NO_ERROR) {
2541 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2542 return status;
2543 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002544
jiabin12dc6b02019-10-01 09:38:30 -07002545 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002546 auto curCurvAttrs = curves.getAttributes();
2547 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2548 auto attr = curCurvAttrs.front();
jiabin12dc6b02019-10-01 09:38:30 -07002549 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002550 } else if (!curves.getStreamTypes().empty()) {
2551 auto stream = curves.getStreamTypes().front();
jiabin12dc6b02019-10-01 09:38:30 -07002552 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002553 } else {
2554 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2555 return BAD_VALUE;
2556 }
jiabin12dc6b02019-10-01 09:38:30 -07002557 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2558 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002559
François Gaffiecfe17322018-11-07 13:41:29 +01002560 // update volume on all outputs and streams matching the following:
2561 // - The requested stream (or a stream matching for volume control) is active on the output
2562 // - The device (or devices) selected by the engine for this stream includes
2563 // the requested device
2564 // - For non default requested device, currently selected device on the output is either the
2565 // requested device or one of the devices selected by the engine for this stream
2566 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2567 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002568 for (size_t i = 0; i < mOutputs.size(); i++) {
2569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07002570 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002571
jiabin12dc6b02019-10-01 09:38:30 -07002572 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2573 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002574 }
François Gaffieed91f582020-01-31 10:35:37 +01002575 if (!(desc->isActive(vs) || isInCall())) {
2576 continue;
2577 }
2578 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2579 curDevices.find(device) == curDevices.end()) {
2580 continue;
2581 }
2582 bool applyVolume = false;
2583 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2584 curSrcDevices.insert(device);
2585 applyVolume = (curSrcDevices.find(
2586 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2587 } else {
2588 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2589 }
2590 if (!applyVolume) {
2591 continue; // next output
2592 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002593 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2594 // If a higher priority strategy is active, and the output is routed to a device with a
2595 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002596 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002597 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002598 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2599 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2600 false /*preferredDevice*/);
2601 if (activeClients.empty()) {
2602 continue;
2603 }
2604 bool isPreempted = false;
2605 bool isHigherPriority = productStrategy < strategy;
2606 for (const auto &client : activeClients) {
2607 if (isHigherPriority && (client->volumeSource() != vs)) {
2608 ALOGV("%s: Strategy=%d (\nrequester:\n"
2609 " group %d, volumeGroup=%d attributes=%s)\n"
2610 " higher priority source active:\n"
2611 " volumeGroup=%d attributes=%s) \n"
2612 " on output %zu, bailing out", __func__, productStrategy,
2613 group, group, toString(attributes).c_str(),
2614 client->volumeSource(), toString(client->attributes()).c_str(), i);
2615 applyVolume = false;
2616 isPreempted = true;
2617 break;
2618 }
2619 // However, continue for loop to ensure no higher prio clients running on output
2620 if (client->volumeSource() == vs) {
2621 applyVolume = true;
2622 }
2623 }
2624 if (isPreempted || applyVolume) {
2625 break;
2626 }
2627 }
2628 if (!applyVolume) {
2629 continue; // next output
2630 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002631 }
François Gaffieed91f582020-01-31 10:35:37 +01002632 //FIXME: workaround for truncated touch sounds
2633 // delayed volume change for system stream to be removed when the problem is
2634 // handled by system UI
2635 status_t volStatus = checkAndSetVolume(
2636 curves, vs, index, desc, curDevices,
2637 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2638 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2639 if (volStatus != NO_ERROR) {
2640 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002641 }
2642 }
François Gaffiecfe17322018-11-07 13:41:29 +01002643 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2644 return status;
2645}
2646
François Gaffieaaac0fd2018-11-22 17:56:39 +01002647status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002648 audio_devices_t device,
2649 IVolumeCurves &volumeCurves)
2650{
2651 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2652 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002653 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2654 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002655 (index > volumeCurves.getVolumeIndexMax())) {
2656 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2657 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2658 return BAD_VALUE;
2659 }
2660 if (!audio_is_output_device(device)) {
2661 return BAD_VALUE;
2662 }
2663
2664 // Force max volume if stream cannot be muted
2665 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2666
François Gaffieaaac0fd2018-11-22 17:56:39 +01002667 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002668 volumeCurves.addCurrentVolumeIndex(device, index);
2669 return NO_ERROR;
2670}
2671
2672status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2673 int &index,
2674 audio_devices_t device)
2675{
2676 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2677 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002678 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002679 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002680 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2681 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002682 }
jiabin12dc6b02019-10-01 09:38:30 -07002683 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002684}
2685
2686status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2687 int &index,
jiabin12dc6b02019-10-01 09:38:30 -07002688 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002689{
jiabin12dc6b02019-10-01 09:38:30 -07002690 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002691 return BAD_VALUE;
2692 }
jiabin12dc6b02019-10-01 09:38:30 -07002693 index = curves.getVolumeIndex(deviceTypes);
2694 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002695 return NO_ERROR;
2696}
2697
2698status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2699 int &index)
2700{
2701 index = getVolumeCurves(attr).getVolumeIndexMin();
2702 return NO_ERROR;
2703}
2704
2705status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2706 int &index)
2707{
2708 index = getVolumeCurves(attr).getVolumeIndexMax();
2709 return NO_ERROR;
2710}
2711
Eric Laurent36829f92017-04-07 19:04:42 -07002712audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002713{
2714 // select one output among several suitable for global effects.
2715 // The priority is as follows:
2716 // 1: An offloaded output. If the effect ends up not being offloadable,
2717 // AudioFlinger will invalidate the track and the offloaded output
2718 // will be closed causing the effect to be moved to a PCM output.
2719 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002720 // 3: The primary output
2721 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002722
François Gaffiec005e562018-11-06 15:04:49 +01002723 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2724 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002725 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002726
Eric Laurent36829f92017-04-07 19:04:42 -07002727 if (outputs.size() == 0) {
2728 return AUDIO_IO_HANDLE_NONE;
2729 }
Eric Laurente552edb2014-03-10 17:42:56 -07002730
Eric Laurent36829f92017-04-07 19:04:42 -07002731 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2732 bool activeOnly = true;
2733
2734 while (output == AUDIO_IO_HANDLE_NONE) {
2735 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2736 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2737 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2738
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002739 for (audio_io_handle_t output : outputs) {
2740 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002741 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002742 continue;
2743 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002744 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2745 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002746 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002747 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002748 }
2749 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002750 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002751 }
2752 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002753 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002754 }
2755 }
2756 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2757 output = outputOffloaded;
2758 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2759 output = outputDeepBuffer;
2760 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2761 output = outputPrimary;
2762 } else {
2763 output = outputs[0];
2764 }
2765 activeOnly = false;
2766 }
2767
2768 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002769 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002770 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2771 mMusicEffectOutput = output;
2772 }
2773
2774 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002775 return output;
2776}
2777
Eric Laurent36829f92017-04-07 19:04:42 -07002778audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2779{
2780 return selectOutputForMusicEffects();
2781}
2782
Eric Laurente0720872014-03-11 09:30:41 -07002783status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002784 audio_io_handle_t io,
2785 uint32_t strategy,
2786 int session,
2787 int id)
2788{
Eric Laurent9b2064c2019-11-22 17:25:04 -08002789 if (session != AUDIO_SESSION_DEVICE) {
2790 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002791 if (index < 0) {
Eric Laurent9b2064c2019-11-22 17:25:04 -08002792 index = mInputs.indexOfKey(io);
2793 if (index < 0) {
2794 ALOGW("registerEffect() unknown io %d", io);
2795 return INVALID_OPERATION;
2796 }
Eric Laurente552edb2014-03-10 17:42:56 -07002797 }
2798 }
François Gaffiec005e562018-11-06 15:04:49 +01002799 return mEffects.registerEffect(desc, io, session, id,
2800 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2801 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002802}
2803
Eric Laurentc241b0d2018-11-28 09:08:49 -08002804status_t AudioPolicyManager::unregisterEffect(int id)
2805{
2806 if (mEffects.getEffect(id) == nullptr) {
2807 return INVALID_OPERATION;
2808 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002809 if (mEffects.isEffectEnabled(id)) {
2810 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2811 setEffectEnabled(id, false);
2812 }
2813 return mEffects.unregisterEffect(id);
2814}
2815
2816status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2817{
2818 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2819 if (effect == nullptr) {
2820 return INVALID_OPERATION;
2821 }
2822
2823 status_t status = mEffects.setEffectEnabled(id, enabled);
2824 if (status == NO_ERROR) {
2825 mInputs.trackEffectEnabled(effect, enabled);
2826 }
2827 return status;
2828}
2829
Eric Laurent6c796322019-04-09 14:13:17 -07002830
2831status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2832{
2833 mEffects.moveEffects(ids, io);
2834 return NO_ERROR;
2835}
2836
Eric Laurentc75307b2015-03-17 15:29:32 -07002837bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2838{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002839 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002840}
2841
2842bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2843{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002844 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002845}
2846
Eric Laurente0720872014-03-11 09:30:41 -07002847bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002848{
2849 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002850 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002851 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002852 return true;
2853 }
2854 }
2855 return false;
2856}
2857
Eric Laurent275e8e92014-11-30 15:14:47 -08002858// Register a list of custom mixes with their attributes and format.
2859// When a mix is registered, corresponding input and output profiles are
2860// added to the remote submix hw module. The profile contains only the
2861// parameters (sampling rate, format...) specified by the mix.
2862// The corresponding input remote submix device is also connected.
2863//
2864// When a remote submix device is connected, the address is checked to select the
2865// appropriate profile and the corresponding input or output stream is opened.
2866//
2867// When capture starts, getInputForAttr() will:
2868// - 1 look for a mix matching the address passed in attribtutes tags if any
2869// - 2 if none found, getDeviceForInputSource() will:
2870// - 2.1 look for a mix matching the attributes source
2871// - 2.2 if none found, default to device selection by policy rules
2872// At this time, the corresponding output remote submix device is also connected
2873// and active playback use cases can be transferred to this mix if needed when reconnecting
2874// after AudioTracks are invalidated
2875//
2876// When playback starts, getOutputForAttr() will:
2877// - 1 look for a mix matching the address passed in attribtutes tags if any
2878// - 2 if none found, look for a mix matching the attributes usage
2879// - 3 if none found, default to device and output selection by policy rules.
2880
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002881status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002882{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002883 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2884 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002885 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002886 sp<HwModule> rSubmixModule;
2887 // examine each mix's route type
2888 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002889 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002890 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2891 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2892 ALOGE("Unsupported Policy Mix %zu of %zu: "
2893 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2894 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002895 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002896 break;
2897 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002898 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2899 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002900 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002901 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2902 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002903 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002904 rSubmixModule = mHwModules.getModuleFromName(
2905 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2906 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002907 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002908 i);
2909 res = INVALID_OPERATION;
2910 break;
2911 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002912 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002913
Eric Laurent97ac8712018-07-27 18:59:02 -07002914 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002915 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002916 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002917 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002918 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2919 } else {
2920 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2921 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002922 }
François Gaffie036e1e92015-03-19 10:16:24 +01002923
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002924 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002925 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002926 res = INVALID_OPERATION;
2927 break;
2928 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002929 audio_config_t outputConfig = mix.mFormat;
2930 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07002931 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
2932 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002933 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2934 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabineaf09f02019-08-19 15:08:30 -07002935 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002936 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabineaf09f02019-08-19 15:08:30 -07002937 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002938 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002939
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002940 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002941 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2942 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2943 ALOGE("Failed to set remote submix device available, type %u, address %s",
2944 mix.mDeviceType, address.string());
2945 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002946 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002947 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2948 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002949 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002950 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002951 i, mixes.size(), type, address.string());
2952
2953 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2954 mix.mDeviceType, mix.mDeviceAddress,
2955 String8(), AUDIO_FORMAT_DEFAULT);
2956 if (device == nullptr) {
2957 res = INVALID_OPERATION;
2958 break;
2959 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002960
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002961 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07002962 // First try to find an already opened output supporting the device
2963 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002964 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002965
Eric Laurentc529cf62020-04-17 18:19:10 -07002966 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002967 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002968 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2969 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002970 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002971 } else {
2972 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002973 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002974 }
2975 }
Eric Laurentc529cf62020-04-17 18:19:10 -07002976 // If no output found, try to find a direct output profile supporting the device
2977 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
2978 sp<HwModule> module = mHwModules[i];
2979 for (size_t j = 0;
2980 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
2981 j++) {
2982 sp<IOProfile> profile = module->getOutputProfiles()[j];
2983 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
2984 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
2985 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2986 address.string());
2987 res = INVALID_OPERATION;
2988 } else {
2989 foundOutput = true;
2990 }
2991 }
2992 }
2993 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002994 if (res != NO_ERROR) {
2995 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002996 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002997 res = INVALID_OPERATION;
2998 break;
2999 } else if (!foundOutput) {
3000 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003001 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003002 res = INVALID_OPERATION;
3003 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003004 } else {
3005 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003006 }
Eric Laurentc722f302014-12-10 11:21:49 -08003007 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003008 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003009 if (res != NO_ERROR) {
3010 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003011 } else if (checkOutputs) {
3012 checkForDeviceAndOutputChanges();
3013 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003014 }
3015 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003016}
3017
3018status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3019{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003020 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003021 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003022 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003023 sp<HwModule> rSubmixModule;
3024 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003025 for (const auto& mix : mixes) {
3026 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003027
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003028 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003029 rSubmixModule = mHwModules.getModuleFromName(
3030 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3031 if (rSubmixModule == 0) {
3032 res = INVALID_OPERATION;
3033 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003034 }
3035 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003036
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003037 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003038
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003039 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003040 res = INVALID_OPERATION;
3041 continue;
3042 }
3043
Kevin Rocard04ed0462019-05-02 17:53:24 -07003044 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3045 if (getDeviceConnectionState(device, address.string()) ==
3046 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3047 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3048 address.string(), "remote-submix",
3049 AUDIO_FORMAT_DEFAULT);
3050 if (res != OK) {
3051 ALOGE("Error making RemoteSubmix device unavailable for mix "
3052 "with type %d, address %s", device, address.string());
3053 }
3054 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003055 }
jiabineaf09f02019-08-19 15:08:30 -07003056 rSubmixModule->removeOutputProfile(address.c_str());
3057 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003058
Kevin Rocard153f92d2018-12-18 18:33:28 -08003059 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003060 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003061 res = INVALID_OPERATION;
3062 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003063 } else {
3064 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003065 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003066 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003067 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003068 if (res == NO_ERROR && checkOutputs) {
3069 checkForDeviceAndOutputChanges();
3070 updateCallAndOutputRouting();
3071 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003072 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003073}
3074
Mikhail Naganov100f0122018-11-29 11:22:16 -08003075void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3076{
3077 size_t i = 0;
3078 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3079 for (const auto& fmt : mManualSurroundFormats) {
3080 if (i++ != 0) dst->append(", ");
3081 std::string sfmt;
3082 FormatConverter::toString(fmt, sfmt);
3083 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3084 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3085 }
3086}
3087
Eric Laurentc529cf62020-04-17 18:19:10 -07003088// Returns true if all devices types match the predicate and are supported by one HW module
3089bool AudioPolicyManager::areAllDevicesSupported(
jiabinc1afe3b2020-08-07 11:56:38 -07003090 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003091 std::function<bool(audio_devices_t)> predicate,
3092 const char *context) {
3093 for (size_t i = 0; i < devices.size(); i++) {
3094 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin4e826212020-08-07 17:32:40 -07003095 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003096 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003097 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang6e468242020-09-03 17:54:16 +00003098 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin4e826212020-08-07 17:32:40 -07003099 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003100 return false;
3101 }
3102 }
3103 return true;
3104}
3105
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003106status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabinc1afe3b2020-08-07 11:56:38 -07003107 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003108 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003109 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3110 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003111 }
3112 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003113 if (res != NO_ERROR) {
3114 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3115 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003116 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003117
3118 checkForDeviceAndOutputChanges();
3119 updateCallAndOutputRouting();
3120
3121 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003122}
3123
3124status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3125 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003126 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3127 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003128 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003129 __FUNCTION__, uid);
3130 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003131 }
3132
Eric Laurentc529cf62020-04-17 18:19:10 -07003133 checkForDeviceAndOutputChanges();
3134 updateCallAndOutputRouting();
3135
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003136 return res;
3137}
3138
Eric Laurentcca11ce2020-11-25 15:31:27 +01003139
jiabin4e826212020-08-07 17:32:40 -07003140status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3141 device_role_t role,
3142 const AudioDeviceTypeAddrVector &devices) {
3143 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3144 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003145
Eric Laurentc529cf62020-04-17 18:19:10 -07003146 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003147 return BAD_VALUE;
3148 }
jiabin4e826212020-08-07 17:32:40 -07003149 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003150 if (status != NO_ERROR) {
jiabin4e826212020-08-07 17:32:40 -07003151 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3152 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003153 return status;
3154 }
3155
3156 checkForDeviceAndOutputChanges();
Eric Laurentcca11ce2020-11-25 15:31:27 +01003157
3158 bool forceVolumeReeval = false;
3159 // FIXME: workaround for truncated touch sounds
3160 // to be removed when the problem is handled by system UI
3161 uint32_t delayMs = 0;
3162 if (strategy == mCommunnicationStrategy) {
3163 forceVolumeReeval = true;
3164 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3165 updateInputRouting();
3166 }
3167 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003168
3169 return NO_ERROR;
3170}
3171
3172void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3173{
3174 uint32_t waitMs = 0;
3175 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3176 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3177 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurente1f1cb52020-08-21 12:50:41 -07003178 // Only apply special touch sound delay once
3179 delayMs = 0;
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003180 }
3181 for (size_t i = 0; i < mOutputs.size(); i++) {
3182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3183 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3184 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3185 // As done in setDeviceConnectionState, we could also fix default device issue by
3186 // preventing the force re-routing in case of default dev that distinguishes on address.
3187 // Let's give back to engine full device choice decision however.
3188 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurente1f1cb52020-08-21 12:50:41 -07003189 // Only apply special touch sound delay once
3190 delayMs = 0;
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003191 }
3192 if (forceVolumeReeval && !newDevices.isEmpty()) {
3193 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3194 }
3195 }
3196}
3197
Eric Laurentcca11ce2020-11-25 15:31:27 +01003198void AudioPolicyManager::updateInputRouting() {
3199 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3200 auto newDevice = getNewInputDevice(activeDesc);
3201 // Force new input selection if the new device can not be reached via current input
3202 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3203 setInputDevice(activeDesc->mIoHandle, newDevice);
3204 } else {
3205 closeInput(activeDesc->mIoHandle);
3206 }
3207 }
3208}
3209
jiabin4e826212020-08-07 17:32:40 -07003210status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3211 device_role_t role)
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003212{
jiabin4e826212020-08-07 17:32:40 -07003213 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003214
jiabin4e826212020-08-07 17:32:40 -07003215 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003216 if (status != NO_ERROR) {
Eric Laurentcca11ce2020-11-25 15:31:27 +01003217 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3218 strategy, status);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003219 return status;
3220 }
3221
3222 checkForDeviceAndOutputChanges();
Eric Laurentcca11ce2020-11-25 15:31:27 +01003223
3224 bool forceVolumeReeval = false;
3225 // FIXME: workaround for truncated touch sounds
3226 // to be removed when the problem is handled by system UI
3227 uint32_t delayMs = 0;
3228 if (strategy == mCommunnicationStrategy) {
3229 forceVolumeReeval = true;
3230 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3231 updateInputRouting();
3232 }
3233 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003234
3235 return NO_ERROR;
3236}
3237
jiabin4e826212020-08-07 17:32:40 -07003238status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3239 device_role_t role,
3240 AudioDeviceTypeAddrVector &devices) {
3241 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003242}
3243
Jiabin Huang6e468242020-09-03 17:54:16 +00003244status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3245 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3246 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3247 dumpAudioDeviceTypeAddrVector(devices).c_str());
3248
3249 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
3250 return BAD_VALUE;
3251 }
3252 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3253 ALOGW_IF(status != NO_ERROR,
3254 "Engine could not set preferred devices %s for audio source %d role %d",
3255 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3256
3257 return status;
3258}
3259
3260status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3261 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3262 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3263 dumpAudioDeviceTypeAddrVector(devices).c_str());
3264
3265 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
3266 return BAD_VALUE;
3267 }
3268 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3269 ALOGW_IF(status != NO_ERROR,
3270 "Engine could not add preferred devices %s for audio source %d role %d",
3271 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3272
Eric Laurentcca11ce2020-11-25 15:31:27 +01003273 updateInputRouting();
Jiabin Huang6e468242020-09-03 17:54:16 +00003274 return status;
3275}
3276
3277status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3278 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3279{
3280 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3281 dumpAudioDeviceTypeAddrVector(devices).c_str());
3282
3283 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
3284 return BAD_VALUE;
3285 }
3286
3287 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3288 audioSource, role, devices);
3289 ALOGW_IF(status != NO_ERROR,
3290 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3291
Eric Laurentcca11ce2020-11-25 15:31:27 +01003292 updateInputRouting();
Jiabin Huang6e468242020-09-03 17:54:16 +00003293 return status;
3294}
3295
3296status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3297 device_role_t role) {
3298 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3299
3300 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3301 ALOGW_IF(status != NO_ERROR,
3302 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3303
Eric Laurentcca11ce2020-11-25 15:31:27 +01003304 updateInputRouting();
Jiabin Huang6e468242020-09-03 17:54:16 +00003305 return status;
3306}
3307
3308status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3309 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3310 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3311}
3312
Oscar Azucena90e77632019-11-27 17:12:28 -08003313status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabinc1afe3b2020-08-07 11:56:38 -07003314 const AudioDeviceTypeAddrVector& devices) {
3315 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003316 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3317 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003318 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003319 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3320 if (status != NO_ERROR) {
3321 ALOGE("%s() could not set device affinity for userId %d",
3322 __FUNCTION__, userId);
3323 return status;
3324 }
3325
3326 // reevaluate outputs for all devices
3327 checkForDeviceAndOutputChanges();
3328 updateCallAndOutputRouting();
3329
3330 return NO_ERROR;
3331}
3332
3333status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3334 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3335 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3336 if (status != NO_ERROR) {
3337 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3338 __FUNCTION__, userId);
3339 return status;
3340 }
3341
3342 // reevaluate outputs for all devices
3343 checkForDeviceAndOutputChanges();
3344 updateCallAndOutputRouting();
3345
3346 return NO_ERROR;
3347}
3348
Andy Hungc29d82b2018-10-05 12:23:17 -07003349void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003350{
Andy Hungc29d82b2018-10-05 12:23:17 -07003351 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3352 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003353 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003354 std::string stateLiteral;
3355 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003356 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003357 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3358 "communications", "media", "record", "dock", "system",
3359 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3360 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3361 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003362 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3363 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3364 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3365 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3366 dst->append(" (MANUAL: ");
3367 dumpManualSurroundFormats(dst);
3368 dst->append(")");
3369 }
3370 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003371 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003372 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3373 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurentcca11ce2020-11-25 15:31:27 +01003374 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003375 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurentcca11ce2020-11-25 15:31:27 +01003376
Andy Hungc29d82b2018-10-05 12:23:17 -07003377 mAvailableOutputDevices.dump(dst, String8("Available output"));
3378 mAvailableInputDevices.dump(dst, String8("Available input"));
3379 mHwModulesAll.dump(dst);
3380 mOutputs.dump(dst);
3381 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003382 mEffects.dump(dst);
3383 mAudioPatches.dump(dst);
3384 mPolicyMixes.dump(dst);
3385 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003386
Kevin Rocardb99cc752019-03-21 20:52:24 -07003387 dst->appendFormat(" AllowedCapturePolicies:\n");
3388 for (auto& policy : mAllowedCapturePolicies) {
3389 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3390 }
3391
François Gaffiec005e562018-11-06 15:04:49 +01003392 dst->appendFormat("\nPolicy Engine dump:\n");
3393 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003394}
3395
3396status_t AudioPolicyManager::dump(int fd)
3397{
3398 String8 result;
3399 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003400 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003401 return NO_ERROR;
3402}
3403
Kevin Rocardb99cc752019-03-21 20:52:24 -07003404status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3405{
3406 mAllowedCapturePolicies[uid] = capturePolicy;
3407 return NO_ERROR;
3408}
3409
Eric Laurente552edb2014-03-10 17:42:56 -07003410// This function checks for the parameters which can be offloaded.
3411// This can be enhanced depending on the capability of the DSP and policy
3412// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07003413bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003414{
3415 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003416 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07003417 offloadInfo.sample_rate, offloadInfo.channel_mask,
3418 offloadInfo.format,
3419 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3420 offloadInfo.has_video);
3421
Andy Hung2ddee192015-12-18 17:34:44 -08003422 if (mMasterMono) {
3423 return false; // no offloading if mono is set.
3424 }
3425
Eric Laurente552edb2014-03-10 17:42:56 -07003426 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003427 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3428 ALOGV("offload disabled by audio.offload.disable");
3429 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07003430 }
3431
3432 // Check if stream type is music, then only allow offload as of now.
3433 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3434 {
3435 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3436 return false;
3437 }
3438
3439 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003440 const bool allowOffloadWithVideo =
3441 property_get_bool("audio.offload.video", false /* default_value */);
3442 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07003443 ALOGV("isOffloadSupported: has_video == true, returning false");
3444 return false;
3445 }
3446
3447 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003448 const int min_duration_secs = property_get_int32(
3449 "audio.offload.min.duration.secs", -1 /* default_value */);
3450 if (min_duration_secs >= 0) {
3451 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3452 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3453 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07003454 return false;
3455 }
3456 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3457 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3458 return false;
3459 }
3460
3461 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3462 // creating an offloaded track and tearing it down immediately after start when audioflinger
3463 // detects there is an active non offloadable effect.
3464 // FIXME: We should check the audio session here but we do not have it in this context.
3465 // This may prevent offloading in rare situations where effects are left active by apps
3466 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003467 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003468 return false;
3469 }
3470
3471 // See if there is a profile to support this.
3472 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003473 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003474 offloadInfo.sample_rate,
3475 offloadInfo.format,
3476 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003477 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3478 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07003479 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3480 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003481}
3482
Michael Chana94fbb22018-04-24 14:31:19 +10003483bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3484 const audio_attributes_t& attributes) {
3485 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003486 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003487 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003488 config.sample_rate,
3489 config.format,
3490 config.channel_mask,
3491 output_flags,
3492 true /* directOnly */);
3493 ALOGV("%s() profile %sfound with name: %s, "
3494 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3495 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabineaf09f02019-08-19 15:08:30 -07003496 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003497 config.sample_rate, config.format, config.channel_mask, output_flags);
3498 return (profile != 0);
3499}
3500
Eric Laurent6a94d692014-05-20 11:18:06 -07003501status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3502 audio_port_type_t type,
3503 unsigned int *num_ports,
3504 struct audio_port *ports,
3505 unsigned int *generation)
3506{
3507 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3508 generation == NULL) {
3509 return BAD_VALUE;
3510 }
3511 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3512 if (ports == NULL) {
3513 *num_ports = 0;
3514 }
3515
3516 size_t portsWritten = 0;
3517 size_t portsMax = *num_ports;
3518 *num_ports = 0;
3519 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003520 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3521 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003522 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003523 for (const auto& dev : mAvailableOutputDevices) {
3524 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003525 continue;
3526 }
3527 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003528 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003529 }
3530 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003531 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003532 }
3533 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 for (const auto& dev : mAvailableInputDevices) {
3535 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003536 continue;
3537 }
3538 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003539 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003540 }
3541 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003542 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003543 }
3544 }
3545 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3546 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3547 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3548 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3549 }
3550 *num_ports += mInputs.size();
3551 }
3552 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003553 size_t numOutputs = 0;
3554 for (size_t i = 0; i < mOutputs.size(); i++) {
3555 if (!mOutputs[i]->isDuplicated()) {
3556 numOutputs++;
3557 if (portsWritten < portsMax) {
3558 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3559 }
3560 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003561 }
Eric Laurent84c70242014-06-23 08:46:27 -07003562 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003563 }
3564 }
3565 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003566 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003567 return NO_ERROR;
3568}
3569
Eric Laurent99fcae42018-05-17 16:59:18 -07003570status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003571{
Eric Laurent99fcae42018-05-17 16:59:18 -07003572 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3573 return BAD_VALUE;
3574 }
3575 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3576 if (dev != 0) {
3577 dev->toAudioPort(port);
3578 return NO_ERROR;
3579 }
3580 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3581 if (dev != 0) {
3582 dev->toAudioPort(port);
3583 return NO_ERROR;
3584 }
3585 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3586 if (out != 0) {
3587 out->toAudioPort(port);
3588 return NO_ERROR;
3589 }
3590 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3591 if (in != 0) {
3592 in->toAudioPort(port);
3593 return NO_ERROR;
3594 }
3595 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003596}
3597
François Gaffiead447b72019-11-18 15:50:22 +01003598status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3599 audio_patch_handle_t *handle,
3600 uid_t uid, uint32_t delayMs,
3601 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003602{
François Gaffiead447b72019-11-18 15:50:22 +01003603 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003604 if (handle == NULL || patch == NULL) {
3605 return BAD_VALUE;
3606 }
François Gaffiead447b72019-11-18 15:50:22 +01003607 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003608
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003609 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003610 return BAD_VALUE;
3611 }
3612 // only one source per audio patch supported for now
3613 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003614 return INVALID_OPERATION;
3615 }
Eric Laurent874c42872014-08-08 15:13:39 -07003616
3617 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003618 return INVALID_OPERATION;
3619 }
Eric Laurent874c42872014-08-08 15:13:39 -07003620 for (size_t i = 0; i < patch->num_sinks; i++) {
3621 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3622 return INVALID_OPERATION;
3623 }
3624 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003625
3626 sp<AudioPatch> patchDesc;
3627 ssize_t index = mAudioPatches.indexOfKey(*handle);
3628
François Gaffiead447b72019-11-18 15:50:22 +01003629 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3630 patch->sources[0].role,
3631 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003632#if LOG_NDEBUG == 0
3633 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffiead447b72019-11-18 15:50:22 +01003634 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3635 patch->sinks[i].role,
3636 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003637 }
3638#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003639
3640 if (index >= 0) {
3641 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003642 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3643 __func__, mUidCached, patchDesc->getUid(), uid);
3644 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003645 return INVALID_OPERATION;
3646 }
3647 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003648 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003649 }
3650
3651 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003652 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003653 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003654 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003655 return BAD_VALUE;
3656 }
Eric Laurent84c70242014-06-23 08:46:27 -07003657 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3658 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003659 if (patchDesc != 0) {
3660 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffiead447b72019-11-18 15:50:22 +01003661 ALOGV("%s source id differs for patch current id %d new id %d",
3662 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003663 return BAD_VALUE;
3664 }
3665 }
Eric Laurent874c42872014-08-08 15:13:39 -07003666 DeviceVector devices;
3667 for (size_t i = 0; i < patch->num_sinks; i++) {
3668 // Only support mix to devices connection
3669 // TODO add support for mix to mix connection
3670 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003671 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003672 return INVALID_OPERATION;
3673 }
3674 sp<DeviceDescriptor> devDesc =
3675 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3676 if (devDesc == 0) {
François Gaffiead447b72019-11-18 15:50:22 +01003677 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003678 return BAD_VALUE;
3679 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003680
François Gaffie11d30102018-11-02 16:09:09 +01003681 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003682 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003683 NULL, // updatedSamplingRate
3684 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003685 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003686 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003687 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003688 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffiead447b72019-11-18 15:50:22 +01003689 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003690 return INVALID_OPERATION;
3691 }
3692 devices.add(devDesc);
3693 }
3694 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003695 return INVALID_OPERATION;
3696 }
Eric Laurent874c42872014-08-08 15:13:39 -07003697
Eric Laurent6a94d692014-05-20 11:18:06 -07003698 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003699 ALOGV("%s setting device %s on output %d",
3700 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003701 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003702 index = mAudioPatches.indexOfKey(*handle);
3703 if (index >= 0) {
3704 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003705 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003706 }
3707 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003708 patchDesc->setUid(uid);
3709 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003710 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003711 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003712 return INVALID_OPERATION;
3713 }
3714 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3715 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3716 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003717 // only one sink supported when connecting an input device to a mix
3718 if (patch->num_sinks > 1) {
3719 return INVALID_OPERATION;
3720 }
François Gaffie53615e22015-03-19 09:24:12 +01003721 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003722 if (inputDesc == NULL) {
3723 return BAD_VALUE;
3724 }
3725 if (patchDesc != 0) {
3726 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3727 return BAD_VALUE;
3728 }
3729 }
François Gaffie11d30102018-11-02 16:09:09 +01003730 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003731 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003732 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003733 return BAD_VALUE;
3734 }
3735
François Gaffie11d30102018-11-02 16:09:09 +01003736 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003737 patch->sinks[0].sample_rate,
3738 NULL, /*updatedSampleRate*/
3739 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003740 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003741 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003742 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003743 // FIXME for the parameter type,
3744 // and the NONE
3745 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003746 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003747 return INVALID_OPERATION;
3748 }
3749 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003750 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003751 device->toString().c_str(), inputDesc->mIoHandle);
3752 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 index = mAudioPatches.indexOfKey(*handle);
3754 if (index >= 0) {
3755 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003756 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003757 }
3758 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003759 patchDesc->setUid(uid);
3760 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003761 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003762 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003763 return INVALID_OPERATION;
3764 }
3765 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3766 // device to device connection
3767 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003768 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003769 return BAD_VALUE;
3770 }
3771 }
François Gaffie11d30102018-11-02 16:09:09 +01003772 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003773 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003774 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003775 return BAD_VALUE;
3776 }
Eric Laurent874c42872014-08-08 15:13:39 -07003777
Eric Laurent6a94d692014-05-20 11:18:06 -07003778 //update source and sink with our own data as the data passed in the patch may
3779 // be incomplete.
François Gaffiead447b72019-11-18 15:50:22 +01003780 PatchBuilder patchBuilder;
3781 audio_port_config sourcePortConfig = {};
3782 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3783 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003784
Eric Laurent874c42872014-08-08 15:13:39 -07003785 for (size_t i = 0; i < patch->num_sinks; i++) {
3786 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003787 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003788 return INVALID_OPERATION;
3789 }
François Gaffie11d30102018-11-02 16:09:09 +01003790 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003791 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003792 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003793 return BAD_VALUE;
3794 }
François Gaffiead447b72019-11-18 15:50:22 +01003795 audio_port_config sinkPortConfig = {};
3796 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3797 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003798
Eric Laurent3bcf8592015-04-03 12:13:24 -07003799 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003800 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003801 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003802 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffiead447b72019-11-18 15:50:22 +01003803 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3804 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003805 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3806 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffiead447b72019-11-18 15:50:22 +01003807 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3808 (sourceDesc != nullptr &&
3809 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003810 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003811 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003812 return INVALID_OPERATION;
3813 }
François Gaffiead447b72019-11-18 15:50:22 +01003814 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3815 if (sourceDesc != nullptr) {
3816 // take care of dynamic routing for SwOutput selection,
3817 audio_attributes_t attributes = sourceDesc->attributes();
3818 audio_stream_type_t stream = sourceDesc->stream();
3819 audio_attributes_t resultAttr;
3820 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3821 config.sample_rate = sourceDesc->config().sample_rate;
3822 config.channel_mask = sourceDesc->config().channel_mask;
3823 config.format = sourceDesc->config().format;
3824 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3825 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3826 bool isRequestedDeviceForExclusiveUse = false;
François Gaffieafd4cea2019-11-18 15:50:22 +01003827 output_type_t outputType;
François Gaffiead447b72019-11-18 15:50:22 +01003828 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3829 &stream, sourceDesc->uid(), &config, &flags,
3830 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07003831 nullptr, &outputType);
François Gaffiead447b72019-11-18 15:50:22 +01003832 if (output == AUDIO_IO_HANDLE_NONE) {
3833 ALOGV("%s no output for device %s",
3834 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003835 return INVALID_OPERATION;
3836 }
François Gaffiead447b72019-11-18 15:50:22 +01003837 } else {
3838 SortedVector<audio_io_handle_t> outputs =
3839 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3840 // if the sink device is reachable via an opened output stream, request to
3841 // go via this output stream by adding a second source to the patch
3842 // description
3843 output = selectOutput(outputs);
3844 }
3845 if (output != AUDIO_IO_HANDLE_NONE) {
3846 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3847 if (outputDesc->isDuplicated()) {
3848 ALOGV("%s output for device %s is duplicated",
3849 __FUNCTION__, sinkDevice->toString().c_str());
3850 return INVALID_OPERATION;
3851 }
3852 audio_port_config srcMixPortConfig = {};
3853 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3854 if (sourceDesc != nullptr) {
3855 sourceDesc->setSwOutput(outputDesc);
3856 }
3857 // for volume control, we may need a valid stream
3858 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3859 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3860 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003861 }
Eric Laurent83b88082014-06-20 18:31:16 -07003862 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003863 }
3864 // TODO: check from routing capabilities in config file and other conflicting patches
3865
François Gaffiead447b72019-11-18 15:50:22 +01003866 status_t status = installPatch(
3867 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003868 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01003869 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 return INVALID_OPERATION;
3871 }
3872 } else {
3873 return BAD_VALUE;
3874 }
3875 } else {
3876 return BAD_VALUE;
3877 }
3878 return NO_ERROR;
3879}
3880
3881status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3882 uid_t uid)
3883{
3884 ALOGV("releaseAudioPatch() patch %d", handle);
3885
3886 ssize_t index = mAudioPatches.indexOfKey(handle);
3887
3888 if (index < 0) {
3889 return BAD_VALUE;
3890 }
3891 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003892 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3893 __func__, mUidCached, patchDesc->getUid(), uid);
3894 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003895 return INVALID_OPERATION;
3896 }
François Gaffiead447b72019-11-18 15:50:22 +01003897 return releaseAudioPatchInternal(handle);
3898}
Eric Laurent6a94d692014-05-20 11:18:06 -07003899
François Gaffiead447b72019-11-18 15:50:22 +01003900status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3901 uint32_t delayMs)
3902{
3903 ALOGV("%s patch %d", __func__, handle);
3904 if (mAudioPatches.indexOfKey(handle) < 0) {
3905 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3906 return BAD_VALUE;
3907 }
3908 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003909 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffiead447b72019-11-18 15:50:22 +01003910 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003911 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003912 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003913 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003914 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003915 return BAD_VALUE;
3916 }
3917
François Gaffie11d30102018-11-02 16:09:09 +01003918 setOutputDevices(outputDesc,
3919 getNewOutputDevices(outputDesc, true /*fromCache*/),
3920 true,
3921 0,
3922 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003923 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3924 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003925 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 if (inputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003927 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003928 return BAD_VALUE;
3929 }
3930 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003931 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003932 true,
3933 NULL);
3934 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003935 status_t status =
3936 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
3937 ALOGV("%s patch panel returned %d patchHandle %d",
3938 __func__, status, patchDesc->getAfHandle());
3939 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003941 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie3b173542020-04-06 17:39:47 +02003942 // SW Bridge
3943 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
3944 sp<SwAudioOutputDescriptor> outputDesc =
3945 mOutputs.getOutputFromId(patch->sources[1].id);
3946 if (outputDesc == NULL) {
3947 ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
3948 return BAD_VALUE;
3949 }
Francois Gaffie8e544542020-05-11 14:12:53 +02003950 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
3951 // force SwOutput patch removal as AF counter part patch has already gone.
3952 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
3953 removeAudioPatch(outputDesc->getPatchHandle());
3954 }
Francois Gaffie3b173542020-04-06 17:39:47 +02003955 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
3956 setOutputDevices(outputDesc,
3957 getNewOutputDevices(outputDesc, true /*fromCache*/),
3958 true, /*force*/
3959 0,
3960 NULL);
3961 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003962 } else {
3963 return BAD_VALUE;
3964 }
3965 } else {
3966 return BAD_VALUE;
3967 }
3968 return NO_ERROR;
3969}
3970
3971status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3972 struct audio_patch *patches,
3973 unsigned int *generation)
3974{
François Gaffie53615e22015-03-19 09:24:12 +01003975 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 return BAD_VALUE;
3977 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003978 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003979 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003980}
3981
Eric Laurente1715a42014-05-20 11:30:42 -07003982status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003983{
Eric Laurente1715a42014-05-20 11:30:42 -07003984 ALOGV("setAudioPortConfig()");
3985
3986 if (config == NULL) {
3987 return BAD_VALUE;
3988 }
3989 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3990 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003991 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3992 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003993 }
3994
Eric Laurenta121f902014-06-03 13:32:54 -07003995 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003996 if (config->type == AUDIO_PORT_TYPE_MIX) {
3997 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003998 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003999 if (outputDesc == NULL) {
4000 return BAD_VALUE;
4001 }
Eric Laurent84c70242014-06-23 08:46:27 -07004002 ALOG_ASSERT(!outputDesc->isDuplicated(),
4003 "setAudioPortConfig() called on duplicated output %d",
4004 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004005 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004006 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004007 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004008 if (inputDesc == NULL) {
4009 return BAD_VALUE;
4010 }
Eric Laurenta121f902014-06-03 13:32:54 -07004011 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004012 } else {
4013 return BAD_VALUE;
4014 }
4015 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4016 sp<DeviceDescriptor> deviceDesc;
4017 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4018 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4019 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4020 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4021 } else {
4022 return BAD_VALUE;
4023 }
4024 if (deviceDesc == NULL) {
4025 return BAD_VALUE;
4026 }
Eric Laurenta121f902014-06-03 13:32:54 -07004027 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004028 } else {
4029 return BAD_VALUE;
4030 }
4031
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004032 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004033 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4034 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004035 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004036 audioPortConfig->toAudioPortConfig(&newConfig, config);
4037 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004038 }
Eric Laurenta121f902014-06-03 13:32:54 -07004039 if (status != NO_ERROR) {
4040 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004041 }
Eric Laurente1715a42014-05-20 11:30:42 -07004042
4043 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004044}
4045
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004046void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4047{
Eric Laurentd60560a2015-04-10 11:31:20 -07004048 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004049 clearAudioPatches(uid);
4050 clearSessionRoutes(uid);
4051}
4052
Eric Laurent6a94d692014-05-20 11:18:06 -07004053void AudioPolicyManager::clearAudioPatches(uid_t uid)
4054{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004055 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004056 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffiead447b72019-11-18 15:50:22 +01004057 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004058 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004059 }
4060 }
4061}
4062
François Gaffiec005e562018-11-06 15:04:49 +01004063void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004064{
François Gaffiec005e562018-11-06 15:04:49 +01004065 // Take the first attributes following the product strategy as it is used to retrieve the routed
4066 // device. All attributes wihin a strategy follows the same "routing strategy"
4067 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4068 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004069 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004070 for (size_t j = 0; j < mOutputs.size(); j++) {
4071 if (mOutputs.keyAt(j) == ouptutToSkip) {
4072 continue;
4073 }
4074 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004075 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004076 continue;
4077 }
4078 // If the default device for this strategy is on another output mix,
4079 // invalidate all tracks in this strategy to force re connection.
4080 // Otherwise select new device on the output mix.
4081 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004082 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4083 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004084 }
4085 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004086 setOutputDevices(
4087 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004088 }
4089 }
4090}
4091
4092void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4093{
4094 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004095 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004096 for (size_t i = 0; i < mOutputs.size(); i++) {
4097 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004098 for (const auto& client : outputDesc->getClientIterable()) {
4099 if (client->hasPreferredDevice() && client->uid() == uid) {
4100 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004101 auto clientStrategy = client->strategy();
4102 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4103 end(affectedStrategies)) {
4104 continue;
4105 }
4106 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004107 }
4108 }
4109 }
4110 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004111 for (const auto& strategy : affectedStrategies) {
4112 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004113 }
4114
4115 // remove input routes associated with this uid
4116 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004117 for (size_t i = 0; i < mInputs.size(); i++) {
4118 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004119 for (const auto& client : inputDesc->getClientIterable()) {
4120 if (client->hasPreferredDevice() && client->uid() == uid) {
4121 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4122 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004123 }
4124 }
4125 }
4126 // reroute inputs if necessary
4127 SortedVector<audio_io_handle_t> inputsToClose;
4128 for (size_t i = 0; i < mInputs.size(); i++) {
4129 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004130 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004131 inputsToClose.add(inputDesc->mIoHandle);
4132 }
4133 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004134 for (const auto& input : inputsToClose) {
4135 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004136 }
4137}
4138
Eric Laurentd60560a2015-04-10 11:31:20 -07004139void AudioPolicyManager::clearAudioSources(uid_t uid)
4140{
4141 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004142 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4143 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004144 stopAudioSource(mAudioSources.keyAt(i));
4145 }
4146 }
4147}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004148
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004149status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4150 audio_io_handle_t *ioHandle,
4151 audio_devices_t *device)
4152{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004153 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4154 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004155 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004156 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004157
François Gaffiedf372692015-03-19 10:43:27 +01004158 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004159}
4160
Eric Laurentd60560a2015-04-10 11:31:20 -07004161status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004162 const audio_attributes_t *attributes,
4163 audio_port_handle_t *portId,
4164 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004165{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004166 ALOGV("%s", __FUNCTION__);
4167 *portId = AUDIO_PORT_HANDLE_NONE;
4168
4169 if (source == NULL || attributes == NULL || portId == NULL) {
4170 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4171 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004172 return BAD_VALUE;
4173 }
4174
Eric Laurentd60560a2015-04-10 11:31:20 -07004175 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4176 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004177 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4178 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004179 return INVALID_OPERATION;
4180 }
4181
François Gaffie11d30102018-11-02 16:09:09 +01004182 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004183 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004184 String8(source->ext.device.address),
4185 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004186 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004187 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004188 return BAD_VALUE;
4189 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004190
jiabindff2a4f2019-09-10 14:29:54 -07004191 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004192
François Gaffieaaac0fd2018-11-22 17:56:39 +01004193 sp<SourceClientDescriptor> sourceDesc =
François Gaffiead447b72019-11-18 15:50:22 +01004194 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004195 mEngine->getStreamTypeForAttributes(*attributes),
4196 mEngine->getProductStrategyForAttributes(*attributes),
4197 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004198
4199 status_t status = connectAudioSource(sourceDesc);
4200 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004201 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004202 }
4203 return status;
4204}
4205
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004206status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004207{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004208 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004209
4210 // make sure we only have one patch per source.
4211 disconnectAudioSource(sourceDesc);
4212
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004213 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01004214 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07004215
François Gaffiec005e562018-11-06 15:04:49 +01004216 DeviceVector sinkDevices =
4217 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
4218 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004219 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
4220 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
4221 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07004222
François Gaffiead447b72019-11-18 15:50:22 +01004223 PatchBuilder patchBuilder;
4224 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4225 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4226 status_t status =
4227 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4228 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4229 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4230 return INVALID_OPERATION;
4231 }
4232 sourceDesc->setPatchHandle(handle);
4233 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4234 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4235 if (swOutput != 0) {
4236 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004237 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004238 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004239 }
François Gaffiead447b72019-11-18 15:50:22 +01004240 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004241 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffiead447b72019-11-18 15:50:22 +01004242 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004243 }
François Gaffiead447b72019-11-18 15:50:22 +01004244 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004245 uint32_t delayMs = 0;
François Gaffiead447b72019-11-18 15:50:22 +01004246 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004247 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004248 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4249 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004250 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004251 if (delayMs != 0) {
4252 usleep(delayMs * 1000);
4253 }
François Gaffiead447b72019-11-18 15:50:22 +01004254 } else {
4255 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4256 if (hwOutputDesc != 0) {
4257 // create Hwoutput and add to mHwOutputs
4258 } else {
4259 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4260 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004261 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004262 return NO_ERROR;
François Gaffiead447b72019-11-18 15:50:22 +01004263
4264FailureSourceActive:
4265 swOutput->stop();
4266 releaseOutput(sourceDesc->portId());
4267FailureSourceAdded:
4268 sourceDesc->setSwOutput(nullptr);
4269FailureReleasePatch:
4270 releaseAudioPatchInternal(handle);
4271 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004272}
4273
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004274status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004275{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004276 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4277 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004278 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004279 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004280 return BAD_VALUE;
4281 }
4282 status_t status = disconnectAudioSource(sourceDesc);
4283
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004284 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004285 return status;
4286}
4287
Andy Hung2ddee192015-12-18 17:34:44 -08004288status_t AudioPolicyManager::setMasterMono(bool mono)
4289{
4290 if (mMasterMono == mono) {
4291 return NO_ERROR;
4292 }
4293 mMasterMono = mono;
4294 // if enabling mono we close all offloaded devices, which will invalidate the
4295 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4296 // for recreating the new AudioTrack as non-offloaded PCM.
4297 //
4298 // If disabling mono, we leave all tracks as is: we don't know which clients
4299 // and tracks are able to be recreated as offloaded. The next "song" should
4300 // play back offloaded.
4301 if (mMasterMono) {
4302 Vector<audio_io_handle_t> offloaded;
4303 for (size_t i = 0; i < mOutputs.size(); ++i) {
4304 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4305 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4306 offloaded.push(desc->mIoHandle);
4307 }
4308 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004309 for (const auto& handle : offloaded) {
4310 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004311 }
4312 }
4313 // update master mono for all remaining outputs
4314 for (size_t i = 0; i < mOutputs.size(); ++i) {
4315 updateMono(mOutputs.keyAt(i));
4316 }
4317 return NO_ERROR;
4318}
4319
4320status_t AudioPolicyManager::getMasterMono(bool *mono)
4321{
4322 *mono = mMasterMono;
4323 return NO_ERROR;
4324}
4325
Eric Laurentac9cef52017-06-09 15:46:26 -07004326float AudioPolicyManager::getStreamVolumeDB(
4327 audio_stream_type_t stream, int index, audio_devices_t device)
4328{
jiabin12dc6b02019-10-01 09:38:30 -07004329 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004330}
4331
jiabin81772902018-04-02 17:52:27 -07004332status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4333 audio_format_t *surroundFormats,
4334 bool *surroundFormatsEnabled,
4335 bool reported)
4336{
4337 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4338 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4339 return BAD_VALUE;
4340 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004341 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4342 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004343
4344 size_t formatsWritten = 0;
4345 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004346 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004347 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004348 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004349 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004350 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4351 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4352 FormatVector supportedFormats =
4353 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
4354 for (size_t j = 0; j < supportedFormats.size(); j++) {
4355 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
4356 formats.insert(supportedFormats[j]);
4357 } else {
4358 for (const auto& pair : mConfig.getSurroundFormats()) {
4359 if (pair.second.count(supportedFormats[j]) != 0) {
4360 formats.insert(pair.first);
4361 break;
4362 }
4363 }
4364 }
4365 }
jiabin81772902018-04-02 17:52:27 -07004366 }
4367 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004368 for (const auto& pair : mConfig.getSurroundFormats()) {
4369 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004370 }
4371 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004372 *numSurroundFormats = formats.size();
4373 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4374 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004375 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004376 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004377 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004378 bool formatEnabled = true;
4379 switch (forceUse) {
4380 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4381 formatEnabled = mManualSurroundFormats.count(format) != 0;
4382 break;
4383 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4384 formatEnabled = false;
4385 break;
4386 default: // AUTO or ALWAYS => true
4387 break;
jiabin81772902018-04-02 17:52:27 -07004388 }
4389 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4390 }
jiabin81772902018-04-02 17:52:27 -07004391 }
4392 return NO_ERROR;
4393}
4394
4395status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4396{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004397 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004398 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4399 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004400 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004401 return BAD_VALUE;
4402 }
4403
Mikhail Naganov100f0122018-11-29 11:22:16 -08004404 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4405 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004406 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004407 return INVALID_OPERATION;
4408 }
4409
Mikhail Naganov100f0122018-11-29 11:22:16 -08004410 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004411 return NO_ERROR;
4412 }
4413
Mikhail Naganov100f0122018-11-29 11:22:16 -08004414 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004415 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004416 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004417 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004418 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004419 }
4420 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004421 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004422 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004423 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004424 }
4425 }
4426
4427 sp<SwAudioOutputDescriptor> outputDesc;
4428 bool profileUpdated = false;
jiabin12dc6b02019-10-01 09:38:30 -07004429 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4430 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004431 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4432 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004433 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004434 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004435 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4436 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4437 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004438 name.c_str(),
4439 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004440 if (status != NO_ERROR) {
4441 continue;
4442 }
4443 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4445 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004446 name.c_str(),
4447 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004448 profileUpdated |= (status == NO_ERROR);
4449 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004450 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin12dc6b02019-10-01 09:38:30 -07004451 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004452 AUDIO_DEVICE_IN_HDMI);
4453 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4454 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004455 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004456 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004457 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4458 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4459 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004460 name.c_str(),
4461 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004462 if (status != NO_ERROR) {
4463 continue;
4464 }
4465 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4466 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4467 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004468 name.c_str(),
4469 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004470 profileUpdated |= (status == NO_ERROR);
4471 }
4472
jiabin81772902018-04-02 17:52:27 -07004473 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004474 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004475 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004476 }
4477
4478 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4479}
4480
Eric Laurent5ada82e2019-08-29 17:53:54 -07004481void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004482{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004483 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004484 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004485 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004486 }
4487}
4488
jiabin6012f912018-11-02 17:06:30 -07004489bool AudioPolicyManager::isHapticPlaybackSupported()
4490{
4491 for (const auto& hwModule : mHwModules) {
4492 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4493 for (const auto &outProfile : outputProfiles) {
4494 struct audio_port audioPort;
4495 outProfile->toAudioPort(&audioPort);
4496 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4497 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4498 return true;
4499 }
4500 }
4501 }
4502 }
4503 return false;
4504}
4505
Eric Laurent8340e672019-11-06 11:01:08 -08004506bool AudioPolicyManager::isCallScreenModeSupported()
4507{
4508 return getConfig().isCallScreenModeSupported();
4509}
4510
4511
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004512status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004513{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004514 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffiead447b72019-11-18 15:50:22 +01004515 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4516 if (swOutput != 0) {
4517 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004518 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004519 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004520 }
François Gaffiead447b72019-11-18 15:50:22 +01004521 releaseOutput(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004522 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004523 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004524 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004525 // close Hwoutput and remove from mHwOutputs
4526 } else {
4527 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4528 }
4529 }
François Gaffiead447b72019-11-18 15:50:22 +01004530 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004531}
4532
François Gaffiec005e562018-11-06 15:04:49 +01004533sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4534 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004535{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004536 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004537 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004538 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004539 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004540 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4541 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004542 source = sourceDesc;
4543 break;
4544 }
4545 }
4546 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004547}
4548
Eric Laurente552edb2014-03-10 17:42:56 -07004549// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004550// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004551// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004552uint32_t AudioPolicyManager::nextAudioPortGeneration()
4553{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004554 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004555}
4556
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004557static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4558 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004559 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004560 status_t ret;
4561
Cheney Ni00ce33d2018-11-01 06:30:37 +08004562 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
Cheney Nie5985452019-02-24 01:39:15 +08004563 if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
4564 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4565 // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
4566 // the legacy hardware module for A2DP and hearing aid.
4567 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4568 } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4569 // A2DP offload supported but disabled: try to use special XML file
Cheney Ni6851adb2018-11-01 06:30:37 +08004570 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4571 }
Cheney Nie5985452019-02-24 01:39:15 +08004572 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
4573 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
Petri Gyntherf497f292018-04-17 18:46:10 -07004574 }
4575 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4576
4577 for (const char* fileName : fileNames) {
Mikhail Naganovedc0ae12020-04-14 14:47:01 -07004578 for (const auto& path : audio_get_configuration_paths()) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004579 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
Mikhail Naganovedc0ae12020-04-14 14:47:01 -07004580 "%s/%s", path.c_str(), fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004581 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004582 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004583 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004584 return ret;
4585 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004586 }
4587 }
4588 return ret;
4589}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004590
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004591AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4592 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004593 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004594 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004595 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004596 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004597 mA2dpSuspended(false),
Mikhail Naganov560095b2020-03-05 16:28:57 -08004598 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004599 mAudioPortGeneration(1),
4600 mBeaconMuteRefCount(0),
4601 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004602 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004603 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004604 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004605 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004606{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004607}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004608
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004609AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4610 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4611{
4612 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004613}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004614
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004615void AudioPolicyManager::loadConfig() {
4616 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004617 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004618 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004619 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004620}
4621
4622status_t AudioPolicyManager::initialize() {
Mikhail Naganove13c6792019-05-14 10:32:51 -07004623 {
4624 auto engLib = EngineLibrary::load(
4625 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4626 if (!engLib) {
4627 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4628 return NO_INIT;
4629 }
4630 mEngine = engLib->createEngine();
4631 if (mEngine == nullptr) {
4632 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4633 return NO_INIT;
4634 }
François Gaffie2110e042015-03-24 08:41:51 +01004635 }
4636 mEngine->setObserver(this);
4637 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004638 if (status != NO_ERROR) {
4639 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4640 return status;
4641 }
François Gaffie2110e042015-03-24 08:41:51 +01004642
Mikhail Naganov560095b2020-03-05 16:28:57 -08004643 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004644 // open all output streams needed to access attached devices
Mikhail Naganova30ec142020-03-24 09:32:34 -07004645 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004646
Eric Laurent3a4311c2014-03-17 12:00:47 -07004647 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004648 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4649 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4650 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004651 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004652 }
jiabin9ff780e2018-03-19 18:19:52 -07004653 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004654 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabin6713a382019-09-12 16:29:15 -07004655 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004656 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004657 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004658 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004659 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004660 }
4661 }
4662 }
Eric Laurente552edb2014-03-10 17:42:56 -07004663
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004664 if (mPrimaryOutput == 0) {
4665 ALOGE("Failed to open primary output");
4666 status = NO_INIT;
4667 }
Eric Laurente552edb2014-03-10 17:42:56 -07004668
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004669 // Silence ALOGV statements
4670 property_set("log.tag." LOG_TAG, "D");
4671
Eric Laurentcca11ce2020-11-25 15:31:27 +01004672 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4673 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4674
Eric Laurente552edb2014-03-10 17:42:56 -07004675 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004676 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004677}
4678
Eric Laurente0720872014-03-11 09:30:41 -07004679AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004680{
Eric Laurente552edb2014-03-10 17:42:56 -07004681 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004682 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004683 }
4684 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004685 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004686 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004687 mAvailableOutputDevices.clear();
4688 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004689 mOutputs.clear();
4690 mInputs.clear();
4691 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004692 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004693 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004694}
4695
Eric Laurente0720872014-03-11 09:30:41 -07004696status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004697{
Eric Laurent87ffa392015-05-22 10:32:38 -07004698 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004699}
4700
Eric Laurente552edb2014-03-10 17:42:56 -07004701// ---
4702
Mikhail Naganov560095b2020-03-05 16:28:57 -08004703void AudioPolicyManager::onNewAudioModulesAvailable()
4704{
Mikhail Naganova30ec142020-03-24 09:32:34 -07004705 DeviceVector newDevices;
4706 onNewAudioModulesAvailableInt(&newDevices);
4707 if (!newDevices.empty()) {
4708 nextAudioPortGeneration();
4709 mpClientInterface->onAudioPortListUpdate();
4710 }
4711}
4712
4713void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4714{
Mikhail Naganov560095b2020-03-05 16:28:57 -08004715 for (const auto& hwModule : mHwModulesAll) {
4716 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4717 continue;
4718 }
4719 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4720 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4721 ALOGW("could not open HW module %s", hwModule->getName());
4722 continue;
4723 }
4724 mHwModules.push_back(hwModule);
4725 // open all output streams needed to access attached devices
4726 // except for direct output streams that are only opened when they are actually
4727 // required by an app.
4728 // This also validates mAvailableOutputDevices list
4729 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4730 if (!outProfile->canOpenNewIo()) {
4731 ALOGE("Invalid Output profile max open count %u for profile %s",
4732 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4733 continue;
4734 }
4735 if (!outProfile->hasSupportedDevices()) {
4736 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4737 continue;
4738 }
4739 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4740 mTtsOutputAvailable = true;
4741 }
4742
Mikhail Naganov560095b2020-03-05 16:28:57 -08004743 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4744 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4745 sp<DeviceDescriptor> supportedDevice = 0;
4746 if (supportedDevices.contains(mDefaultOutputDevice)) {
4747 supportedDevice = mDefaultOutputDevice;
4748 } else {
4749 // choose first device present in profile's SupportedDevices also part of
4750 // mAvailableOutputDevices.
4751 if (availProfileDevices.isEmpty()) {
4752 continue;
4753 }
4754 supportedDevice = availProfileDevices.itemAt(0);
4755 }
4756 if (!mOutputDevicesAll.contains(supportedDevice)) {
4757 continue;
4758 }
4759 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4760 mpClientInterface);
4761 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4762 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4763 AUDIO_STREAM_DEFAULT,
4764 AUDIO_OUTPUT_FLAG_NONE, &output);
4765 if (status != NO_ERROR) {
4766 ALOGW("Cannot open output stream for devices %s on hw module %s",
4767 supportedDevice->toString().c_str(), hwModule->getName());
4768 continue;
4769 }
4770 for (const auto &device : availProfileDevices) {
4771 // give a valid ID to an attached device once confirmed it is reachable
4772 if (!device->isAttached()) {
4773 device->attach(hwModule);
4774 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004775 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004776 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004777 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4778 }
4779 }
4780 if (mPrimaryOutput == 0 &&
4781 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4782 mPrimaryOutput = outputDesc;
4783 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004784 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4785 outputDesc->close();
4786 } else {
4787 addOutput(output, outputDesc);
4788 setOutputDevices(outputDesc,
4789 DeviceVector(supportedDevice),
4790 true,
4791 0,
4792 NULL);
4793 }
Mikhail Naganov560095b2020-03-05 16:28:57 -08004794 }
4795 // open input streams needed to access attached devices to validate
4796 // mAvailableInputDevices list
4797 for (const auto& inProfile : hwModule->getInputProfiles()) {
4798 if (!inProfile->canOpenNewIo()) {
4799 ALOGE("Invalid Input profile max open count %u for profile %s",
4800 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4801 continue;
4802 }
4803 if (!inProfile->hasSupportedDevices()) {
4804 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4805 continue;
4806 }
4807 // chose first device present in profile's SupportedDevices also part of
4808 // available input devices
4809 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4810 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4811 if (availProfileDevices.isEmpty()) {
4812 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4813 continue;
4814 }
4815 sp<AudioInputDescriptor> inputDesc =
4816 new AudioInputDescriptor(inProfile, mpClientInterface);
4817
4818 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4819 status_t status = inputDesc->open(nullptr,
4820 availProfileDevices.itemAt(0),
4821 AUDIO_SOURCE_MIC,
4822 AUDIO_INPUT_FLAG_NONE,
4823 &input);
4824 if (status != NO_ERROR) {
4825 ALOGW("Cannot open input stream for device %s on hw module %s",
4826 availProfileDevices.toString().c_str(),
4827 hwModule->getName());
4828 continue;
4829 }
4830 for (const auto &device : availProfileDevices) {
4831 // give a valid ID to an attached device once confirmed it is reachable
4832 if (!device->isAttached()) {
4833 device->attach(hwModule);
4834 device->importAudioPortAndPickAudioProfile(inProfile, true);
4835 mAvailableInputDevices.add(device);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004836 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004837 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4838 }
4839 }
4840 inputDesc->close();
4841 }
4842 }
4843}
4844
Eric Laurent98e38192018-02-15 18:31:53 -08004845void AudioPolicyManager::addOutput(audio_io_handle_t output,
4846 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004847{
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 mOutputs.add(output, outputDesc);
jiabin12dc6b02019-10-01 09:38:30 -07004849 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004850 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004851 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004852 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004853}
4854
François Gaffie53615e22015-03-19 09:24:12 +01004855void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4856{
4857 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004858 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004859}
4860
Eric Laurent98e38192018-02-15 18:31:53 -08004861void AudioPolicyManager::addInput(audio_io_handle_t input,
4862 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004863{
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004866}
Eric Laurente552edb2014-03-10 17:42:56 -07004867
François Gaffie11d30102018-11-02 16:09:09 +01004868status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004869 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004870 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004871{
François Gaffie11d30102018-11-02 16:09:09 +01004872 audio_devices_t deviceType = device->type();
jiabin6713a382019-09-12 16:29:15 -07004873 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004874 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004875
François Gaffie11d30102018-11-02 16:09:09 +01004876 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004877 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004878 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004879 }
Eric Laurente552edb2014-03-10 17:42:56 -07004880
Eric Laurent3b73df72014-03-11 09:06:29 -07004881 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 // first list already open outputs that can be routed to this device
4883 for (size_t i = 0; i < mOutputs.size(); i++) {
4884 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004885 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07004886 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004887 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4888 mOutputs.keyAt(i), device->toString().c_str());
4889 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004890 }
4891 }
4892 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004893 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004894 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004895 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4896 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004897 if (profile->supportsDevice(device)) {
4898 profiles.add(profile);
4899 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4900 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004901 }
4902 }
4903 }
4904
Eric Laurent7b279bb2015-12-14 10:18:23 -08004905 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004906
Eric Laurente552edb2014-03-10 17:42:56 -07004907 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004908 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004909 return BAD_VALUE;
4910 }
4911
4912 // open outputs for matching profiles if needed. Direct outputs are also opened to
4913 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4914 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004915 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004916
4917 // nothing to do if one output is already opened for this profile
4918 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004919 for (j = 0; j < outputs.size(); j++) {
4920 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004921 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004922 // matching profile: save the sample rates, format and channel masks supported
4923 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004924 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07004925 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004926 }
Eric Laurente552edb2014-03-10 17:42:56 -07004927 break;
4928 }
4929 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004930 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004931 continue;
4932 }
4933
Eric Laurent3974e3b2017-12-07 17:58:43 -08004934 if (!profile->canOpenNewIo()) {
4935 ALOGW("Max Output number %u already opened for this profile %s",
4936 profile->maxOpenCount, profile->getTagName().c_str());
4937 continue;
4938 }
4939
Eric Laurent83efe1c2017-07-09 16:51:08 -07004940 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabineaf09f02019-08-19 15:08:30 -07004941 deviceType, address.string(), profile.get(), profile->getName().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004942 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004943 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004944 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004945 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004946
Eric Laurentfe231122017-11-17 17:48:06 -08004947 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004948 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004949 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004950 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004951 mpClientInterface->setParameters(output, String8(param));
4952 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004953 }
François Gaffie11d30102018-11-02 16:09:09 +01004954 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004955 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004956 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004957 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004958 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004959 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004960 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004961 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004962 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4963 profile->pickAudioProfile(
4964 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004965 config.offload_info.sample_rate = config.sample_rate;
4966 config.offload_info.channel_mask = config.channel_mask;
4967 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004968
François Gaffie11d30102018-11-02 16:09:09 +01004969 status_t status = desc->open(&config, DeviceVector(device),
4970 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004971 AUDIO_OUTPUT_FLAG_NONE, &output);
4972 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004973 output = AUDIO_IO_HANDLE_NONE;
4974 }
Eric Laurentd4692962014-05-05 18:13:44 -07004975 }
4976
Eric Laurentcf2c0212014-07-25 16:20:43 -07004977 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004978 addOutput(output, desc);
Eric Laurent0e26e3f2020-04-29 14:24:16 -07004979 if (audio_is_remote_submix_device(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004980 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004981 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix)
4982 == NO_ERROR) {
François Gaffieb141c522018-03-12 11:47:40 +01004983 policyMix->setOutput(desc);
Mikhail Naganovbfac5832019-03-05 16:55:28 -08004984 desc->mPolicyMix = policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004985 } else {
4986 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004987 address.string());
4988 }
François Gaffie036e1e92015-03-19 10:16:24 +01004989
Eric Laurent87ffa392015-05-22 10:32:38 -07004990 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4991 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004992 // no duplicated output for direct outputs and
4993 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004994 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004995
Eric Laurentd4692962014-05-05 18:13:44 -07004996 //TODO: configure audio effect output stage here
4997
4998 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004999 sp<SwAudioOutputDescriptor> dupOutputDesc =
5000 new SwAudioOutputDescriptor(NULL, mpClientInterface);
5001 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
5002 &duplicatedOutput);
5003 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07005004 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07005005 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07005006 } else {
5007 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005008 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08005009 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01005010 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005012 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005013 }
Eric Laurente552edb2014-03-10 17:42:56 -07005014 }
5015 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07005016 } else {
5017 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07005018 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07005019 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005020 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005021 profiles.removeAt(profile_index);
5022 profile_index--;
5023 } else {
5024 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005025 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005026 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07005027 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005028 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005029
François Gaffie11d30102018-11-02 16:09:09 +01005030 if (device_distinguishes_on_address(deviceType)) {
5031 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5032 device->toString().c_str());
5033 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5034 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005035 }
Eric Laurente552edb2014-03-10 17:42:56 -07005036 ALOGV("checkOutputsForDevice(): adding output %d", output);
5037 }
5038 }
5039
5040 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005041 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005042 return BAD_VALUE;
5043 }
Eric Laurentd4692962014-05-05 18:13:44 -07005044 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005045 // check if one opened output is not needed any more after disconnecting one device
5046 for (size_t i = 0; i < mOutputs.size(); i++) {
5047 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005048 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005049 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005050 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07005051 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005052 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005053 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005054 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5055 mOutputs.keyAt(i));
5056 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005057 }
Eric Laurente552edb2014-03-10 17:42:56 -07005058 }
5059 }
Eric Laurentd4692962014-05-05 18:13:44 -07005060 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005061 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005062 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5063 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005064 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07005065 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08005066 "clearing direct output profile %zu on module %s",
5067 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005068 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07005069 }
5070 }
5071 }
5072 }
5073 return NO_ERROR;
5074}
5075
François Gaffie11d30102018-11-02 16:09:09 +01005076status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005077 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005078{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005079 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005080
François Gaffie11d30102018-11-02 16:09:09 +01005081 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005082 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005083 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005084 }
5085
Eric Laurentd4692962014-05-05 18:13:44 -07005086 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005087 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005088 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005089 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005090 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005091 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005092 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005093 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005094
François Gaffie11d30102018-11-02 16:09:09 +01005095 if (profile->supportsDevice(device)) {
5096 profiles.add(profile);
5097 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5098 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005099 }
5100 }
5101 }
5102
Eric Laurent0dd51852019-04-19 18:18:58 -07005103 if (profiles.isEmpty()) {
5104 ALOGW("%s: No input profile available for device %s",
5105 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005106 return BAD_VALUE;
5107 }
5108
5109 // open inputs for matching profiles if needed. Direct inputs are also opened to
5110 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5111 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5112
Eric Laurent1c333e22014-05-20 10:48:17 -07005113 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005114
Eric Laurentd4692962014-05-05 18:13:44 -07005115 // nothing to do if one input is already opened for this profile
5116 size_t input_index;
5117 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5118 desc = mInputs.valueAt(input_index);
5119 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005120 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07005121 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005122 }
Eric Laurentd4692962014-05-05 18:13:44 -07005123 break;
5124 }
5125 }
5126 if (input_index != mInputs.size()) {
5127 continue;
5128 }
5129
Eric Laurent3974e3b2017-12-07 17:58:43 -08005130 if (!profile->canOpenNewIo()) {
5131 ALOGW("Max Input number %u already opened for this profile %s",
5132 profile->maxOpenCount, profile->getTagName().c_str());
5133 continue;
5134 }
5135
Eric Laurentfe231122017-11-17 17:48:06 -08005136 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005137 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005138 status_t status = desc->open(nullptr,
5139 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005140 AUDIO_SOURCE_MIC,
5141 AUDIO_INPUT_FLAG_NONE,
5142 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005143
Eric Laurentcf2c0212014-07-25 16:20:43 -07005144 if (status == NO_ERROR) {
jiabin6713a382019-09-12 16:29:15 -07005145 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005146 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005147 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005148 mpClientInterface->setParameters(input, String8(param));
5149 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005150 }
François Gaffie11d30102018-11-02 16:09:09 +01005151 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005152 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005153 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005154 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005155 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005156 }
5157
Eric Laurent0dd51852019-04-19 18:18:58 -07005158 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005159 addInput(input, desc);
5160 }
5161 } // endif input != 0
5162
Eric Laurentcf2c0212014-07-25 16:20:43 -07005163 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005164 ALOGW("%s could not open input for device %s", __func__,
5165 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005166 profiles.removeAt(profile_index);
5167 profile_index--;
5168 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005169 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07005170 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005171 }
Eric Laurentd4692962014-05-05 18:13:44 -07005172 ALOGV("checkInputsForDevice(): adding input %d", input);
5173 }
5174 } // end scan profiles
5175
5176 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005177 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005178 return BAD_VALUE;
5179 }
5180 } else {
5181 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005182 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005183 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005184 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005185 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005186 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005187 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005188 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005189 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5190 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005191 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005192 }
5193 }
5194 }
5195 } // end disconnect
5196
5197 return NO_ERROR;
5198}
5199
5200
Eric Laurente0720872014-03-11 09:30:41 -07005201void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005202{
5203 ALOGV("closeOutput(%d)", output);
5204
François Gaffie1c878552018-11-22 16:53:21 +01005205 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5206 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005207 ALOGW("closeOutput() unknown output %d", output);
5208 return;
5209 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005210 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005211 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005212
Eric Laurente552edb2014-03-10 17:42:56 -07005213 // look for duplicated outputs connected to the output being removed.
5214 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005215 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5216 if (dupOutput->isDuplicated() &&
5217 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5218 sp<SwAudioOutputDescriptor> remainingOutput =
5219 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005220 // As all active tracks on duplicated output will be deleted,
5221 // and as they were also referenced on the other output, the reference
5222 // count for their stream type must be adjusted accordingly on
5223 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005224 const bool wasActive = remainingOutput->isActive();
5225 // Note: no-op on the closing output where all clients has already been set inactive
5226 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005227 // stop() will be a no op if the output is still active but is needed in case all
5228 // active streams refcounts where cleared above
5229 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005230 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005231 }
Eric Laurente552edb2014-03-10 17:42:56 -07005232 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5233 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5234
5235 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005236 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005237 }
5238 }
5239
Eric Laurent05b90f82014-08-27 15:32:29 -07005240 nextAudioPortGeneration();
5241
François Gaffie1c878552018-11-22 16:53:21 +01005242 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005243 if (index >= 0) {
5244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005245 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5246 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005247 mAudioPatches.removeItemsAt(index);
5248 mpClientInterface->onAudioPatchListUpdate();
5249 }
5250
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005251 if (closingOutputWasActive) {
5252 closingOutput->stop();
5253 }
François Gaffie1c878552018-11-22 16:53:21 +01005254 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005255
François Gaffie53615e22015-03-19 09:24:12 +01005256 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005257 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005258
5259 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5260 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005261 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005262 bool directOutputOpen = false;
5263 for (size_t i = 0; i < mOutputs.size(); i++) {
5264 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5265 directOutputOpen = true;
5266 break;
5267 }
5268 }
5269 if (!directOutputOpen) {
5270 ALOGV("no direct outputs open, reset MSD patch");
5271 setMsdPatch();
5272 }
5273 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005274}
5275
5276void AudioPolicyManager::closeInput(audio_io_handle_t input)
5277{
5278 ALOGV("closeInput(%d)", input);
5279
5280 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5281 if (inputDesc == NULL) {
5282 ALOGW("closeInput() unknown input %d", input);
5283 return;
5284 }
5285
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005287
François Gaffie11d30102018-11-02 16:09:09 +01005288 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005289 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005290 if (index >= 0) {
5291 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005292 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5293 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005294 mAudioPatches.removeItemsAt(index);
5295 mpClientInterface->onAudioPatchListUpdate();
5296 }
5297
Eric Laurentfe231122017-11-17 17:48:06 -08005298 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005299 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005300
François Gaffie11d30102018-11-02 16:09:09 +01005301 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5302 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005303 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005304 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005305 }
Eric Laurente552edb2014-03-10 17:42:56 -07005306}
5307
François Gaffie11d30102018-11-02 16:09:09 +01005308SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5309 const DeviceVector &devices,
5310 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005311{
5312 SortedVector<audio_io_handle_t> outputs;
5313
François Gaffie11d30102018-11-02 16:09:09 +01005314 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005315 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005316 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005317 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005318 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005319 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin12dc6b02019-10-01 09:38:30 -07005320 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005321 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005322 outputs.add(openOutputs.keyAt(i));
5323 }
5324 }
5325 return outputs;
5326}
5327
Mikhail Naganov37977152018-07-11 15:54:44 -07005328void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5329{
5330 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5331 // output is suspended before any tracks are moved to it
5332 checkA2dpSuspend();
5333 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005334 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005335 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005336 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005337 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005338 setMsdPatch();
5339 }
Mikhail Naganov37977152018-07-11 15:54:44 -07005340}
5341
François Gaffiec005e562018-11-06 15:04:49 +01005342bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5343 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005344{
François Gaffiec005e562018-11-06 15:04:49 +01005345 return mEngine->getProductStrategyForAttributes(lAttr) ==
5346 mEngine->getProductStrategyForAttributes(rAttr);
5347}
5348
5349void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5350{
5351 auto psId = mEngine->getProductStrategyForAttributes(attr);
5352
5353 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5354 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07005355
François Gaffie11d30102018-11-02 16:09:09 +01005356 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5357 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005358
Eric Laurentc209fe42020-06-05 18:11:23 -07005359 uint32_t maxLatency = 0;
5360 bool invalidate = false;
5361 // take into account dynamic audio policies related changes: if a client is now associated
5362 // to a different policy mix than at creation time, invalidate corresponding stream
5363 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5364 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5365 if (desc->isDuplicated()) {
5366 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005367 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005368 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5369 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5370 continue;
5371 }
5372 sp<AudioPolicyMix> primaryMix;
5373 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5374 client->flags(), primaryMix, nullptr);
5375 if (status != OK) {
5376 continue;
5377 }
5378 if (client->getPrimaryMix() != primaryMix) {
5379 invalidate = true;
5380 if (desc->isStrategyActive(psId)) {
5381 maxLatency = desc->latency();
5382 }
5383 break;
5384 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005385 }
5386 }
5387
Eric Laurentc209fe42020-06-05 18:11:23 -07005388 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005389 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5390 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005391 for (audio_io_handle_t srcOut : srcOutputs) {
5392 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005393 if (desc == nullptr) continue;
5394
5395 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005396 maxLatency = desc->latency();
5397 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005398
5399 if (invalidate) continue;
5400
5401 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005402 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005403 // a client on a non direct outputs has necessarily a linear PCM format
5404 // so we can call selectOutput() safely
5405 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5406 client->flags(),
5407 client->config().format,
5408 client->config().channel_mask,
5409 client->config().sample_rate);
5410 if (newOutput != srcOut) {
5411 invalidate = true;
5412 break;
5413 }
5414 } else {
5415 sp<IOProfile> profile = getProfileForOutput(newDevices,
5416 client->config().sample_rate,
5417 client->config().format,
5418 client->config().channel_mask,
5419 client->flags(),
5420 true /* directOnly */);
5421 if (profile != desc->mProfile) {
5422 invalidate = true;
5423 break;
5424 }
5425 }
5426 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005427 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005428
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005429 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005430 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005431 std::to_string(srcOutputs[0]).c_str(),
5432 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005433 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005434 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005435 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005436 if (desc == nullptr) continue;
5437
5438 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005439 setStrategyMute(psId, true, desc);
5440 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005441 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005442 }
François Gaffiec005e562018-11-06 15:04:49 +01005443 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005444 if (source != 0){
5445 connectAudioSource(source);
5446 }
Eric Laurente552edb2014-03-10 17:42:56 -07005447 }
5448
François Gaffiec005e562018-11-06 15:04:49 +01005449 // Move effects associated to this stream from previous output to new output
5450 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005451 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005452 }
François Gaffiec005e562018-11-06 15:04:49 +01005453 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005454 if (invalidate) {
5455 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5456 mpClientInterface->invalidateStream(stream);
5457 }
Eric Laurente552edb2014-03-10 17:42:56 -07005458 }
5459 }
5460}
5461
Eric Laurente0720872014-03-11 09:30:41 -07005462void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005463{
François Gaffiec005e562018-11-06 15:04:49 +01005464 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5465 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5466 checkOutputForAttributes(attributes);
5467 }
Eric Laurente552edb2014-03-10 17:42:56 -07005468}
5469
Kevin Rocard153f92d2018-12-18 18:33:28 -08005470void AudioPolicyManager::checkSecondaryOutputs() {
5471 std::set<audio_stream_type_t> streamsToInvalidate;
5472 for (size_t i = 0; i < mOutputs.size(); i++) {
5473 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5474 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005475 sp<AudioPolicyMix> primaryMix;
5476 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005477 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005478 client->flags(), primaryMix, &secondaryMixes);
5479 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5480 for (auto &secondaryMix : secondaryMixes) {
5481 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5482 if (outputDesc != nullptr &&
5483 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5484 secondaryDescs.push_back(outputDesc);
5485 }
5486 }
5487
Kevin Rocard94114a22019-04-01 19:38:23 -07005488 if (status != OK ||
5489 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005490 client->getSecondaryOutputs().end(),
5491 secondaryDescs.begin(), secondaryDescs.end())) {
5492 streamsToInvalidate.insert(client->stream());
5493 }
5494 }
5495 }
5496 for (audio_stream_type_t stream : streamsToInvalidate) {
5497 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5498 mpClientInterface->invalidateStream(stream);
5499 }
5500}
5501
Eric Laurentcca11ce2020-11-25 15:31:27 +01005502bool AudioPolicyManager::isScoRequestedForComm() const {
5503 AudioDeviceTypeAddrVector devices;
5504 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5505 for (const auto &device : devices) {
5506 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5507 return true;
5508 }
5509 }
5510 return false;
5511}
5512
Eric Laurente0720872014-03-11 09:30:41 -07005513void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005514{
François Gaffie53615e22015-03-19 09:24:12 +01005515 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005516 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005517 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005518 return;
5519 }
5520
Eric Laurent3a4311c2014-03-17 12:00:47 -07005521 bool isScoConnected =
jiabin12dc6b02019-10-01 09:38:30 -07005522 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5523 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurentcca11ce2020-11-25 15:31:27 +01005524 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005525
5526 // if suspended, restore A2DP output if:
5527 // ((SCO device is NOT connected) ||
Eric Laurentcca11ce2020-11-25 15:31:27 +01005528 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005529 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005530 //
Eric Laurentf732e072016-08-03 19:30:28 -07005531 // if not suspended, suspend A2DP output if:
5532 // (SCO device is connected) &&
Eric Laurentcca11ce2020-11-25 15:31:27 +01005533 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005534 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005535 //
5536 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005537 if (!isScoConnected ||
Eric Laurentcca11ce2020-11-25 15:31:27 +01005538 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005539 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005540 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005541
5542 mpClientInterface->restoreOutput(a2dpOutput);
5543 mA2dpSuspended = false;
5544 }
5545 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005546 if (isScoConnected &&
Eric Laurentcca11ce2020-11-25 15:31:27 +01005547 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005548 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005549 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005550
5551 mpClientInterface->suspendOutput(a2dpOutput);
5552 mA2dpSuspended = true;
5553 }
5554 }
5555}
5556
François Gaffie11d30102018-11-02 16:09:09 +01005557DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5558 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005559{
François Gaffie11d30102018-11-02 16:09:09 +01005560 DeviceVector devices;
5561
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005562 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005563 if (index >= 0) {
5564 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005565 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005566 ALOGV("%s device %s forced by patch %d", __func__,
5567 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5568 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005569 }
5570 }
5571
Dean Wheatley514b4312020-06-17 21:45:00 +10005572 // Do not retrieve engine device for outputs through MSD
5573 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5574 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5575 return outputDesc->devices();
5576 }
5577
Eric Laurent97ac8712018-07-27 18:59:02 -07005578 // Honor explicit routing requests only if no client using default routing is active on this
5579 // input: a specific app can not force routing for other apps by setting a preferred device.
5580 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005581 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005582 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005583 if (device != nullptr) {
5584 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005585 }
5586
François Gaffiea807ef92018-11-05 10:44:33 +01005587 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5588 // of setForceUse / Default Bus device here
5589 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5590 if (device != nullptr) {
5591 return DeviceVector(device);
5592 }
5593
François Gaffiec005e562018-11-06 15:04:49 +01005594 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5595 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5596 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005597
François Gaffiec005e562018-11-06 15:04:49 +01005598 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005599 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5600 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005601 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005602 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5603 outputDesc->isStrategyActive(productStrategy)) {
5604 // Retrieval of devices for voice DL is done on primary output profile, cannot
5605 // check the route (would force modifying configuration file for this profile)
5606 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5607 break;
5608 }
Eric Laurente552edb2014-03-10 17:42:56 -07005609 }
François Gaffiec005e562018-11-06 15:04:49 +01005610 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005611 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005612}
5613
François Gaffie11d30102018-11-02 16:09:09 +01005614sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5615 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005616{
François Gaffie11d30102018-11-02 16:09:09 +01005617 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005618
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005619 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005620 if (index >= 0) {
5621 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005622 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005623 ALOGV("getNewInputDevice() device %s forced by patch %d",
5624 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5625 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005626 }
5627 }
5628
Eric Laurent97ac8712018-07-27 18:59:02 -07005629 // Honor explicit routing requests only if no client using default routing is active on this
5630 // input: a specific app can not force routing for other apps by setting a preferred device.
5631 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005632 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5633 if (device != nullptr) {
5634 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005635 }
5636
Eric Laurentdc95a252018-04-12 12:46:56 -07005637 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005638 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005639 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5640 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5641 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005642 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005643 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005644 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005645 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005646
Eric Laurente552edb2014-03-10 17:42:56 -07005647 return device;
5648}
5649
Eric Laurent794fde22016-03-11 09:50:45 -08005650bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5651 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005652 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005653}
5654
Eric Laurente0720872014-03-11 09:30:41 -07005655audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005656 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005657 // getOutputDevicesForStream's behavior for invalid streams.
5658 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5659 // device for music stream), but we want to return the empty set.
5660 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005661 return AUDIO_DEVICE_NONE;
5662 }
François Gaffie11d30102018-11-02 16:09:09 +01005663 DeviceVector activeDevices;
5664 DeviceVector devices;
Mikhail Naganovdc6be0d2020-09-25 23:03:05 +00005665 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5666 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005667 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005668 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005669 }
François Gaffiec005e562018-11-06 15:04:49 +01005670 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005671 devices.merge(curDevices);
5672 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005673 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005674 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005675 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005676 }
5677 }
Eric Laurente552edb2014-03-10 17:42:56 -07005678 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005679
Eric Laurentb0688d62018-08-14 15:49:18 -07005680 // Favor devices selected on active streams if any to report correct device in case of
5681 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005682 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005683 devices = activeDevices;
5684 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005685 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5686 and doesn't really need to.*/
jiabin12dc6b02019-10-01 09:38:30 -07005687 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005688 if (!speakerSafeDevices.isEmpty()) {
jiabin12dc6b02019-10-01 09:38:30 -07005689 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005690 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005691 }
jiabin12dc6b02019-10-01 09:38:30 -07005692 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5693 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005694}
5695
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005696status_t AudioPolicyManager::getDevicesForAttributes(
5697 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5698 if (devices == nullptr) {
5699 return BAD_VALUE;
5700 }
5701 // check dynamic policies but only for primary descriptors (secondary not used for audible
5702 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005703 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005704 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005705 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005706 if (status != OK) {
5707 return status;
5708 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005709 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5710 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5711 devices->push_back(device);
5712 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005713 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005714 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5715 for (const auto& device : curDevices) {
5716 devices->push_back(device->getDeviceTypeAddr());
5717 }
5718 return NO_ERROR;
5719}
5720
Eric Laurente0720872014-03-11 09:30:41 -07005721void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005722 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005723 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005724 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005725 updateDevicesAndOutputs();
5726 break;
5727 default:
5728 break;
5729 }
5730}
5731
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005732uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005733
5734 // skip beacon mute management if a dedicated TTS output is available
5735 if (mTtsOutputAvailable) {
5736 return 0;
5737 }
5738
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005739 switch(event) {
5740 case STARTING_OUTPUT:
5741 mBeaconMuteRefCount++;
5742 break;
5743 case STOPPING_OUTPUT:
5744 if (mBeaconMuteRefCount > 0) {
5745 mBeaconMuteRefCount--;
5746 }
5747 break;
5748 case STARTING_BEACON:
5749 mBeaconPlayingRefCount++;
5750 break;
5751 case STOPPING_BEACON:
5752 if (mBeaconPlayingRefCount > 0) {
5753 mBeaconPlayingRefCount--;
5754 }
5755 break;
5756 }
5757
5758 if (mBeaconMuteRefCount > 0) {
5759 // any playback causes beacon to be muted
5760 return setBeaconMute(true);
5761 } else {
5762 // no other playback: unmute when beacon starts playing, mute when it stops
5763 return setBeaconMute(mBeaconPlayingRefCount == 0);
5764 }
5765}
5766
5767uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5768 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5769 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5770 // keep track of muted state to avoid repeating mute/unmute operations
5771 if (mBeaconMuted != mute) {
5772 // mute/unmute AUDIO_STREAM_TTS on all outputs
5773 ALOGV("\t muting %d", mute);
5774 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005775 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005776 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005777 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07005778 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005779 const uint32_t latency = desc->latency() * 2;
Eric Laurent33897ba2020-07-23 10:57:02 -07005780 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005781 maxLatency = latency;
5782 }
5783 }
5784 mBeaconMuted = mute;
5785 return maxLatency;
5786 }
5787 return 0;
5788}
5789
Eric Laurente0720872014-03-11 09:30:41 -07005790void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005791{
François Gaffiec005e562018-11-06 15:04:49 +01005792 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005793 mPreviousOutputs = mOutputs;
5794}
5795
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005796uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005797 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005798 uint32_t delayMs)
5799{
5800 // mute/unmute strategies using an incompatible device combination
5801 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5802 // if unmuting, unmute only after the specified delay
5803 if (outputDesc->isDuplicated()) {
5804 return 0;
5805 }
5806
5807 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005808 DeviceVector devices = outputDesc->devices();
5809 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005810
François Gaffiec005e562018-11-06 15:04:49 +01005811 auto productStrategies = mEngine->getOrderedProductStrategies();
5812 for (const auto &productStrategy : productStrategies) {
5813 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5814 DeviceVector curDevices =
5815 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5816 curDevices = curDevices.filter(outputDesc->supportedDevices());
5817 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005818 bool doMute = false;
5819
François Gaffiec005e562018-11-06 15:04:49 +01005820 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005821 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005822 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5823 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005824 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005825 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005826 }
Eric Laurent99401132014-05-07 19:48:15 -07005827 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005828 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005829 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005830 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005831 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005832 continue;
5833 }
François Gaffiec005e562018-11-06 15:04:49 +01005834 ALOGVV("%s() %s (curDevice %s)", __func__,
5835 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5836 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5837 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005838 if (mute) {
5839 // FIXME: should not need to double latency if volume could be applied
5840 // immediately by the audioflinger mixer. We must account for the delay
5841 // between now and the next time the audioflinger thread for this output
5842 // will process a buffer (which corresponds to one buffer size,
5843 // usually 1/2 or 1/4 of the latency).
5844 if (muteWaitMs < desc->latency() * 2) {
5845 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005846 }
5847 }
5848 }
5849 }
5850 }
5851 }
5852
Eric Laurent99401132014-05-07 19:48:15 -07005853 // temporary mute output if device selection changes to avoid volume bursts due to
5854 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005855 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005856 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5857 // temporary mute duration is conservatively set to 4 times the reported latency
5858 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5859 if (muteWaitMs < tempMuteWaitMs) {
5860 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005861 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005862 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5863 // make sure that we do not start the temporary mute period too early in case of
5864 // delayed device change
5865 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5866 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005867 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005868 }
5869 }
5870
Eric Laurente552edb2014-03-10 17:42:56 -07005871 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5872 if (muteWaitMs > delayMs) {
5873 muteWaitMs -= delayMs;
5874 usleep(muteWaitMs * 1000);
5875 return muteWaitMs;
5876 }
5877 return 0;
5878}
5879
François Gaffie11d30102018-11-02 16:09:09 +01005880uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5881 const DeviceVector &devices,
5882 bool force,
5883 int delayMs,
5884 audio_patch_handle_t *patchHandle,
5885 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005886{
François Gaffie11d30102018-11-02 16:09:09 +01005887 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005888 uint32_t muteWaitMs;
5889
5890 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005891 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5892 nullptr /* patchHandle */, requiresMuteCheck);
5893 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5894 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005895 return muteWaitMs;
5896 }
Eric Laurente552edb2014-03-10 17:42:56 -07005897
5898 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005899 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005900 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005901
François Gaffie11d30102018-11-02 16:09:09 +01005902 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5903
5904 if (!filteredDevices.isEmpty()) {
5905 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005906 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005907
5908 // if the outputs are not materially active, there is no need to mute.
5909 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005910 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005911 } else {
5912 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5913 muteWaitMs = 0;
5914 }
Eric Laurente552edb2014-03-10 17:42:56 -07005915
Eric Laurent79ea9582020-06-11 18:49:24 -07005916 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5917 // output profile or if new device is not supported AND previous device(s) is(are) still
5918 // available (otherwise reset device must be done on the output)
5919 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5920 !mAvailableOutputDevices.filter(prevDevices).empty()) {
5921 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5922 // restore previous device after evaluating strategy mute state
5923 outputDesc->setDevices(prevDevices);
5924 return muteWaitMs;
5925 }
5926
Eric Laurente552edb2014-03-10 17:42:56 -07005927 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005928 // the requested device is AUDIO_DEVICE_NONE
5929 // OR the requested device is the same as current device
5930 // AND force is not specified
5931 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005932 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005933 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005934 !force && outputDesc->getPatchHandle() != 0) {
5935 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5936 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005937 return muteWaitMs;
5938 }
5939
François Gaffie11d30102018-11-02 16:09:09 +01005940 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005941
Eric Laurente552edb2014-03-10 17:42:56 -07005942 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005943 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005944 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005945 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005946 PatchBuilder patchBuilder;
5947 patchBuilder.addSource(outputDesc);
5948 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5949 for (const auto &filteredDevice : filteredDevices) {
5950 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005951 }
5952
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005953 // Add half reported latency to delayMs when muteWaitMs is null in order
5954 // to avoid disordered sequence of muting volume and changing devices.
5955 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5956 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005957 }
Eric Laurente552edb2014-03-10 17:42:56 -07005958
5959 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005960 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005961
5962 return muteWaitMs;
5963}
5964
Eric Laurentc75307b2015-03-17 15:29:32 -07005965status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005966 int delayMs,
5967 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005968{
Eric Laurent6a94d692014-05-20 11:18:06 -07005969 ssize_t index;
5970 if (patchHandle) {
5971 index = mAudioPatches.indexOfKey(*patchHandle);
5972 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005973 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005974 }
5975 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005976 return INVALID_OPERATION;
5977 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005978 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005979 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005980 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005981 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01005982 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005983 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005984 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005985 return status;
5986}
5987
5988status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005989 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005990 bool force,
5991 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005992{
5993 status_t status = NO_ERROR;
5994
Eric Laurent1f2f2232014-06-02 12:01:23 -07005995 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005996 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5997 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005998
François Gaffie11d30102018-11-02 16:09:09 +01005999 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006000 PatchBuilder patchBuilder;
6001 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006002 // AUDIO_SOURCE_HOTWORD is for internal use only:
6003 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006004 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6005 auto result = usecase;
6006 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6007 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6008 }
6009 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006010 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006011 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006012 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006013 }
6014 }
6015 return status;
6016}
6017
Eric Laurent6a94d692014-05-20 11:18:06 -07006018status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6019 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006020{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006021 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006022 ssize_t index;
6023 if (patchHandle) {
6024 index = mAudioPatches.indexOfKey(*patchHandle);
6025 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006026 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006027 }
6028 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006029 return INVALID_OPERATION;
6030 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006031 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006032 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006033 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006034 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01006035 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006036 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006037 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006038 return status;
6039}
6040
François Gaffie11d30102018-11-02 16:09:09 +01006041sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006042 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006043 audio_format_t& format,
6044 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006045 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006046{
6047 // Choose an input profile based on the requested capture parameters: select the first available
6048 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006049 //
6050 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6051 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006052
Glenn Kasten730b9262018-03-29 15:01:26 -07006053 sp<IOProfile> firstInexact;
6054 uint32_t updatedSamplingRate = 0;
6055 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6056 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006057 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006058 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006059 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006060 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006061 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006062 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006063 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006064 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006065 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006066 &channelMask /*updatedChannelMask*/,
6067 // FIXME ugly cast
6068 (audio_output_flags_t) flags,
6069 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006070 return profile;
6071 }
François Gaffie11d30102018-11-02 16:09:09 +01006072 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006073 samplingRate,
6074 &updatedSamplingRate,
6075 format,
6076 &updatedFormat,
6077 channelMask,
6078 &updatedChannelMask,
6079 // FIXME ugly cast
6080 (audio_output_flags_t) flags,
6081 false /*exactMatchRequiredForInputFlags*/)) {
6082 firstInexact = profile;
6083 }
6084
Eric Laurente552edb2014-03-10 17:42:56 -07006085 }
6086 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006087 if (firstInexact != nullptr) {
6088 samplingRate = updatedSamplingRate;
6089 format = updatedFormat;
6090 channelMask = updatedChannelMask;
6091 return firstInexact;
6092 }
Eric Laurente552edb2014-03-10 17:42:56 -07006093 return NULL;
6094}
6095
François Gaffieaaac0fd2018-11-22 17:56:39 +01006096float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6097 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006098 int index,
jiabin12dc6b02019-10-01 09:38:30 -07006099 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006100{
jiabin12dc6b02019-10-01 09:38:30 -07006101 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006102
6103 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6104 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6105 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6106 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006107 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6108 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6109 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6110 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006111 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006112
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006113 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006114 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6115 mOutputs.isActive(ringVolumeSrc, 0)) {
6116 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin12dc6b02019-10-01 09:38:30 -07006117 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006118 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006119 }
6120
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006121 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006122 if ((volumeSource != callVolumeSrc && (isInCall() ||
6123 mOutputs.isActiveLocally(callVolumeSrc))) &&
6124 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6125 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6126 volumeSource == alarmVolumeSrc ||
6127 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6128 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6129 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006130 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006131 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin12dc6b02019-10-01 09:38:30 -07006132 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006133 const float maxVoiceVolDb =
jiabin12dc6b02019-10-01 09:38:30 -07006134 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006135 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006136 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6137 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6138 // programmatically muted.
6139 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6140 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6141 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07006142 bool exemptFromCapping =
6143 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6144 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006145 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6146 volumeSource, volumeDb);
6147 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006148 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6149 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6150 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006151 }
6152 }
Eric Laurente552edb2014-03-10 17:42:56 -07006153 // if a headset is connected, apply the following rules to ring tones and notifications
6154 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006155 // - always attenuate notifications volume by 6dB
6156 // - attenuate ring tones volume by 6dB unless music is not playing and
6157 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006158 // - if music is playing, always limit the volume to current music volume,
6159 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin12dc6b02019-10-01 09:38:30 -07006160 if (!Intersection(deviceTypes,
6161 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6162 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurent7a62f292020-08-07 10:51:53 -07006163 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6164 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006165 ((volumeSource == alarmVolumeSrc ||
6166 volumeSource == ringVolumeSrc) ||
6167 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6168 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6169 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6170 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6171 curves.canBeMuted()) {
6172
Eric Laurente552edb2014-03-10 17:42:56 -07006173 // when the phone is ringing we must consider that music could have been paused just before
6174 // by the music application and behave as if music was active if the last music track was
6175 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006176 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006177 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006178 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin12dc6b02019-10-01 09:38:30 -07006179 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006180 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6181 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006182 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin12dc6b02019-10-01 09:38:30 -07006183 float musicVolDb = computeVolume(musicCurves,
6184 musicVolumeSrc,
6185 musicCurves.getVolumeIndex(musicDevice),
6186 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006187 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6188 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6189 if (volumeDb > minVolDb) {
6190 volumeDb = minVolDb;
6191 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006192 }
jiabin12dc6b02019-10-01 09:38:30 -07006193 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6194 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006195 // on A2DP, also ensure notification volume is not too low compared to media when
6196 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006197 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006198 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin12dc6b02019-10-01 09:38:30 -07006199 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6200 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006201 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6202 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006203 }
6204 }
jiabin12dc6b02019-10-01 09:38:30 -07006205 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006206 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006207 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006208 }
6209 }
6210
François Gaffie43c73442018-11-08 08:21:55 +01006211 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006212}
6213
Eric Laurent3839bc02018-07-10 18:33:34 -07006214int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006215 VolumeSource fromVolumeSource,
6216 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006217{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006218 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006219 return srcIndex;
6220 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006221 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6222 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006223 float minSrc = (float)srcCurves.getVolumeIndexMin();
6224 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6225 float minDst = (float)dstCurves.getVolumeIndexMin();
6226 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006227
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006228 // preserve mute request or correct range
6229 if (srcIndex < minSrc) {
6230 if (srcIndex == 0) {
6231 return 0;
6232 }
6233 srcIndex = minSrc;
6234 } else if (srcIndex > maxSrc) {
6235 srcIndex = maxSrc;
6236 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006237 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6238}
6239
François Gaffieaaac0fd2018-11-22 17:56:39 +01006240status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6241 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006242 int index,
6243 const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006244 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006245 int delayMs,
6246 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006247{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006248 // do not change actual attributes volume if the attributes is muted
6249 if (outputDesc->isMuted(volumeSource)) {
6250 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6251 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006252 return NO_ERROR;
6253 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006254 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6255 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6256 bool isVoiceVolSrc = callVolSrc == volumeSource;
6257 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6258
Eric Laurentcca11ce2020-11-25 15:31:27 +01006259 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006260 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006261 // if sco and call follow same curves, bypass forceUseForComm
6262 if ((callVolSrc != btScoVolSrc) &&
Eric Laurentcca11ce2020-11-25 15:31:27 +01006263 ((isVoiceVolSrc && isScoRequested) ||
6264 (isBtScoVolSrc && !isScoRequested))) {
6265 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6266 volumeSource, isScoRequested ? " " : "n ot ");
6267 // Do not return an error here as AudioService will always set both voice call
6268 // and bluetooth SCO volumes due to stream aliasing.
6269 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006270 }
jiabin12dc6b02019-10-01 09:38:30 -07006271 if (deviceTypes.empty()) {
6272 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006273 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006274
jiabin12dc6b02019-10-01 09:38:30 -07006275 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6276 if (outputDesc->isFixedVolume(deviceTypes) ||
HW Leeda7581e2018-05-22 18:31:34 +08006277 // Force VoIP volume to max for bluetooth SCO
jiabin12dc6b02019-10-01 09:38:30 -07006278
6279 ((isVoiceVolSrc || isBtScoVolSrc) &&
6280 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006281 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006282 }
jiabin12dc6b02019-10-01 09:38:30 -07006283 outputDesc->setVolume(
6284 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006285
François Gaffieaaac0fd2018-11-22 17:56:39 +01006286 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006287 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006288 // 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 +01006289 if (isVoiceVolSrc) {
6290 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006291 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006292 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006293 }
Eric Laurent18fba842016-03-31 14:41:26 -07006294 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006295 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6296 mLastVoiceVolume = voiceVolume;
6297 }
6298 }
Eric Laurente552edb2014-03-10 17:42:56 -07006299 return NO_ERROR;
6300}
6301
Eric Laurentc75307b2015-03-17 15:29:32 -07006302void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006303 const DeviceTypeSet& deviceTypes,
6304 int delayMs,
6305 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006306{
Francois Gaffie5992b182020-03-20 14:55:14 +01006307 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006308 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6309 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6310 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin12dc6b02019-10-01 09:38:30 -07006311 curves.getVolumeIndex(deviceTypes),
6312 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006313 }
6314}
6315
François Gaffiec005e562018-11-06 15:04:49 +01006316void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6317 bool on,
6318 const sp<AudioOutputDescriptor>& outputDesc,
6319 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006320 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006321{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006322 std::vector<VolumeSource> sourcesToMute;
6323 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6324 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6325 toString(attributes).c_str(), on, outputDesc->getId());
6326 VolumeSource source = toVolumeSource(attributes);
6327 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6328 sourcesToMute.push_back(source);
6329 }
Eric Laurente552edb2014-03-10 17:42:56 -07006330 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006331 for (auto source : sourcesToMute) {
jiabin12dc6b02019-10-01 09:38:30 -07006332 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006333 }
6334
Eric Laurente552edb2014-03-10 17:42:56 -07006335}
6336
François Gaffieaaac0fd2018-11-22 17:56:39 +01006337void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6338 bool on,
6339 const sp<AudioOutputDescriptor>& outputDesc,
6340 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006341 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006342{
jiabin12dc6b02019-10-01 09:38:30 -07006343 if (deviceTypes.empty()) {
6344 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006345 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006346 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006347 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006348 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006349 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006350 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6351 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6352 AUDIO_POLICY_FORCE_NONE))) {
jiabin12dc6b02019-10-01 09:38:30 -07006353 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006354 }
6355 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006356 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6357 // ignored
6358 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006359 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006360 if (!outputDesc->isMuted(volumeSource)) {
6361 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006362 return;
6363 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006364 if (outputDesc->decMuteCount(volumeSource) == 0) {
6365 checkAndSetVolume(curves, volumeSource,
jiabin12dc6b02019-10-01 09:38:30 -07006366 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006367 outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006368 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006369 delayMs);
6370 }
6371 }
6372}
6373
François Gaffie53615e22015-03-19 09:24:12 +01006374bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6375{
François Gaffiec005e562018-11-06 15:04:49 +01006376 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006377 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6378 return true;
6379 }
6380
6381 // has known usage?
6382 switch (paa->usage) {
6383 case AUDIO_USAGE_UNKNOWN:
6384 case AUDIO_USAGE_MEDIA:
6385 case AUDIO_USAGE_VOICE_COMMUNICATION:
6386 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6387 case AUDIO_USAGE_ALARM:
6388 case AUDIO_USAGE_NOTIFICATION:
6389 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6390 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6391 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6392 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6393 case AUDIO_USAGE_NOTIFICATION_EVENT:
6394 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6395 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6396 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6397 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006398 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006399 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006400 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006401 case AUDIO_USAGE_EMERGENCY:
6402 case AUDIO_USAGE_SAFETY:
6403 case AUDIO_USAGE_VEHICLE_STATUS:
6404 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006405 break;
6406 default:
6407 return false;
6408 }
6409 return true;
6410}
6411
François Gaffie2110e042015-03-24 08:41:51 +01006412audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6413{
6414 return mEngine->getForceUse(usage);
6415}
6416
6417bool AudioPolicyManager::isInCall()
6418{
6419 return isStateInCall(mEngine->getPhoneState());
6420}
6421
6422bool AudioPolicyManager::isStateInCall(int state)
6423{
6424 return is_state_in_call(state);
6425}
6426
Eric Laurent74b71512019-11-06 17:21:57 -08006427bool AudioPolicyManager::isCallAudioAccessible()
6428{
6429 audio_mode_t mode = mEngine->getPhoneState();
6430 return (mode == AUDIO_MODE_IN_CALL)
6431 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6432 || (mode == AUDIO_MODE_CALL_SCREEN);
6433}
6434
Eric Laurentd60560a2015-04-10 11:31:20 -07006435void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6436{
6437 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006438 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6439 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6440 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6441 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006442 }
6443 }
6444
6445 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6446 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6447 bool release = false;
6448 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6449 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6450 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6451 source->ext.device.type == deviceDesc->type()) {
6452 release = true;
6453 }
6454 }
6455 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6456 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6457 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6458 sink->ext.device.type == deviceDesc->type()) {
6459 release = true;
6460 }
6461 }
6462 if (release) {
François Gaffiead447b72019-11-18 15:50:22 +01006463 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6464 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006465 }
6466 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006467
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006468 mInputs.clearSessionRoutesForDevice(deviceDesc);
6469
Francois Gaffie716e1432019-01-14 16:58:59 +01006470 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006471}
6472
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006473void AudioPolicyManager::modifySurroundFormats(
6474 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006475 std::unordered_set<audio_format_t> enforcedSurround(
6476 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006477 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6478 for (const auto& pair : mConfig.getSurroundFormats()) {
6479 allSurround.insert(pair.first);
6480 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6481 }
Phil Burk09bc4612016-02-24 15:58:15 -08006482
6483 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6484 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006485 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006486 // This is the resulting set of formats depending on the surround mode:
6487 // 'all surround' = allSurround
6488 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6489 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6490 // 'manual surround' = mManualSurroundFormats
6491 // AUTO: formats v 'enforced surround'
6492 // ALWAYS: formats v 'all surround' v 'enforced surround'
6493 // NEVER: formats ^ 'non-surround'
6494 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006495
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006496 std::unordered_set<audio_format_t> formatSet;
6497 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6498 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006499 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006500 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006501 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006502 formatSet.insert(*formatIter);
6503 }
6504 }
6505 } else {
6506 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6507 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006508 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006509
jiabin81772902018-04-02 17:52:27 -07006510 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006511 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006512 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6513 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6514 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006515 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006516 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6517 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6518 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006519 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006520 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006521 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006522 for (const auto& format : formatSet) {
jiabin4562b3b2019-07-29 10:13:34 -07006523 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006524 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006525}
6526
jiabin4562b3b2019-07-29 10:13:34 -07006527void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6528 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006529 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6530 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6531
6532 // If NEVER, then remove support for channelMasks > stereo.
6533 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin4562b3b2019-07-29 10:13:34 -07006534 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6535 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006536 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6537 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin4562b3b2019-07-29 10:13:34 -07006538 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006539 } else {
jiabin4562b3b2019-07-29 10:13:34 -07006540 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006541 }
6542 }
jiabin81772902018-04-02 17:52:27 -07006543 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6544 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6545 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006546 bool supports5dot1 = false;
6547 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006548 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006549 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6550 supports5dot1 = true;
6551 break;
6552 }
6553 }
6554 // If not then add 5.1 support.
6555 if (!supports5dot1) {
jiabin4562b3b2019-07-29 10:13:34 -07006556 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006557 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006558 }
Phil Burk09bc4612016-02-24 15:58:15 -08006559 }
6560}
6561
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006562void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006563 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006564 AudioProfileVector &profiles)
6565{
6566 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006567 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006568
François Gaffie112b0af2015-11-19 16:13:25 +01006569 // Format MUST be checked first to update the list of AudioProfile
6570 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006571 reply = mpClientInterface->getParameters(
6572 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006573 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006574 AudioParameter repliedParameters(reply);
6575 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006576 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006577 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6578 return;
6579 }
Phil Burk09bc4612016-02-24 15:58:15 -08006580 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006581 if (device == AUDIO_DEVICE_OUT_HDMI
6582 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006583 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006584 }
jiabinb9733bc2019-09-10 14:27:34 -07006585 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006586 }
François Gaffie112b0af2015-11-19 16:13:25 +01006587
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006588 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin4562b3b2019-07-29 10:13:34 -07006589 ChannelMaskSet channelMasks;
6590 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006591 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006592 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006593
6594 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006595 reply = mpClientInterface->getParameters(
6596 ioHandle,
6597 requestedParameters.toString() + ";" +
6598 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006599 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006600 AudioParameter repliedParameters(reply);
6601 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006602 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006603 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006604 }
6605 }
6606 if (profiles.hasDynamicChannelsFor(format)) {
6607 reply = mpClientInterface->getParameters(ioHandle,
6608 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006609 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006610 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006611 AudioParameter repliedParameters(reply);
6612 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006613 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006614 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006615 if (device == AUDIO_DEVICE_OUT_HDMI
6616 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006617 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006618 }
François Gaffie112b0af2015-11-19 16:13:25 +01006619 }
6620 }
jiabinb9733bc2019-09-10 14:27:34 -07006621 addDynamicAudioProfileAndSort(
6622 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006623 }
6624}
Eric Laurentd60560a2015-04-10 11:31:20 -07006625
Mikhail Naganovdc769682018-05-04 15:34:08 -07006626status_t AudioPolicyManager::installPatch(const char *caller,
6627 audio_patch_handle_t *patchHandle,
6628 AudioIODescriptorInterface *ioDescriptor,
6629 const struct audio_patch *patch,
6630 int delayMs)
6631{
6632 ssize_t index = mAudioPatches.indexOfKey(
6633 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6634 *patchHandle : ioDescriptor->getPatchHandle());
6635 sp<AudioPatch> patchDesc;
6636 status_t status = installPatch(
6637 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6638 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01006639 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006640 }
6641 return status;
6642}
6643
6644status_t AudioPolicyManager::installPatch(const char *caller,
6645 ssize_t index,
6646 audio_patch_handle_t *patchHandle,
6647 const struct audio_patch *patch,
6648 int delayMs,
6649 uid_t uid,
6650 sp<AudioPatch> *patchDescPtr)
6651{
6652 sp<AudioPatch> patchDesc;
6653 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6654 if (index >= 0) {
6655 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006656 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006657 }
6658
6659 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6660 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6661 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6662 if (status == NO_ERROR) {
6663 if (index < 0) {
6664 patchDesc = new AudioPatch(patch, uid);
François Gaffiead447b72019-11-18 15:50:22 +01006665 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006666 } else {
6667 patchDesc->mPatch = *patch;
6668 }
François Gaffiead447b72019-11-18 15:50:22 +01006669 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006670 if (patchHandle) {
François Gaffiead447b72019-11-18 15:50:22 +01006671 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006672 }
6673 nextAudioPortGeneration();
6674 mpClientInterface->onAudioPatchListUpdate();
6675 }
6676 if (patchDescPtr) *patchDescPtr = patchDesc;
6677 return status;
6678}
6679
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006680} // namespace android