blob: 13db5b38def1b72ea04f8bbcc3e78378f7e8f226 [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
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070050#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070052#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070053#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070054#include <utils/Log.h>
55
Eric Laurentd4692962014-05-05 18:13:44 -070056#include "AudioPolicyManager.h"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000057#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000069using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000070using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070071
Eric Laurentdc462862016-07-19 12:29:53 -070072//FIXME: workaround for truncated touch sounds
73// to be removed when the problem is handled by system UI
74#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070075
76// Largest difference in dB on earpiece in call between the voice volume and another
77// media / notification / system volume.
78constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
79
jiabin06e4bab2019-07-29 10:13:34 -070080template <typename T>
81bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
82{
83 if (left.size() != right.size()) {
84 return false;
85 }
86 for (size_t index = 0; index < right.size(); index++) {
87 if (left[index] != right[index]) {
88 return false;
89 }
90 }
91 return true;
92}
93
94template <typename T>
95bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
96{
97 return !(left == right);
98}
99
Eric Laurente552edb2014-03-10 17:42:56 -0700100// ----------------------------------------------------------------------------
101// AudioPolicyInterface implementation
102// ----------------------------------------------------------------------------
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
105 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
106 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800107 nextAudioPortGeneration();
108 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109}
110
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100111status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
112 audio_policy_dev_state_t state,
113 const char* device_address,
114 const char* device_name,
115 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800116 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100117 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
118 status == OK) {
119 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
120 } else {
121 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
122 return status;
123 }
124}
125
Ping Tsai2a5a5242024-08-16 13:39:10 +0800126status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000127 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200128{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 audio_port_v7 devicePort;
130 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800131 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
132 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
133 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
134
135 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800216 if (broadcastDeviceConnectionState(
217 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
218 mAvailableOutputDevices.remove(device);
219 mHwModules.cleanUpForDevice(device);
220 ALOGE("%s() device %s format %x connection failed", __func__,
221 device->toString().c_str(), device->getEncodedFormat());
222 return INVALID_OPERATION;
223 }
François Gaffie44481e72016-04-20 07:49:57 +0200224
François Gaffie11d30102018-11-02 16:09:09 +0100225 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
226 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200227
jiabinc0048632023-04-27 22:04:31 +0000228 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700229
230 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700231 return INVALID_OPERATION;
232 }
François Gaffie2110e042015-03-24 08:41:51 +0100233
jiabin1c4794b2020-05-05 10:08:05 -0700234 // Populate encapsulation information when a output device is connected.
235 device->setEncapsulationInfoFromHal(mpClientInterface);
236
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700237 // outputs should never be empty here
238 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
239 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100240 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800241
Eric Laurent3ae5f312015-02-03 17:12:08 -0800242 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700244 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100246 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700247 return INVALID_OPERATION;
248 }
249
François Gaffie11d30102018-11-02 16:09:09 +0100250 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700251
jiabinc0048632023-04-27 22:04:31 +0000252 // Notify the HAL to prepare to disconnect device
253 broadcastDeviceConnectionState(
254 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100257 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700258
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100259 mOutputs.clearSessionRoutesForDevice(device);
260
François Gaffie11d30102018-11-02 16:09:09 +0100261 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100262
jiabinc0048632023-04-27 22:04:31 +0000263 // Send Disconnect to HALs
264 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
265
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800266 // Reset active device codec
267 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
268
Kriti Dangef6be8f2020-11-05 11:58:19 +0100269 // remove device from mReportedFormatsMap cache
270 mReportedFormatsMap.erase(device);
271
jiabina84c3d32022-12-02 18:59:55 +0000272 // remove preferred mixer configurations
273 mPreferredMixerAttrInfos.erase(device->getId());
274
Eric Laurente552edb2014-03-10 17:42:56 -0700275 } break;
276
277 default:
François Gaffie11d30102018-11-02 16:09:09 +0100278 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700279 return BAD_VALUE;
280 }
281
Eric Laurent736a1022019-03-27 18:28:46 -0700282 // Propagate device availability to Engine
283 setEngineDeviceConnectionState(device, state);
284
Eric Laurentae970022019-01-29 14:25:04 -0800285 // No need to evaluate playback routing when connecting a remote submix
286 // output device used by a dynamic policy of type recorder as no
287 // playback use case is affected.
288 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700289 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800290 for (audio_io_handle_t output : outputs) {
291 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800292 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
293 if (policyMix != nullptr
294 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000295 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800296 doCheckForDeviceAndOutputChanges = false;
297 break;
298 }
299 }
300 }
301
302 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 // outputs must be closed after checkOutputForAllStrategies() is executed
304 if (!outputs.isEmpty()) {
305 for (audio_io_handle_t output : outputs) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100307 // close unused outputs after device disconnection or direct outputs that have
308 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200309 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200310 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
311 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200312 (desc->mDirectOpenCount == 0))
313 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
314 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200315 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700316 closeOutput(output);
317 }
Eric Laurente552edb2014-03-10 17:42:56 -0700318 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700319 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
320 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700321 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700322 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800323 };
324
325 if (doCheckForDeviceAndOutputChanges) {
326 checkForDeviceAndOutputChanges(checkCloseOutputs);
327 } else {
328 checkCloseOutputs();
329 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100330 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100331 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700332 const DeviceVector activeMediaDevices =
333 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000334 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700335 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700336 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530337 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
338 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100339 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 // do not force device change on duplicated output because if device is 0, it will
341 // also force a device 0 for the two outputs it is duplicated to which may override
342 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100343 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100344 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700345 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700346 // always force when disconnecting (a non-duplicated device)
347 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000348 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000349 // If the device is using preferred mixer attributes, the output need to reopen
350 // with default configuration when the new selected devices are different from
351 // current routing devices
352 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
353 continue;
354 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530355 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700356 }
jiabinbce0c1d2020-10-05 11:20:18 -0700357 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000358 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700359 desc->supportsDevicesForPlayback(activeMediaDevices)) {
360 // Reopen the output to query the dynamic profiles when there is not active
361 // clients or all active clients will be rerouted. Otherwise, set the flag
362 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
363 // can be reopened to query dynamic profiles when all clients are inactive.
364 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000365 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700366 } else {
367 desc->mPendingReopenToQueryProfiles = true;
368 }
369 }
370 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
371 // Clear the flag that previously set for re-querying profiles.
372 desc->mPendingReopenToQueryProfiles = false;
373 }
374 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000375 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700376
Eric Laurentd60560a2015-04-10 11:31:20 -0700377 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100378 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700379 }
380
Eric Laurent96d1dda2022-03-14 17:14:19 +0100381 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
382
Eric Laurent72aa32f2014-05-30 18:51:48 -0700383 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530384 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700385 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700386 } // end if is output device
387
Eric Laurente552edb2014-03-10 17:42:56 -0700388 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700389 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700391 switch (state)
392 {
393 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700394 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700395 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100396 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700397 return INVALID_OPERATION;
398 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700399
Jaideep Sharma33173202024-06-18 17:46:45 +0530400 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
401
Eric Laurent0dd51852019-04-19 18:18:58 -0700402 if (mAvailableInputDevices.add(device) < 0) {
403 return NO_MEMORY;
404 }
405
François Gaffie44481e72016-04-20 07:49:57 +0200406 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
407 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800408 if (broadcastDeviceConnectionState(
409 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
410 mAvailableInputDevices.remove(device);
411 mHwModules.cleanUpForDevice(device);
412 ALOGE("%s() device %s format %x connection failed", __func__,
413 device->toString().c_str(), device->getEncodedFormat());
414 return INVALID_OPERATION;
415 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700416 // Propagate device availability to Engine
417 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200418
Eric Laurent0dd51852019-04-19 18:18:58 -0700419 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700420 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
421
Eric Laurent0dd51852019-04-19 18:18:58 -0700422 mAvailableInputDevices.remove(device);
423
jiabinc0048632023-04-27 22:04:31 +0000424 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100425
426 mHwModules.cleanUpForDevice(device);
427
Eric Laurentd4692962014-05-05 18:13:44 -0700428 return INVALID_OPERATION;
429 }
430
Eric Laurentd4692962014-05-05 18:13:44 -0700431 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700432
433 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700434 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100436 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700437 return INVALID_OPERATION;
438 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700439
François Gaffie11d30102018-11-02 16:09:09 +0100440 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700441
jiabinc0048632023-04-27 22:04:31 +0000442 // Notify the HAL to prepare to disconnect device
443 broadcastDeviceConnectionState(
444 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700445
François Gaffie11d30102018-11-02 16:09:09 +0100446 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700447
448 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100449
jiabinc0048632023-04-27 22:04:31 +0000450 // Set Disconnect to HALs
451 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
452
Kriti Dangef6be8f2020-11-05 11:58:19 +0100453 // remove device from mReportedFormatsMap cache
454 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700455
456 // Propagate device availability to Engine
457 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700458 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700459
460 default:
François Gaffie11d30102018-11-02 16:09:09 +0100461 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700462 return BAD_VALUE;
463 }
464
Eric Laurent0dd51852019-04-19 18:18:58 -0700465 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700466 // As the input device list can impact the output device selection, update
467 // getDeviceForStrategy() cache
468 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700469
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100470 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200471 // Reconnect Audio Source
472 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
473 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
474 checkAudioSourceForAttributes(attributes);
475 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700476 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100477 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700478 }
479
Eric Laurentb52c1522014-05-20 11:27:36 -0700480 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530481 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700482 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700483 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700484
François Gaffie11d30102018-11-02 16:09:09 +0100485 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700486 return BAD_VALUE;
487}
488
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100489status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
490 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800491 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700492 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
493 devDescr->setName(device_name);
494 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100495}
496
Eric Laurent736a1022019-03-27 18:28:46 -0700497void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
498 audio_policy_dev_state_t state) {
499
500 // the Engine does not have to know about remote submix devices used by dynamic audio policies
501 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
502 return;
503 }
504 mEngine->setDeviceConnectionState(device, state);
505}
506
507
Eric Laurente0720872014-03-11 09:30:41 -0700508audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100509 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700510{
Eric Laurent634b7142016-04-20 13:48:02 -0700511 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
513 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700514 (strlen(device_address) != 0)/*matchAddress*/);
515
516 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100517 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700518 device, device_address);
519 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
520 }
François Gaffie53615e22015-03-19 09:24:12 +0100521
Eric Laurent3a4311c2014-03-17 12:00:47 -0700522 DeviceVector *deviceVector;
523
Eric Laurente552edb2014-03-10 17:42:56 -0700524 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700525 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700526 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700527 deviceVector = &mAvailableInputDevices;
528 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100529 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700530 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700531 }
Eric Laurent634b7142016-04-20 13:48:02 -0700532
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 return (deviceVector->getDevice(
534 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700535 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800536}
537
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
539 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 const char *device_name,
541 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800543 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
544 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800545
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800546 // connect/disconnect only 1 device at a time
547 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
548
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800549 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700550 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800552 // Nothing to do: device is not connected
553 return NO_ERROR;
554 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800555 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800556
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700557 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 // configure codecs.
559 // Handle two specific cases by sending a set parameter to
560 // configure A2DP codecs. No need to toggle device state.
561 // Case 1: A2DP active device switches from primary to primary
562 // module
563 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100564 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700565 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
567 if (availablePrimaryOutputDevices().contains(devDesc) &&
568 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100569 bool isA2dp = audio_is_a2dp_out_device(device);
570 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
571 : String8(AudioParameter::keyReconfigLeSupported);
572 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100574 int isReconfigSupported;
575 repliedParameters.getInt(supportKey, isReconfigSupported);
576 if (isReconfigSupported) {
577 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
578 : String8(AudioParameter::keyReconfigLe);
579 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800580 param.add(key, String8("true"));
581 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
582 devDesc->setEncodedFormat(encodedFormat);
583 return NO_ERROR;
584 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700585 }
586 }
cnx421bd2dcc42020-07-11 14:58:44 +0800587 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000588 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800589 for (size_t i = 0; i < mOutputs.size(); i++) {
590 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000591 // mute media strategies to avoid sending the music tail into
592 // the earpiece or headset.
593 if (desc->isStrategyActive(musicStrategy)) {
594 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
595 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
596 tempRecommendedMuteDuration : desc->latency() * 4;
597 if (muteWaitMs < tempMuteDurationMs) {
598 muteWaitMs = tempMuteDurationMs;
599 }
600 }
cnx421bd2dcc42020-07-11 14:58:44 +0800601 setStrategyMute(musicStrategy, true, desc);
602 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
603 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
604 nullptr, true /*fromCache*/).types());
605 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000606 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
607 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
608 // happens after the actual device switch.
609 if (muteWaitMs > 0) {
610 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
611 usleep(muteWaitMs * 1000);
612 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800613 // Toggle the device state: UNAVAILABLE -> AVAILABLE
614 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100615 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800616 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800617 device_address, device_name,
618 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800619 if (status != NO_ERROR) {
620 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
621 status);
622 return status;
623 }
624
625 status = setDeviceConnectionState(device,
626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800627 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800628 if (status != NO_ERROR) {
629 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
630 status);
631 return status;
632 }
633
634 return NO_ERROR;
635}
636
Pattydd807582021-11-04 21:01:03 +0800637status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
638 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800639{
Pattydd807582021-11-04 21:01:03 +0800640 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800641 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800642 std::unordered_set<audio_format_t> formatSet;
643 sp<HwModule> primaryModule =
644 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700645 if (primaryModule == nullptr) {
646 ALOGE("%s() unable to get primary module", __func__);
647 return NO_INIT;
648 }
Pattydd807582021-11-04 21:01:03 +0800649
650 DeviceTypeSet audioDeviceSet;
651
652 switch(device) {
653 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
654 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
655 break;
656 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800657 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
658 break;
659 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
660 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800661 break;
662 default:
663 ALOGE("%s() device type 0x%08x not supported", __func__, device);
664 return BAD_VALUE;
665 }
666
jiabin9a3361e2019-10-01 09:38:30 -0700667 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800668 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800669 for (const auto& device : declaredDevices) {
670 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800671 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800672 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800673 return status;
674}
675
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
677{
678 DeviceVector rxSinkdevices{};
679 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
680 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
681 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
682 auto rxSinkDevice = rxSinkdevices.itemAt(0);
683 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
684 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
685 // retrieve Rx Source device descriptor
686 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
687 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
688
689 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
690 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
691 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
692 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
693 return DeviceVector(rxSinkDevice);
694 }
695 }
696 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
697 // the device returned is not necessarily reachable via this output
698 // (filter later by setOutputDevices())
699 return getNewOutputDevices(mPrimaryOutput, fromCache);
700}
701
702status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
703{
François Gaffiedb1755b2023-09-01 11:50:35 +0200704 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100705 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
706 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
707 }
708 return INVALID_OPERATION;
709}
710
711status_t AudioPolicyManager::updateCallRoutingInternal(
712 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700713{
714 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100715 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700716 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200717 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700718 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100719 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700720 }
François Gaffie11d30102018-11-02 16:09:09 +0100721
Francois Gaffie716e1432019-01-14 16:58:59 +0100722 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100723 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200724
Eric Laurentb2fb4102024-06-21 12:25:26 +0000725 if (!fix_call_audio_patch()) {
726 disconnectTelephonyAudioSource(mCallRxSourceClient);
727 disconnectTelephonyAudioSource(mCallTxSourceClient);
728 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200729
730 if (rxDevices.isEmpty()) {
731 ALOGW("%s() no selected output device", __func__);
732 return INVALID_OPERATION;
733 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000734 if (txSourceDevice == nullptr) {
735 ALOGE("%s() selected input device not available", __func__);
736 return INVALID_OPERATION;
737 }
François Gaffiec005e562018-11-06 15:04:49 +0100738
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100739 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100740 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
François Gaffie9eb18552018-11-05 10:33:26 +0100742 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700743 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100744 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700745 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100746 // retrieve Rx Source and Tx Sink device descriptors
747 sp<DeviceDescriptor> rxSourceDevice =
748 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
749 String8(),
750 AUDIO_FORMAT_DEFAULT);
751 sp<DeviceDescriptor> txSinkDevice =
752 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
753 String8(),
754 AUDIO_FORMAT_DEFAULT);
755
756 // RX and TX Telephony device are declared by Primary Audio HAL
757 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
758 (telephonyRxModule->getHalVersionMajor() >= 3)) {
759 if (rxSourceDevice == 0 || txSinkDevice == 0) {
760 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100761 ALOGE("%s() no telephony Tx and/or RX device", __func__);
762 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100763 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100764 // createAudioPatchInternal now supports both HW / SW bridging
765 createRxPatch = true;
766 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100767 } else {
768 // If the RX device is on the primary HW module, then use legacy routing method for
769 // voice calls via setOutputDevice() on primary output.
770 // Otherwise, create two audio patches for TX and RX path.
771 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
772 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700773 // If the TX device is also on the primary HW module, setOutputDevice() will take care
774 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100775 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
776 (txSinkDevice != 0);
777 }
778 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
779 // Otherwise, create two audio patches for TX and RX path.
780 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000781 if (fix_call_audio_patch()) {
782 disconnectTelephonyAudioSource(mCallRxSourceClient);
783 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200784 if (!hasPrimaryOutput()) {
785 ALOGW("%s() no primary output available", __func__);
786 return INVALID_OPERATION;
787 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530788 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700789 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000790 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800791 // If the TX device is on the primary HW module but RX device is
792 // on other HW module, SinkMetaData of telephony input should handle it
793 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700794 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700795 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100796 // terminate active capture if on the same HW module as the call TX source device
797 // FIXME: would be better to refine to only inputs whose profile connects to the
798 // call TX device but this information is not in the audio patch and logic here must be
799 // symmetric to the one in startInput()
800 for (const auto& activeDesc : mInputs.getActiveInputs()) {
801 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
802 closeActiveClients(activeDesc);
803 }
804 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000806 } else if (fix_call_audio_patch()) {
807 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800808 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100809 if (waitMs != nullptr) {
810 *waitMs = muteWaitMs;
811 }
812 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800813}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700814
Mikhail Naganov100f0122018-11-29 11:22:16 -0800815bool AudioPolicyManager::isDeviceOfModule(
816 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
817 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
818 if (module != 0) {
819 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
820 .indexOf(devDesc) != NAME_NOT_FOUND
821 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
822 .indexOf(devDesc) != NAME_NOT_FOUND;
823 }
824 return false;
825}
826
David Lif85c5e32024-07-01 13:14:10 +0000827void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200828{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000829 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
830
831 if (fix_call_audio_patch()) {
832 if (mCallRxSourceClient != nullptr) {
833 DeviceVector rxDevices =
834 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
835 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
836 "connectTelephonyRxAudioSource(): no device found for call RX source");
837 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
838 if (mCallRxSourceClient->isConnected()
839 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
840 return;
841 }
842 disconnectTelephonyAudioSource(mCallRxSourceClient);
843 }
844 } else {
845 disconnectTelephonyAudioSource(mCallRxSourceClient);
846 }
847
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200848 const struct audio_port_config source = {
849 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
850 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
851 };
Eric Laurent541a2002024-01-15 18:11:42 +0100852 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000853
Eric Laurentccbd7872024-06-20 12:34:15 +0000854 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000855 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100856 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
857 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000858 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
859 mCallRxSourceClient->srcDevice()->toString().c_str(),
860 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200861 ALOGE_IF(mCallRxSourceClient == nullptr,
862 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200863}
864
Francois Gaffie601801d2021-06-22 13:27:39 +0200865void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200866{
Francois Gaffie601801d2021-06-22 13:27:39 +0200867 if (clientDesc == nullptr) {
868 return;
869 }
870 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
871 "%s error stopping audio source", __func__);
872 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200873}
874
875void AudioPolicyManager::connectTelephonyTxAudioSource(
876 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
877 uint32_t delayMs)
878{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200879 if (srcDevice == nullptr || sinkDevice == nullptr) {
880 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
881 return;
882 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000883
884 if (fix_call_audio_patch()) {
885 if (mCallTxSourceClient != nullptr) {
886 if (mCallTxSourceClient->isConnected()
887 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
888 return;
889 }
890 disconnectTelephonyAudioSource(mCallTxSourceClient);
891 }
892 } else {
893 disconnectTelephonyAudioSource(mCallTxSourceClient);
894 }
895
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200896 PatchBuilder patchBuilder;
897 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000898
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200900 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
901
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200902 struct audio_port_config source = {};
903 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100904 mCallTxSourceClient = new SourceClientDescriptor(
905 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000906 mCommunnicationStrategy, toVolumeSource(aa), true,
907 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100908 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
909
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200910 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
911 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200912 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
913 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200914 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000915 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
916 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200917 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200918 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200919 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200920}
921
Eric Laurente0720872014-03-11 09:30:41 -0700922void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700923{
924 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100925 // store previous phone state for management of sonification strategy below
926 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100927 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100928
929 if (mEngine->setPhoneState(state) != NO_ERROR) {
930 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700931 return;
932 }
François Gaffie2110e042015-03-24 08:41:51 +0100933 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700934 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700935 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700936 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800937 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700938 }
939
François Gaffie2110e042015-03-24 08:41:51 +0100940 /**
941 * Switching to or from incall state or switching between telephony and VoIP lead to force
942 * routing command.
943 */
Eric Laurent74b71512019-11-06 17:21:57 -0800944 bool force = ((isStateInCall(oldState) != isStateInCall(state))
945 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700946
947 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700948 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700949
Eric Laurente552edb2014-03-10 17:42:56 -0700950 int delayMs = 0;
951 if (isStateInCall(state)) {
952 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100953 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
954 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700955 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700957 // mute media and sonification strategies and delay device switch by the largest
958 // latency of any output where either strategy is active.
959 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100960 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
961 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
962 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700963 (delayMs < (int)desc->latency()*2)) {
964 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700965 }
François Gaffiec005e562018-11-06 15:04:49 +0100966 setStrategyMute(musicStrategy, true, desc);
967 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
968 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
969 nullptr, true /*fromCache*/).types());
970 setStrategyMute(sonificationStrategy, true, desc);
971 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
972 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
973 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
975 }
976
François Gaffiedb1755b2023-09-01 11:50:35 +0200977 if (state == AUDIO_MODE_IN_CALL) {
978 (void)updateCallRouting(false /*fromCache*/, delayMs);
979 } else {
980 if (oldState == AUDIO_MODE_IN_CALL) {
981 disconnectTelephonyAudioSource(mCallRxSourceClient);
982 disconnectTelephonyAudioSource(mCallTxSourceClient);
983 }
984 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100985 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
986 // force routing command to audio hardware when ending call
987 // even if no device change is needed
988 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
989 rxDevices = mPrimaryOutput->devices();
990 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530991 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700992 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700993 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700994
jiabin3ff8d7d2022-12-13 06:27:44 +0000995 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700996 // reevaluate routing on all outputs in case tracks have been started during the call
997 for (size_t i = 0; i < mOutputs.size(); i++) {
998 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100999 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001000 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1001 && desc->mPreferredAttrInfo != nullptr) {
1002 // If the output is using preferred mixer attributes and the audio mode is not normal,
1003 // the output need to reopen with default configuration.
1004 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1005 continue;
1006 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001007 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1008 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301009 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001010 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001011 }
1012 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001013 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001014
Eric Laurent96d1dda2022-03-14 17:14:19 +01001015 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1016
Eric Laurente552edb2014-03-10 17:42:56 -07001017 if (isStateInCall(state)) {
1018 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001019 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001020 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001021 }
1022
1023 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001024 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1025 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001026}
1027
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001028audio_mode_t AudioPolicyManager::getPhoneState() {
1029 return mEngine->getPhoneState();
1030}
1031
Eric Laurente0720872014-03-11 09:30:41 -07001032void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001033 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001034{
François Gaffie2110e042015-03-24 08:41:51 +01001035 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001036 if (config == mEngine->getForceUse(usage)) {
1037 return;
1038 }
Eric Laurente552edb2014-03-10 17:42:56 -07001039
François Gaffie2110e042015-03-24 08:41:51 +01001040 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1041 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1042 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001043 }
François Gaffie2110e042015-03-24 08:41:51 +01001044 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1045 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1046 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001047
1048 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001049 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001050
Eric Laurent22fcda22019-05-17 16:28:47 -07001051 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1052 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001053 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001054 }
1055
Eric Laurentdc462862016-07-19 12:29:53 -07001056 //FIXME: workaround for truncated touch sounds
1057 // to be removed when the problem is handled by system UI
1058 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001059 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1060 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1061 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001062
1063 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001064 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001065}
1066
Eric Laurente0720872014-03-11 09:30:41 -07001067void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001068{
1069 ALOGV("setSystemProperty() property %s, value %s", property, value);
1070}
1071
Dorin Drimusecc9f422022-03-09 17:57:40 +01001072// Find an MSD output profile compatible with the parameters passed.
1073// When "directOnly" is set, restrict search to profiles for direct outputs.
1074sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1075 const DeviceVector& devices,
1076 uint32_t samplingRate,
1077 audio_format_t format,
1078 audio_channel_mask_t channelMask,
1079 audio_output_flags_t flags,
1080 bool directOnly)
1081{
1082 flags = getRelevantFlags(flags, directOnly);
1083
1084 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1085 if (msdModule != nullptr) {
1086 // for the msd module check if there are patches to the output devices
1087 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1088 HwModuleCollection modules;
1089 modules.add(msdModule);
1090 return searchCompatibleProfileHwModules(
1091 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1092 flags, directOnly);
1093 }
1094 }
1095 return nullptr;
1096}
1097
Michael Chana94fbb22018-04-24 14:31:19 +10001098// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1099// search to profiles for direct outputs.
1100sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001101 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001102 uint32_t samplingRate,
1103 audio_format_t format,
1104 audio_channel_mask_t channelMask,
1105 audio_output_flags_t flags,
1106 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001107{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 flags = getRelevantFlags(flags, directOnly);
1109
1110 return searchCompatibleProfileHwModules(
1111 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1112}
1113
1114audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1115 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001116 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001117 // only retain flags that will drive the direct output profile selection
1118 // if explicitly requested
1119 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001120 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001121 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1122 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001123 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001124 return flags;
1125}
Eric Laurent861a6282015-05-18 15:40:16 -07001126
Dorin Drimusecc9f422022-03-09 17:57:40 +01001127sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1128 const HwModuleCollection& hwModules,
1129 const DeviceVector& devices,
1130 uint32_t samplingRate,
1131 audio_format_t format,
1132 audio_channel_mask_t channelMask,
1133 audio_output_flags_t flags,
1134 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001135 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001136 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001137 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001138 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001139 samplingRate, NULL /*updatedSamplingRate*/,
1140 format, NULL /*updatedFormat*/,
1141 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001142 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001143 continue;
1144 }
1145 // reject profiles not corresponding to a device currently available
1146 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1147 continue;
1148 }
1149 // reject profiles if connected device does not support codec
1150 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1151 continue;
1152 }
1153 if (!directOnly) {
1154 return curProfile;
1155 }
1156
1157 // when searching for direct outputs, if several profiles are compatible, give priority
1158 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001159 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001160 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001161 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001162 }
1163 profile = curProfile;
1164 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1165 break;
1166 }
Eric Laurente552edb2014-03-10 17:42:56 -07001167 }
1168 }
Eric Laurent861a6282015-05-18 15:40:16 -07001169 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001170}
1171
Eric Laurentfa0f6742021-08-17 18:39:44 +02001172sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001173 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001174{
1175 for (const auto& hwModule : mHwModules) {
1176 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001177 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001178 continue;
1179 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001180 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001181 // reject profiles not corresponding to a device currently available
1182 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1183 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1184 continue;
1185 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001186 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1187 != devices.size()) {
1188 continue;
1189 }
1190 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001191 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1192 return curProfile;
1193 }
1194 }
1195 return nullptr;
1196}
1197
Eric Laurentf4e63452017-11-06 19:31:46 +00001198audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001199{
François Gaffiec005e562018-11-06 15:04:49 +01001200 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001201
1202 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1203 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1204 // format, flags, etc. This may result in some discrepancy for functions that utilize
1205 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1206 // and AudioSystem::getOutputSamplingRate().
1207
François Gaffie11d30102018-11-02 16:09:09 +01001208 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001209 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001210 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001211 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1212 }
1213 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001214
François Gaffie11d30102018-11-02 16:09:09 +01001215 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1216 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001217 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001218}
1219
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001220status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1221 const audio_attributes_t *srcAttr,
1222 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001223{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001224 if (srcAttr != NULL) {
1225 if (!isValidAttributes(srcAttr)) {
1226 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1227 __func__,
1228 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1229 srcAttr->tags);
1230 return BAD_VALUE;
1231 }
1232 *dstAttr = *srcAttr;
1233 } else {
1234 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1235 ALOGE("%s: invalid stream type", __func__);
1236 return BAD_VALUE;
1237 }
François Gaffiec005e562018-11-06 15:04:49 +01001238 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001239 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001240
1241 // Only honor audibility enforced when required. The client will be
1242 // forced to reconnect if the forced usage changes.
1243 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001244 dstAttr->flags = static_cast<audio_flags_mask_t>(
1245 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001246 }
1247
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001248 return NO_ERROR;
1249}
1250
Kevin Rocard153f92d2018-12-18 18:33:28 -08001251status_t AudioPolicyManager::getOutputForAttrInt(
1252 audio_attributes_t *resultAttr,
1253 audio_io_handle_t *output,
1254 audio_session_t session,
1255 const audio_attributes_t *attr,
1256 audio_stream_type_t *stream,
1257 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001258 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001259 audio_output_flags_t *flags,
1260 audio_port_handle_t *selectedDeviceId,
1261 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001262 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001263 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001264 bool *isSpatialized,
1265 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001266{
François Gaffiec005e562018-11-06 15:04:49 +01001267 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001268 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001269 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001270 const sp<DeviceDescriptor> requestedDevice =
1271 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1272
Eric Laurent8a1095a2019-11-08 14:44:16 -08001273 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001274 *isSpatialized = false;
1275
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001276 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1277 if (status != NO_ERROR) {
1278 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001279 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001280 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001281 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001282 }
François Gaffiec005e562018-11-06 15:04:49 +01001283 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001284
François Gaffiec005e562018-11-06 15:04:49 +01001285 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1286 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287
Oscar Azucena873d10f2023-01-12 18:34:42 -08001288 bool usePrimaryOutputFromPolicyMixes = false;
1289
Kevin Rocard153f92d2018-12-18 18:33:28 -08001290 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1291 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1292 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001293 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001294 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1295 .channel_mask = config->channel_mask,
1296 .format = config->format,
1297 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001298 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001299 mAvailableOutputDevices, requestedDevice, primaryMix,
1300 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001301 if (status != OK) {
1302 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001303 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001304
Kevin Rocard153f92d2018-12-18 18:33:28 -08001305 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001306 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001307 && (!audio_is_linear_pcm(config->format) ||
1308 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001309 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001310 return BAD_VALUE;
1311 }
1312 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001313 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001314 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1315 primaryMix->mDeviceAddress,
1316 AUDIO_FORMAT_DEFAULT);
1317 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001318 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001319 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1320 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001321 // if a direct output can be opened to deliver the track's multi-channel content to the
1322 // output rather than being downmixed by the primary output, then use this direct
1323 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1324 // mix.
1325 bool tryDirectForChannelMask = policyDesc != nullptr
1326 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1327 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001328 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001329 audio_io_handle_t newOutput;
1330 status = openDirectOutput(
1331 *stream, session, config,
1332 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001333 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001334 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001335 policyDesc = mOutputs.valueFor(newOutput);
1336 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001337 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001338 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001339 policyDesc = nullptr;
1340 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001341 }
1342 if (policyDesc != nullptr) {
1343 policyDesc->mPolicyMix = primaryMix;
1344 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001345 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1346 : AUDIO_PORT_HANDLE_NONE;
1347 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1348 // Remove direct flag as it is not on a direct output.
1349 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1350 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001351
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001352 ALOGV("getOutputForAttr() returns output %d", *output);
1353 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1354 *outputType = API_OUT_MIX_PLAYBACK;
1355 } else {
1356 *outputType = API_OUTPUT_LEGACY;
1357 }
1358 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001359 } else {
1360 if (policyMixDevice != nullptr) {
1361 ALOGE("%s, try to use primary mix but no output found", __func__);
1362 return INVALID_OPERATION;
1363 }
1364 // Fallback to default engine selection as the selected primary mix device is not
1365 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001366 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001367 }
François Gaffiec005e562018-11-06 15:04:49 +01001368 // Virtual sources must always be dynamicaly or explicitly routed
1369 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1370 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1371 return BAD_VALUE;
1372 }
1373 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1374 // in order to let the choice of the order to future vendor engine
1375 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001376
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001377 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001378 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001379 }
1380
Nadav Barb2f18162018-07-18 13:01:53 +03001381 // Set incall music only if device was explicitly set, and fallback to the device which is
1382 // chosen by the engine if not.
1383 // FIXME: provide a more generic approach which is not device specific and move this back
1384 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001385 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001386 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001387 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001388 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001389 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001390 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001391 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001392 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001393 }
1394 }
1395
François Gaffiec005e562018-11-06 15:04:49 +01001396 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1397 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1398 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001399
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001400 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001401 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001402 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001403 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001404 ALOGV("%s() Using MSD devices %s instead of devices %s",
1405 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001406 } else {
1407 *output = AUDIO_IO_HANDLE_NONE;
1408 }
1409 }
1410 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001411 sp<PreferredMixerAttributesInfo> info = nullptr;
1412 if (outputDevices.size() == 1) {
1413 info = getPreferredMixerAttributesInfo(
1414 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001415 mEngine->getProductStrategyForAttributes(*resultAttr),
1416 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001417 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1418 // and it is currently active.
1419 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001420 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001421 info = nullptr;
1422 }
jiabin8a096672024-09-18 18:20:24 +00001423
1424 if (info != nullptr && info->isBitPerfect() &&
1425 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1426 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1427 // Reject direct request if a preferred mixer config in use is bit-perfect.
1428 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1429 __func__);
1430 return BAD_VALUE;
1431 }
1432
jiabin220eea12024-05-17 17:55:20 +00001433 if (com::android::media::audioserver::
1434 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1435 if (info != nullptr && info->getUid() == uid &&
1436 info->configMatches(*config) &&
1437 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1438 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1439 [this, &outputDevices](audio_usage_t usage) {
1440 return mOutputs.isUsageActiveOnDevice(
1441 usage, outputDevices[0]); }))) {
1442 // Bit-perfect request is not allowed when the phone mode is not normal or
1443 // there is any higher priority user case active.
1444 return INVALID_OPERATION;
1445 }
1446 }
jiabina84c3d32022-12-02 18:59:55 +00001447 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001448 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001449 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001450 // The client will be active if the client is currently preferred mixer owner and the
1451 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001452 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001453 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001454 && info->getUid() == uid
1455 && *output != AUDIO_IO_HANDLE_NONE
1456 // When bit-perfect output is selected for the preferred mixer attributes owner,
1457 // only need to consider the config matches.
1458 && mOutputs.valueFor(*output)->isConfigurationMatched(
1459 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001460
1461 if (*isBitPerfect) {
1462 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1463 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001465 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001466 AudioProfileVector profiles;
1467 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1468 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001469 const auto channels = profiles[0]->getChannels();
1470 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1471 config->channel_mask = *channels.begin();
1472 }
1473 const auto sampleRates = profiles[0]->getSampleRates();
1474 if (!sampleRates.empty() &&
1475 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1476 config->sample_rate = *sampleRates.begin();
1477 }
jiabinf1c73972022-04-14 16:28:52 -07001478 config->format = profiles[0]->getFormat();
1479 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001480 return INVALID_OPERATION;
1481 }
Paul McLeanaa981192015-03-21 09:55:15 -07001482
François Gaffiec005e562018-11-06 15:04:49 +01001483 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001484 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001485 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001486 *selectedDeviceId = outputDevice->getId();
1487 break;
1488 }
1489 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001490
Eric Laurent8a1095a2019-11-08 14:44:16 -08001491 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1492 *outputType = API_OUTPUT_TELEPHONY_TX;
1493 } else {
1494 *outputType = API_OUTPUT_LEGACY;
1495 }
1496
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001497 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1498
1499 return NO_ERROR;
1500}
1501
1502status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1503 audio_io_handle_t *output,
1504 audio_session_t session,
1505 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001506 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001507 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001508 audio_output_flags_t *flags,
1509 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001510 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001511 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001512 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001513 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001514 bool *isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -07001515 float *volume,
1516 bool *muted)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001517{
1518 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1519 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1520 return INVALID_OPERATION;
1521 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001522 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001523 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001524 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001525 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001526 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001527 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001528 const sp<DeviceDescriptor> requestedDevice =
1529 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1530
1531 // Prevent from storing invalid requested device id in clients
1532 const audio_port_handle_t sanitizedRequestedPortId =
1533 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1534 *selectedDeviceId = sanitizedRequestedPortId;
1535
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001536 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001537 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001538 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1539 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001540 if (status != NO_ERROR) {
1541 return status;
1542 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001543 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001544 if (secondaryOutputs != nullptr) {
1545 for (auto &secondaryMix : secondaryMixes) {
1546 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1547 if (outputDesc != nullptr &&
1548 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1549 secondaryOutputs->push_back(outputDesc->mIoHandle);
1550 weakSecondaryOutputDescs.push_back(outputDesc);
1551 }
1552 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001553 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001554
Eric Laurent8fc147b2018-07-22 19:13:55 -07001555 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001556 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001557 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001558 };
jiabin4ef93452019-09-10 14:29:54 -07001559 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001560
Eric Laurentc209fe42020-06-05 18:11:23 -07001561 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001562 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001563 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001564 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001565 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001566 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001567 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001568 std::move(weakSecondaryOutputDescs),
1569 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001570 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001571
Andy Hung6b137d12024-08-27 22:35:17 +00001572 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001573 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001574
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001575 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1576 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001577
Eric Laurente83b55d2014-11-14 10:06:21 -08001578 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001579}
1580
Eric Laurentc529cf62020-04-17 18:19:10 -07001581status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1582 audio_session_t session,
1583 const audio_config_t *config,
1584 audio_output_flags_t flags,
1585 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001586 audio_io_handle_t *output,
1587 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001588
1589 *output = AUDIO_IO_HANDLE_NONE;
1590
1591 // skip direct output selection if the request can obviously be attached to a mixed output
1592 // and not explicitly requested
1593 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1594 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1595 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1596 return NAME_NOT_FOUND;
1597 }
1598
Mikhail Naganov806170e2024-09-05 17:26:50 -07001599 // Reject flag combinations that do not make sense. Note that the requested flags might not
1600 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1601 // combine the requested flags with its own flags, yielding an unsupported combination.
1602 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1603 return NAME_NOT_FOUND;
1604 }
1605
Eric Laurentc529cf62020-04-17 18:19:10 -07001606 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1607 // This prevents creating an offloaded track and tearing it down immediately after start
1608 // when audioflinger detects there is an active non offloadable effect.
1609 // FIXME: We should check the audio session here but we do not have it in this context.
1610 // This may prevent offloading in rare situations where effects are left active by apps
1611 // in the background.
1612 sp<IOProfile> profile;
1613 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1614 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1615 profile = getProfileForOutput(
1616 devices, config->sample_rate, config->format, config->channel_mask,
1617 flags, true /* directOnly */);
1618 }
1619
1620 if (profile == nullptr) {
1621 return NAME_NOT_FOUND;
1622 }
1623
1624 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1625 for (size_t i = 0; i < mOutputs.size(); i++) {
1626 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1627 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1628 // reuse direct output if currently open by the same client
1629 // and configured with same parameters
1630 if ((config->sample_rate == desc->getSamplingRate()) &&
1631 (config->format == desc->getFormat()) &&
1632 (config->channel_mask == desc->getChannelMask()) &&
1633 (session == desc->mDirectClientSession)) {
1634 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301635 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001636 mOutputs.keyAt(i), session);
1637 *output = mOutputs.keyAt(i);
1638 return NO_ERROR;
1639 }
1640 }
1641 }
1642
1643 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001644 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301645 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1646 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001647 return NAME_NOT_FOUND;
1648 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1649 // MMAP gracefully handles lack of an exclusive track resource by mixing
1650 // above the audio framework. For AAudio to know that the limit is reached,
1651 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301652 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1653 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001654 return NAME_NOT_FOUND;
1655 } else {
1656 // Close outputs on this profile, if available, to free resources for this request
1657 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1658 const auto desc = mOutputs.valueAt(i);
1659 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301660 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1661 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001662 closeOutput(desc->mIoHandle);
1663 }
1664 }
1665 }
1666 }
1667
1668 // Unable to close streams to find free resources for this request
1669 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301670 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1671 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001672 return NAME_NOT_FOUND;
1673 }
1674
Atneya Nairb16666a2023-12-11 20:18:33 -08001675 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001676
Michael Chan6fb34492020-12-08 15:44:49 +11001677 // An MSD patch may be using the only output stream that can service this request. Release
1678 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001679 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001680
Eric Laurentf1f22e72021-07-13 14:04:14 +02001681 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001682 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001683 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001684
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001685 // only accept an output with the requested parameters, unless the format can be IEC61937
1686 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1687 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1688 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1689 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001690 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001691 (!ignoreRequestedParametersCheck &&
1692 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1693 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1694 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001695 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1696 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1697 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1698 config->channel_mask, outputDesc->getChannelMask());
1699 if (*output != AUDIO_IO_HANDLE_NONE) {
1700 outputDesc->close();
1701 }
1702 // fall back to mixer output if possible when the direct output could not be open
1703 if (audio_is_linear_pcm(config->format) &&
1704 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1705 return NAME_NOT_FOUND;
1706 }
1707 *output = AUDIO_IO_HANDLE_NONE;
1708 return BAD_VALUE;
1709 }
1710 outputDesc->mDirectOpenCount = 1;
1711 outputDesc->mDirectClientSession = session;
1712
1713 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001714 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1715 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1716 hwModule->getHalVersionMajor() >= 3) {
1717 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1718 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001719 mPreviousOutputs = mOutputs;
1720 ALOGV("%s returns new direct output %d", __func__, *output);
1721 mpClientInterface->onAudioPortListUpdate();
1722 return NO_ERROR;
1723}
1724
François Gaffie11d30102018-11-02 16:09:09 +01001725audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1726 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001727 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001728 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001729 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001730 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001731 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001732 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001733 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001734{
Andy Hungc88b0642018-04-27 15:42:35 -07001735 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001736
jiabine375d412019-02-26 12:54:53 -08001737 // Discard haptic channel mask when forcing muting haptic channels.
1738 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001739 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1740 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001741
Eric Laurente552edb2014-03-10 17:42:56 -07001742 // open a direct output if required by specified parameters
1743 //force direct flag if offload flag is set: offloading implies a direct output stream
1744 // and all common behaviors are driven by checking only the direct flag
1745 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001746 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1747 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001748 }
Nadav Bar766fb022018-01-07 12:18:03 +02001749 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1750 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001751 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001752
1753 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1754
Eric Laurente83b55d2014-11-14 10:06:21 -08001755 // only allow deep buffering for music stream type
1756 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001757 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001758 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001759 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001760 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001761 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001762 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001763 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001764 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001765 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001766 audio_is_linear_pcm(config->format) &&
1767 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001768 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001769 AUDIO_OUTPUT_FLAG_DIRECT);
1770 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001771 }
Eric Laurente552edb2014-03-10 17:42:56 -07001772
Carter Hsua3abb402021-10-26 11:11:20 +08001773 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1774 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1775 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1776 }
1777
Eric Laurentf9230d52024-01-26 18:49:09 +01001778 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001779 // was specified and offload or direct playback is not explicitly requested, and there is no
1780 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001781 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001782 if (mSpatializerOutput != nullptr &&
1783 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1784 prefMixerConfigInfo == nullptr &&
1785 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1786 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001787 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001788 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001789 }
1790
Eric Laurentc529cf62020-04-17 18:19:10 -07001791 audio_config_t directConfig = *config;
1792 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001793
1794 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1795 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001796 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001797 return output;
1798 }
1799
Eric Laurent14cbfca2016-03-17 09:42:16 -07001800 // A request for HW A/V sync cannot fallback to a mixed output because time
1801 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001802 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001803 return AUDIO_IO_HANDLE_NONE;
1804 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001805 // A request for Tuner cannot fallback to a mixed output
1806 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1807 return AUDIO_IO_HANDLE_NONE;
1808 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001809
Eric Laurente552edb2014-03-10 17:42:56 -07001810 // ignoring channel mask due to downmix capability in mixer
1811
1812 // open a non direct output
1813
1814 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001815 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001816 // get which output is suitable for the specified stream. The actual
1817 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001818 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001819 if (prefMixerConfigInfo != nullptr) {
1820 for (audio_io_handle_t outputHandle : outputs) {
1821 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1822 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1823 output = outputHandle;
1824 break;
1825 }
1826 }
1827 if (output == AUDIO_IO_HANDLE_NONE) {
1828 // No output open with the preferred profile. Open a new one.
1829 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1830 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1831 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1832 config.format = prefMixerConfigInfo->getConfigBase().format;
1833 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1834 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1835 &config, prefMixerConfigInfo->getFlags());
1836 if (preferredOutput == nullptr) {
1837 ALOGE("%s failed to open output with preferred mixer config", __func__);
1838 } else {
1839 output = preferredOutput->mIoHandle;
1840 }
1841 }
1842 } else {
1843 // at this stage we should ignore the DIRECT flag as no direct output could be
1844 // found earlier
1845 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001846 if (com::android::media::audioserver::
1847 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1848 // If the preferred mixer attributes is null, do not select the bit-perfect output
1849 // unless the bit-perfect output is the only output.
1850 // The bit-perfect output can exist while the passed in preferred mixer attributes
1851 // info is null when it is a high priority client. The high priority clients are
1852 // ringtone or alarm, which is not a bit-perfect use case.
1853 size_t i = 0;
1854 while (i < outputs.size() && outputs.size() > 1) {
1855 auto desc = mOutputs.valueFor(outputs[i]);
1856 // The output descriptor must not be null here.
1857 if (desc->isBitPerfect()) {
1858 outputs.removeItemsAt(i);
1859 } else {
1860 i += 1;
1861 }
1862 }
1863 }
jiabina84c3d32022-12-02 18:59:55 +00001864 output = selectOutput(
1865 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1866 }
Eric Laurente552edb2014-03-10 17:42:56 -07001867 }
François Gaffie11d30102018-11-02 16:09:09 +01001868 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001869 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001870 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001871
Eric Laurente552edb2014-03-10 17:42:56 -07001872 return output;
1873}
1874
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001875sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001876 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1877 mAvailableInputDevices);
1878 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1879}
1880
1881DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1882 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1883 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884}
1885
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001888 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1889 if (msdModule != 0) {
1890 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1891 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1892 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1893 const struct audio_port_config *source = &patch->mPatch.sources[j];
1894 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1895 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001896 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001897 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898 }
1899 }
1900 }
1901 return msdPatches;
1902}
1903
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001904bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1905 ssize_t index = mAudioPatches.indexOfKey(handle);
1906 if (index < 0) {
1907 return false;
1908 }
1909 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1910 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1911 if (msdModule == nullptr) {
1912 return false;
1913 }
1914 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1915 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1916 return true;
1917 }
1918 index = getMsdOutputPatches().indexOfKey(handle);
1919 if (index < 0) {
1920 return false;
1921 }
1922 return true;
1923}
1924
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001925status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1926 const InputProfileCollection &inputProfiles,
1927 const OutputProfileCollection &outputProfiles,
1928 const sp<DeviceDescriptor> &sourceDevice,
1929 const sp<DeviceDescriptor> &sinkDevice,
1930 AudioProfileVector& sourceProfiles,
1931 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001933 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 return NO_INIT;
1935 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001936 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001937 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001938 return NO_INIT;
1939 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001940 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001941 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1942 inProfile->supportsDevice(sourceDevice)) {
1943 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001944 }
1945 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001947 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001948 outProfile->supportsDevice(sinkDevice)) {
1949 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001950 }
1951 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001952 return NO_ERROR;
1953}
1954
1955status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1956 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1957 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1958{
Dean Wheatley16809da2022-12-09 14:55:46 +11001959 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1960 static const std::vector<audio_format_t> formatsOrder = {{
1961 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001962 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1963 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001964 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1965 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1966 // preferred).
1967 std::vector<audio_channel_mask_t> masks = {{
1968 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1969 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1970 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1971 // insert index masks (higher counts most preferred) as preferred over position masks
1972 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1973 masks.insert(
1974 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1975 }
1976 return masks;
1977 }();
1978
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001979 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001980 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1981 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001982 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001983 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1984 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001985 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001986 }
1987 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1988 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1989 sinkConfig->format = bestSinkConfig.format;
1990 // For encoded streams force direct flag to prevent downstream mixing.
1991 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1992 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001993 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1994 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001995 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001996 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1997 // raw and IEC61937 framed streams.
1998 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1999 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2000 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002001 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2002 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002003 sourceConfig->channel_mask =
2004 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2005 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2006 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002007 sourceConfig->format = bestSinkConfig.format;
2008 // Copy input stream directly without any processing (e.g. resampling).
2009 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2010 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2011 if (hwAvSync) {
2012 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2013 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2014 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2015 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2016 }
2017 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2018 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2019 sinkConfig->config_mask |= config_mask;
2020 sourceConfig->config_mask |= config_mask;
2021 return NO_ERROR;
2022}
2023
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002024PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2025 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002026{
2027 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002028 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2029 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2030 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2031 if (deviceModule == nullptr) {
2032 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2033 return patchBuilder;
2034 }
2035 const InputProfileCollection inputProfiles = msdIsSource ?
2036 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2037 const OutputProfileCollection outputProfiles = msdIsSource ?
2038 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2039
2040 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2041 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2042 device : getMsdAudioOutDevices().itemAt(0);
2043 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2044
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002045 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2046 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002047 AudioProfileVector sourceProfiles;
2048 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002049 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2050 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002051 for (auto hwAvSync : { true, false }) {
2052 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2053 sourceProfiles, sinkProfiles) != NO_ERROR) {
2054 continue;
2055 }
2056 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2057 &sinkConfig) == NO_ERROR) {
2058 // Found a matching config. Re-create PatchBuilder with this config.
2059 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2060 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002061 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002062 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002063 " supporting PCM format conversion.", __func__);
2064 return patchBuilder;
2065}
2066
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002067status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002068 DeviceVector devices;
2069 if (outputDevices != nullptr && outputDevices->size() > 0) {
2070 devices.add(*outputDevices);
2071 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002072 // Use media strategy for unspecified output device. This should only
2073 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2074 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002075 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002076 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002077 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002078 }
Michael Chan6fb34492020-12-08 15:44:49 +11002079 std::vector<PatchBuilder> patchesToCreate;
2080 for (auto i = 0u; i < devices.size(); ++i) {
2081 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002082 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002083 }
2084 // Retain only the MSD patches associated with outputDevices request.
2085 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002086 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002087 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2088 auto retainedPatch = false;
2089 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2090 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2091 patchesToRemove.removeItemsAt(i);
2092 retainedPatch = true;
2093 break;
2094 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002095 }
Michael Chan6fb34492020-12-08 15:44:49 +11002096 if (retainedPatch) {
2097 it = patchesToCreate.erase(it);
2098 continue;
2099 }
2100 ++it;
2101 }
2102 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2103 return NO_ERROR;
2104 }
2105 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2106 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002107 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002108 }
Michael Chan6fb34492020-12-08 15:44:49 +11002109 status_t status = NO_ERROR;
2110 for (const auto &p : patchesToCreate) {
2111 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2112 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2113 char message[256];
2114 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2115 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2116 currStatus == NO_ERROR ? "Success" : "Error",
2117 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2118 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2119 if (currStatus == NO_ERROR) {
2120 ALOGD("%s", message);
2121 } else {
2122 ALOGE("%s", message);
2123 if (status == NO_ERROR) {
2124 status = currStatus;
2125 }
2126 }
2127 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002128 return status;
2129}
2130
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002131void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2132 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002133 for (size_t i = 0; i < msdPatches.size(); i++) {
2134 const auto& patch = msdPatches[i];
2135 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2136 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2137 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2138 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2139 releaseAudioPatch(patch->getHandle(), mUidCached);
2140 break;
2141 }
2142 }
2143 }
2144}
2145
Dorin Drimus94d94412022-02-02 09:05:02 +01002146bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002147 DeviceVector devicesToCheck =
2148 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002149 AudioPatchCollection msdPatches = getMsdOutputPatches();
2150 for (size_t i = 0; i < msdPatches.size(); i++) {
2151 const auto& patch = msdPatches[i];
2152 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2153 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2154 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2155 const auto& foundDevice = devicesToCheck.getDevice(
2156 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2157 if (foundDevice != nullptr) {
2158 devicesToCheck.remove(foundDevice);
2159 if (devicesToCheck.isEmpty()) {
2160 return true;
2161 }
2162 }
2163 }
2164 }
2165 }
2166 return false;
2167}
2168
Eric Laurente0720872014-03-11 09:30:41 -07002169audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002170 audio_output_flags_t flags,
2171 audio_format_t format,
2172 audio_channel_mask_t channelMask,
2173 uint32_t samplingRate,
2174 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002175{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002176 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2177 "%s called with format %#x", __func__, format);
2178
jiabinebb6af42020-06-09 17:31:17 -07002179 // Return the output that haptic-generating attached to when 1) session id is specified,
2180 // 2) haptic-generating effect exists for given session id and 3) the output that
2181 // haptic-generating effect attached to is in given outputs.
2182 if (sessionId != AUDIO_SESSION_NONE) {
2183 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2184 sessionId, FX_IID_HAPTICGENERATOR);
2185 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2186 return hapticGeneratingOutput;
2187 }
2188 }
2189
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 // Flags disqualifying an output: the match must happen before calling selectOutput()
2191 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2192 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2193
2194 // Flags expressing a functional request: must be honored in priority over
2195 // other criteria
2196 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2197 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002198 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2199 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002200 // Flags expressing a performance request: have lower priority than serving
2201 // requested sampling rate or channel mask
2202 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2203 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2204 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2205
2206 const audio_output_flags_t functionalFlags =
2207 (audio_output_flags_t)(flags & kFunctionalFlags);
2208 const audio_output_flags_t performanceFlags =
2209 (audio_output_flags_t)(flags & kPerformanceFlags);
2210
2211 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2212
Eric Laurente552edb2014-03-10 17:42:56 -07002213 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002214 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002215 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002216 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002217 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002218 // with tiebreak preferring the minimum number of extra functional flags
2219 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002220 // 3: the output supporting the exact channel mask
2221 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002222 // 5: the output with the highest sampling rate if the requested sample rate is
2223 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002224 // 6: the output with the highest number of requested performance flags
2225 // 7: the output with the bit depth the closest to the requested one
2226 // 8: the primary output
2227 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002228
Eric Laurent16c66dd2019-05-01 17:54:10 -07002229 // matching criteria values in priority order for best matching output so far
2230 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002231
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002232 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002233 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2234 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2235 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002236
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002237 for (audio_io_handle_t output : outputs) {
2238 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002239 // matching criteria values in priority order for current output
2240 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002241
Eric Laurent16c66dd2019-05-01 17:54:10 -07002242 if (outputDesc->isDuplicated()) {
2243 continue;
2244 }
2245 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2246 continue;
2247 }
Eric Laurent8838a382014-09-08 16:44:28 -07002248
Eric Laurent16c66dd2019-05-01 17:54:10 -07002249 // If haptic channel is specified, use the haptic output if present.
2250 // When using haptic output, same audio format and sample rate are required.
2251 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002252 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002253 // skip if haptic channel specified but output does not support it, or output support haptic
2254 // but there is no haptic channel requested AND no orphan haptic effect exist
2255 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2256 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002257 continue;
2258 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002259 // In the case of audio-coupled-haptic playback, there is no format conversion and
2260 // resampling in the framework, same format/channel/sampleRate for client and the output
2261 // thread is required. In the case of HapticGenerator effect, do not require format
2262 // matching.
2263 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2264 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002265 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002266 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002267 }
2268
2269 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002270 const int matchingFunctionalFlags =
2271 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2272 const int totalFunctionalFlags =
2273 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2274 // Prefer matching functional flags, but subtract unnecessary functional flags.
2275 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002276
2277 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002278 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2279 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002280 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2281 channelCount <= outputChannelCount) {
2282 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002283 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2284 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002285 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002286 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002287 currentMatchCriteria[3] = outputChannelCount;
2288 }
2289
2290 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002291 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002292 int diff; // avoid unsigned integer overflow.
2293 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2294
2295 // prefer the closest output sampling rate greater than or equal to target
2296 // if none exists, prefer the closest output sampling rate less than target.
2297 //
2298 // criteria is offset to make non-negative.
2299 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002300 }
2301
2302 // performance flags match
2303 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2304
2305 // format match
2306 if (format != AUDIO_FORMAT_INVALID) {
2307 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002308 PolicyAudioPort::kFormatDistanceMax -
2309 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002310 }
2311
2312 // primary output match
2313 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2314
2315 // compare match criteria by priority then value
2316 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2317 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2318 bestMatchCriteria = currentMatchCriteria;
2319 bestOutput = output;
2320
2321 std::stringstream result;
2322 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2323 std::ostream_iterator<int>(result, " "));
2324 ALOGV("%s new bestOutput %d criteria %s",
2325 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002326 }
2327 }
2328
Eric Laurent16c66dd2019-05-01 17:54:10 -07002329 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002330}
2331
Eric Laurent8fc147b2018-07-22 19:13:55 -07002332status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002333{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002334 ALOGV("%s portId %d", __FUNCTION__, portId);
2335
2336 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2337 if (outputDesc == 0) {
2338 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002339 return BAD_VALUE;
2340 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002341 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002342
Eric Laurent8fc147b2018-07-22 19:13:55 -07002343 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002344 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002345
jiabin220eea12024-05-17 17:55:20 +00002346 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2347 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2348 && outputDesc->isBitPerfect()) {
2349 // Usually, APM selects bit-perfect output for high priority use cases only when
2350 // bit-perfect output is the only output that can be routed to the selected device.
2351 // However, here is no need to play high priority use cases such as ringtone and alarm
2352 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2353 // can attach to new output.
2354 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2355 __func__, client->stream());
2356 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2357 return DEAD_OBJECT;
2358 }
2359
Eric Laurent733ce942017-12-07 12:18:25 -08002360 status_t status = outputDesc->start();
2361 if (status != NO_ERROR) {
2362 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002363 }
2364
Eric Laurent97ac8712018-07-27 18:59:02 -07002365 uint32_t delayMs;
2366 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002367
2368 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002369 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002370 if (status == DEAD_OBJECT) {
2371 sp<SwAudioOutputDescriptor> desc =
2372 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2373 if (desc == nullptr) {
2374 // This is not common, it may indicate something wrong with the HAL.
2375 ALOGE("%s unable to open output with default config", __func__);
2376 return status;
2377 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002378 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002379 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002380 }
jiabina84c3d32022-12-02 18:59:55 +00002381
2382 // If the client is the first one active on preferred mixer parameters, reopen the output
2383 // if the current mixer parameters doesn't match the preferred one.
2384 if (outputDesc->devices().size() == 1) {
2385 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2386 outputDesc->devices()[0]->getId(), client->strategy());
2387 if (info != nullptr && info->getUid() == client->uid()) {
2388 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2389 info->getConfigBase(), info->getFlags())) {
2390 stopSource(outputDesc, client);
2391 outputDesc->stop();
2392 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2393 config.channel_mask = info->getConfigBase().channel_mask;
2394 config.sample_rate = info->getConfigBase().sample_rate;
2395 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002396 sp<SwAudioOutputDescriptor> desc =
2397 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2398 if (desc == nullptr) {
2399 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002400 }
jiabin220eea12024-05-17 17:55:20 +00002401 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002402 // Intentionally return error to let the client side resending request for
2403 // creating and starting.
2404 return DEAD_OBJECT;
2405 }
2406 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002407 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002408 // If it is first bit-perfect client, reroute all clients that will be routed to
2409 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2410 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002411 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002412 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002413 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2414 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002415 continue;
2416 }
jiabine6b87492024-09-18 23:36:14 +00002417 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2418 outputsToResetDevice.push_back(mOutputs[i]);
2419 }
jiabine3d1f552023-06-14 17:42:17 +00002420 for (const auto& c : mOutputs[i]->getClientIterable()) {
2421 clientsToInvalidate.push_back(c->portId());
2422 }
2423 }
2424 if (!clientsToInvalidate.empty()) {
2425 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2426 __func__);
2427 mpClientInterface->invalidateTracks(clientsToInvalidate);
2428 }
jiabine6b87492024-09-18 23:36:14 +00002429 for (const auto& output : outputsToResetDevice) {
2430 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2431 }
jiabine3d1f552023-06-14 17:42:17 +00002432 }
jiabina84c3d32022-12-02 18:59:55 +00002433 }
2434 }
2435
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002436 if (client->hasPreferredDevice()) {
2437 // playback activity with preferred device impacts routing occurred, inform upper layers
2438 mpClientInterface->onRoutingUpdated();
2439 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002440 if (delayMs != 0) {
2441 usleep(delayMs * 1000);
2442 }
2443
jiabin220eea12024-05-17 17:55:20 +00002444 if (status == NO_ERROR &&
2445 outputDesc->mPreferredAttrInfo != nullptr &&
2446 outputDesc->isBitPerfect() &&
2447 com::android::media::audioserver::
2448 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2449 // A new client is started on bit-perfect output, update all clients internal mute.
2450 updateClientsInternalMute(outputDesc);
2451 }
2452
Eric Laurentc75307b2015-03-17 15:29:32 -07002453 return status;
2454}
2455
Eric Laurent96d1dda2022-03-14 17:14:19 +01002456bool AudioPolicyManager::isLeUnicastActive() const {
2457 if (isInCall()) {
2458 return true;
2459 }
2460 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2461}
2462
2463bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2464 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2465 return false;
2466 }
2467 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2468 ALOGV("%s active %d", __func__, active);
2469 return active;
2470}
2471
Eric Laurent97ac8712018-07-27 18:59:02 -07002472status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2473 const sp<TrackClientDescriptor>& client,
2474 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002475{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002476 // cannot start playback of STREAM_TTS if any other output is being used
2477 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002478
2479 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002480 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002481 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002482 auto clientStrategy = client->strategy();
2483 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002484 if (stream == AUDIO_STREAM_TTS) {
2485 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002486 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002487 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002488 return INVALID_OPERATION;
2489 } else {
2490 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2491 }
2492 } else {
2493 // some playback other than beacon starts
2494 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2495 }
2496
Eric Laurent77305a62016-07-25 16:39:22 -07002497 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002498 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002499 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002500
François Gaffie11d30102018-11-02 16:09:09 +01002501 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002502 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002503 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002504 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002505 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002506 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002507 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002508 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002509 } else {
2510 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002511 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002512 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2513 AUDIO_FORMAT_DEFAULT);
2514 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2515 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002516 }
2517
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002518 // requiresMuteCheck is false when we can bypass mute strategy.
2519 // It covers a common case when there is no materially active audio
2520 // and muting would result in unnecessary delay and dropped audio.
2521 const uint32_t outputLatencyMs = outputDesc->latency();
2522 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002523 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002524
Eric Laurente552edb2014-03-10 17:42:56 -07002525 // increment usage count for this stream on the requested output:
2526 // NOTE that the usage count is the same for duplicated output and hardware output which is
2527 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002528 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002529
2530 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002531 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002532 // Preferred device may be exclusive, use only if no other active clients on this output
2533 devices = DeviceVector(
2534 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2535 } else {
2536 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2537 }
François Gaffie11d30102018-11-02 16:09:09 +01002538 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002539 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 }
2541 }
Eric Laurente552edb2014-03-10 17:42:56 -07002542
François Gaffiec005e562018-11-06 15:04:49 +01002543 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002544 selectOutputForMusicEffects();
2545 }
2546
François Gaffie1c878552018-11-22 16:53:21 +01002547 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002548 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002549 if (devices.isEmpty()) {
2550 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002551 }
François Gaffiec005e562018-11-06 15:04:49 +01002552 bool shouldWait =
2553 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2554 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2555 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002556 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002557 const bool needToCloseBitPerfectOutput =
2558 (com::android::media::audioserver::
2559 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2560 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2561 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002562 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002564 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002565 // An output has a shared device if
2566 // - managed by the same hw module
2567 // - supports the currently selected device
2568 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002569 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002570
Eric Laurent77305a62016-07-25 16:39:22 -07002571 // force a device change if any other output is:
2572 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002573 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002574 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002575 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002576 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002577 // change the device currently selected by the other output.
2578 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002579 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002580 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002581 force = true;
2582 }
2583 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002584 // a notification so that audio focus effect can propagate, or that a mute/unmute
2585 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002586 const uint32_t latencyMs = desc->latency();
2587 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2588
2589 if (shouldWait && isActive && (waitMs < latencyMs)) {
2590 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002591 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002592
2593 // Require mute check if another output is on a shared device
2594 // and currently active to have proper drain and avoid pops.
2595 // Note restoring AudioTracks onto this output needs to invoke
2596 // a volume ramp if there is no mute.
2597 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002598
2599 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2600 outputsToReopen.push_back(desc);
2601 }
Eric Laurente552edb2014-03-10 17:42:56 -07002602 }
2603 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002604
jiabin220eea12024-05-17 17:55:20 +00002605 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002606 // If the output is open with preferred mixer attributes, but the routed device is
2607 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2608 // changed.
2609 return DEAD_OBJECT;
2610 }
jiabin220eea12024-05-17 17:55:20 +00002611 for (auto& outputToReopen : outputsToReopen) {
2612 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2613 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002614 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302615 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2616 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002617
Eric Laurente552edb2014-03-10 17:42:56 -07002618 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002619 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002620 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002621 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002622 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002623 outputDesc->useHwGain() /*force*/)) {
2624 // request AudioService to reinitialize the volume curves asynchronously
2625 ALOGE("checkAndSetVolume failed, requesting volume range init");
2626 mpClientInterface->onVolumeRangeInitRequest();
2627 };
Eric Laurente552edb2014-03-10 17:42:56 -07002628
2629 // update the outputs if starting an output with a stream that can affect notification
2630 // routing
2631 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002632
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002633 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002634 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002635 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002636 }
Eric Laurentdc462862016-07-19 12:29:53 -07002637
2638 if (waitMs > muteWaitMs) {
2639 *delayMs = waitMs - muteWaitMs;
2640 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002641
2642 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2643 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2644 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2645 // change occurs after the MixerThread starts and causes a stream volume
2646 // glitch.
2647 //
2648 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
Eric Laurentdc462862016-07-19 12:29:53 -07002650
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002651 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002652 mEngine->getForceUse(
2653 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002654 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002655 }
2656
Eric Laurent97ac8712018-07-27 18:59:02 -07002657 // Automatically enable the remote submix input when output is started on a re routing mix
2658 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002659 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2660 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002661 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2662 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2663 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002664 "remote-submix",
2665 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002666 }
2667
Eric Laurent96d1dda2022-03-14 17:14:19 +01002668 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2669
Eric Laurente552edb2014-03-10 17:42:56 -07002670 return NO_ERROR;
2671}
2672
Eric Laurent96d1dda2022-03-14 17:14:19 +01002673void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2674 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2675 bool isUnicastActive = isLeUnicastActive();
2676
2677 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002678 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002679 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2680 for (size_t i = 0; i < mOutputs.size(); i++) {
2681 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2682 if (desc != ignoredOutput && desc->isActive()
2683 && ((isUnicastActive &&
2684 !desc->devices().
2685 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2686 || (wasUnicastActive &&
2687 !desc->devices().getDevicesFromTypes(
2688 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2689 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2690 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002691 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002692 // If the device is using preferred mixer attributes, the output need to reopen
2693 // with default configuration when the new selected devices are different from
2694 // current routing devices.
2695 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2696 continue;
2697 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302698 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002699 // re-apply device specific volume if not done by setOutputDevice()
2700 if (!force) {
2701 applyStreamVolumes(desc, newDevices.types(), delayMs);
2702 }
2703 }
2704 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002705 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002706 }
2707}
2708
Eric Laurent8fc147b2018-07-22 19:13:55 -07002709status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002710{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002711 ALOGV("%s portId %d", __FUNCTION__, portId);
2712
2713 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2714 if (outputDesc == 0) {
2715 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002716 return BAD_VALUE;
2717 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002718 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002719
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002720 if (client->hasPreferredDevice(true)) {
2721 // playback activity with preferred device impacts routing occurred, inform upper layers
2722 mpClientInterface->onRoutingUpdated();
2723 }
2724
Eric Laurent97ac8712018-07-27 18:59:02 -07002725 ALOGV("stopOutput() output %d, stream %d, session %d",
2726 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002727
Eric Laurent97ac8712018-07-27 18:59:02 -07002728 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002729
Eric Laurent733ce942017-12-07 12:18:25 -08002730 if (status == NO_ERROR ) {
2731 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002732 } else {
2733 return status;
2734 }
2735
2736 if (outputDesc->devices().size() == 1) {
2737 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2738 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002739 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002740 if (info != nullptr && info->getUid() == client->uid()) {
2741 info->decreaseActiveClient();
2742 if (info->getActiveClientCount() == 0) {
2743 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002744 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002745 }
2746 }
jiabin220eea12024-05-17 17:55:20 +00002747 if (com::android::media::audioserver::
2748 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2749 !outputReopened && outputDesc->isBitPerfect()) {
2750 // Only need to update the clients' internal mute when the output is bit-perfect and it
2751 // is not reopened.
2752 updateClientsInternalMute(outputDesc);
2753 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002754 }
2755 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002756}
2757
Eric Laurent97ac8712018-07-27 18:59:02 -07002758status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2759 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002760{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002761 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002762 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002763 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002764 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002765
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002766 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2767
François Gaffie1c878552018-11-22 16:53:21 +01002768 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2769 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002770 // Automatically disable the remote submix input when output is stopped on a
2771 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002772 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002773 if (isSingleDeviceType(
2774 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002775 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002776 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002777 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2778 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002779 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002780 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002781 }
2782 }
2783 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002784 if (client->hasPreferredDevice(true) &&
2785 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002786 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002787 forceDeviceUpdate = true;
2788 }
2789
Eric Laurente552edb2014-03-10 17:42:56 -07002790 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002791 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002792
Eric Laurente552edb2014-03-10 17:42:56 -07002793 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002794 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002795 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002796 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002797
2798 // If the routing does not change, if an output is routed on a device using HwGain
2799 // (aka setAudioPortConfig) and there are still active clients following different
2800 // volume group(s), force reapply volume
2801 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2802 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2803
Eric Laurente552edb2014-03-10 17:42:56 -07002804 // delay the device switch by twice the latency because stopOutput() is executed when
2805 // the track stop() command is received and at that time the audio track buffer can
2806 // still contain data that needs to be drained. The latency only covers the audio HAL
2807 // and kernel buffers. Also the latency does not always include additional delay in the
2808 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302809 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002810 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002811
2812 // force restoring the device selection on other active outputs if it differs from the
2813 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002814 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002815 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002816 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002817 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002818 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002819 desc->isActive() &&
2820 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002821 (newDevices != desc->devices())) {
2822 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2823 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002824
jiabin220eea12024-05-17 17:55:20 +00002825 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002826 // If the device is using preferred mixer attributes, the output need to
2827 // reopen with default configuration when the new selected devices are
2828 // different from current routing devices.
2829 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2830 continue;
2831 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302832 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002833
Eric Laurent57de36c2016-09-28 16:59:11 -07002834 // re-apply device specific volume if not done by setOutputDevice()
2835 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002836 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002837 }
Eric Laurente552edb2014-03-10 17:42:56 -07002838 }
2839 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002840 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002841 // update the outputs if stopping one with a stream that can affect notification routing
2842 handleNotificationRoutingForStream(stream);
2843 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002844
2845 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2846 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002847 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002848 }
2849
François Gaffiec005e562018-11-06 15:04:49 +01002850 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002851 selectOutputForMusicEffects();
2852 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002853
2854 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2855
Eric Laurente552edb2014-03-10 17:42:56 -07002856 return NO_ERROR;
2857 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002858 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002859 return INVALID_OPERATION;
2860 }
2861}
2862
jiabinbce0c1d2020-10-05 11:20:18 -07002863bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002864{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002865 ALOGV("%s portId %d", __FUNCTION__, portId);
2866
2867 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2868 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002869 // If an output descriptor is closed due to a device routing change,
2870 // then there are race conditions with releaseOutput from tracks
2871 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2872 // destroyed shortly thereafter.
2873 //
2874 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002875 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002876 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002877 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002878
2879 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002880
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302881 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2882 if (outputDesc->isClientActive(client)) {
2883 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2884 stopOutput(portId);
2885 }
2886
Eric Laurent8fc147b2018-07-22 19:13:55 -07002887 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2888 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002889 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002890 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002891 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002892 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002893 if (--outputDesc->mDirectOpenCount == 0) {
2894 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002895 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002896 }
2897 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302898
Andy Hung39efb7a2018-09-26 15:39:28 -07002899 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002900 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2901 // The output is pending reopened to query dynamic profiles and
2902 // there is no active clients
2903 closeOutput(outputDesc->mIoHandle);
2904 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2905 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2906 if (newOutputDesc == nullptr) {
2907 ALOGE("%s failed to open output", __func__);
2908 }
2909 return true;
2910 }
2911 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002912}
2913
Eric Laurentcaf7f482014-11-25 17:50:47 -08002914status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2915 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002916 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002917 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002918 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002919 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002920 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002921 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002922 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002923 audio_port_handle_t *portId,
2924 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002925{
François Gaffiec005e562018-11-06 15:04:49 +01002926 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002927 "flags %#x attributes=%s requested device ID %d",
2928 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2929 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002930
Eric Laurentad2e7b92017-09-14 20:06:42 -07002931 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002932 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002933 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002934 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002935 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002936 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002937 sp<RecordClientDescriptor> clientDesc;
2938 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002939 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002941
2942 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2943 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2944 return INVALID_OPERATION;
2945 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002946
Francois Gaffie716e1432019-01-14 16:58:59 +01002947 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2948 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002949 }
2950
Paul McLean466dc8e2015-04-17 13:15:36 -06002951 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002952 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002953 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002954
Eric Laurentad2e7b92017-09-14 20:06:42 -07002955 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2956 // possible
2957 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2958 *input != AUDIO_IO_HANDLE_NONE) {
2959 ssize_t index = mInputs.indexOfKey(*input);
2960 if (index < 0) {
2961 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2962 status = BAD_VALUE;
2963 goto error;
2964 }
2965 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966 RecordClientVector clients = inputDesc->getClientsForSession(session);
2967 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002968 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2969 status = BAD_VALUE;
2970 goto error;
2971 }
2972 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2973 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002974 // corresponds to a new client and is only permitted from the same UID.
2975 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 if (clients.size() > 1) {
2977 for (const auto& client : clients) {
2978 // The client map is ordered by key values (portId) and portIds are allocated
2979 // incrementaly. So the first client in this list is the one opened by audio flinger
2980 // when the mmap stream is created and should be ignored as it does not correspond
2981 // to an actual client
2982 if (client == *clients.cbegin()) {
2983 continue;
2984 }
2985 if (uid != client->uid() && !client->isSilenced()) {
2986 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2987 uid, client->portId(), client->uid());
2988 status = INVALID_OPERATION;
2989 goto error;
2990 }
Eric Laurent331679c2018-04-16 17:03:16 -07002991 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002992 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002993 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002994 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002995
Eric Laurentfecbceb2021-02-09 14:46:43 +01002996 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002997 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002998 }
2999
3000 *input = AUDIO_IO_HANDLE_NONE;
3001 *inputType = API_INPUT_INVALID;
3002
Francois Gaffie716e1432019-01-14 16:58:59 +01003003 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003004 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003005 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003007 ALOGW("%s could not find input mix for attr %s",
3008 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003009 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003010 }
jiabinc1de2df2019-05-07 14:26:40 -07003011 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3012 String8(attr->tags + strlen("addr=")),
3013 AUDIO_FORMAT_DEFAULT);
3014 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003015 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003016 __func__, attributes.source, attributes.tags);
3017 status = BAD_VALUE;
3018 goto error;
3019 }
3020
Kevin Rocard25f9b052019-02-27 15:08:54 -08003021 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3022 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3023 } else {
3024 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3025 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003026 if (virtualDeviceId) {
3027 *virtualDeviceId = policyMix->mVirtualDeviceId;
3028 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003029 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003030 if (explicitRoutingDevice != nullptr) {
3031 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003032 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003033 // Prevent from storing invalid requested device id in clients
3034 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003035 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003036 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3037 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003038 }
François Gaffie11d30102018-11-02 16:09:09 +01003039 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003040 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003041 status = BAD_VALUE;
3042 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003043 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003044 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3045 *inputType = API_INPUT_MIX_CAPTURE;
3046 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003047 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3048 // there is an external policy, but this input is attached to a mix of recorders,
3049 // meaning it receives audio injected into the framework, so the recorder doesn't
3050 // know about it and is therefore considered "legacy"
3051 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003052
3053 if (virtualDeviceId) {
3054 *virtualDeviceId = policyMix->mVirtualDeviceId;
3055 }
François Gaffie11d30102018-11-02 16:09:09 +01003056 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003057 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003058 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003059 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003060 } else {
3061 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003062 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003063
Eric Laurent599c7582015-12-07 18:05:55 -08003064 }
3065
François Gaffiec005e562018-11-06 15:04:49 +01003066 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003067 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003068 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003069 AudioProfileVector profiles;
3070 status_t ret = getProfilesForDevices(
3071 DeviceVector(device), profiles, flags, true /*isInput*/);
3072 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003073 const auto channels = profiles[0]->getChannels();
3074 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3075 config->channel_mask = *channels.begin();
3076 }
3077 const auto sampleRates = profiles[0]->getSampleRates();
3078 if (!sampleRates.empty() &&
3079 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3080 config->sample_rate = *sampleRates.begin();
3081 }
jiabinf1c73972022-04-14 16:28:52 -07003082 config->format = profiles[0]->getFormat();
3083 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003084 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003085 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003086
Marvin Ramine5a122d2023-12-07 13:57:59 +01003087
3088 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3089 *virtualDeviceId = policyMix->mVirtualDeviceId;
3090 }
3091
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092exit:
3093
François Gaffiec005e562018-11-06 15:04:49 +01003094 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3095 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003096
Francois Gaffie716e1432019-01-14 16:58:59 +01003097 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003098 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003099 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100
Mikhail Naganov2996f672019-04-18 12:29:59 -07003101 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003102 requestedDeviceId, attributes.source, flags,
3103 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003104 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003105 // Move (if found) effect for the client session to its input
3106 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003107 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003108
3109 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3110 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003111
Eric Laurent599c7582015-12-07 18:05:55 -08003112 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003113
3114error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003115 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003116}
3117
3118
François Gaffie11d30102018-11-02 16:09:09 +01003119audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003120 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003121 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003122 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003123 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003124 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003125{
3126 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003127 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003128 bool isSoundTrigger = false;
3129
François Gaffiec005e562018-11-06 15:04:49 +01003130 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003131 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3132 if (index >= 0) {
3133 input = mSoundTriggerSessions.valueFor(session);
3134 isSoundTrigger = true;
3135 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3136 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3137 } else {
3138 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003139 }
François Gaffiec005e562018-11-06 15:04:49 +01003140 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003141 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003142 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003143 }
3144
Carter Hsua3abb402021-10-26 11:11:20 +08003145 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3146 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3147 }
3148
Eric Laurentfe231122017-11-17 17:48:06 -08003149 // sampling rate and flags may be updated by getInputProfile
3150 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3151 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003152 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003153 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003154 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003155 // find a compatible input profile (not necessarily identical in parameters)
3156 sp<IOProfile> profile = getInputProfile(
3157 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3158 if (profile == nullptr) {
3159 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003160 }
jiabin2fd710d2022-05-02 23:20:22 +00003161
Glenn Kasten05ddca52016-02-11 08:17:12 -08003162 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003163 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003164 if (samplingRate == 0) {
3165 samplingRate = profileSamplingRate;
3166 }
Eric Laurente552edb2014-03-10 17:42:56 -07003167
Eric Laurent322b4d22015-04-03 15:57:54 -07003168 if (profile->getModuleHandle() == 0) {
3169 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003170 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003171 }
3172
Eric Laurentec376dc2021-04-08 20:41:22 +02003173 // Reuse an already opened input if a client with the same session ID already exists
3174 // on that input
3175 for (size_t i = 0; i < mInputs.size(); i++) {
3176 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3177 if (desc->mProfile != profile) {
3178 continue;
3179 }
3180 RecordClientVector clients = desc->clientsList();
3181 for (const auto &client : clients) {
3182 if (session == client->session()) {
3183 return desc->mIoHandle;
3184 }
3185 }
3186 }
3187
Eric Laurentc71b11b2024-06-03 12:54:53 +00003188 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003189 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003190 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3191 // First pick best candidate for preemption (there may not be any):
3192 // - Preempt and input if:
3193 // - It has only strictly lower priority use cases than the new client
3194 // - It has equal priority use cases than the new client, was not
3195 // opened thanks to preemption or has been active since opened.
3196 // - Order the preemption candidates by inactive first and priority second
3197 sp<AudioInputDescriptor> closeCandidate;
3198 int leastCloseRank = INT_MAX;
3199 static const int sCloseActive = 0x100;
3200
3201 for (size_t i = 0; i < mInputs.size(); i++) {
3202 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3203 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003204 continue;
3205 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003206 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3207 if (topPrioClient == nullptr) {
3208 continue;
3209 }
3210 int topPrio = source_priority(topPrioClient->source());
3211 if (topPrio < source_priority(attributes.source)
3212 || (topPrio == source_priority(attributes.source)
3213 && !desc->isPreemptor())) {
3214 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3215 if (closeRank < leastCloseRank) {
3216 leastCloseRank = closeRank;
3217 closeCandidate = desc;
3218 }
3219 }
3220 }
3221
3222 if (closeCandidate != nullptr) {
3223 closeInput(closeCandidate->mIoHandle);
3224 // Mark the new input as being issued from a preemption
3225 // so that is will not be preempted later
3226 isPreemptor = true;
3227 } else {
3228 // Then pick the best reusable input (There is always one)
3229 // The order of preference is:
3230 // 1) active inputs with same use case as the new client
3231 // 2) inactive inputs with same use case
3232 // 3) active inputs with different use cases
3233 // 4) inactive inputs with different use cases
3234 sp<AudioInputDescriptor> reuseCandidate;
3235 int leastReuseRank = INT_MAX;
3236 static const int sReuseDifferentUseCase = 0x100;
3237
3238 for (size_t i = 0; i < mInputs.size(); i++) {
3239 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3240 if (desc->mProfile != profile) {
3241 continue;
3242 }
3243 int reuseRank = sReuseDifferentUseCase;
3244 for (const auto& client: desc->getClientIterable()) {
3245 if (client->source() == attributes.source) {
3246 reuseRank = 0;
3247 break;
3248 }
3249 }
3250 reuseRank += desc->isActive() ? 0 : 1;
3251 if (reuseRank < leastReuseRank) {
3252 leastReuseRank = reuseRank;
3253 reuseCandidate = desc;
3254 }
3255 }
3256 return reuseCandidate->mIoHandle;
3257 }
3258 } else { // fix_input_sharing_logic()
3259 for (size_t i = 0; i < mInputs.size(); ) {
3260 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3261 if (desc->mProfile != profile) {
3262 i++;
3263 continue;
3264 }
3265 // if sound trigger, reuse input if used by other sound trigger on same session
3266 // else
3267 // reuse input if active client app is not in IDLE state
3268 //
3269 RecordClientVector clients = desc->clientsList();
3270 bool doClose = false;
3271 for (const auto& client : clients) {
3272 if (isSoundTrigger != client->isSoundTrigger()) {
3273 continue;
3274 }
3275 if (client->isSoundTrigger()) {
3276 if (session == client->session()) {
3277 return desc->mIoHandle;
3278 }
3279 continue;
3280 }
3281 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003282 return desc->mIoHandle;
3283 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003284 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003285 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003286 if (doClose) {
3287 closeInput(desc->mIoHandle);
3288 } else {
3289 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003290 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003291 }
3292 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003293 }
3294
Eric Laurentc71b11b2024-06-03 12:54:53 +00003295 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3296 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003297
Eric Laurentfe231122017-11-17 17:48:06 -08003298 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3299 lConfig.sample_rate = profileSamplingRate;
3300 lConfig.channel_mask = profileChannelMask;
3301 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003302
François Gaffie11d30102018-11-02 16:09:09 +01003303 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003304
3305 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003306 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003307 (profileSamplingRate != lConfig.sample_rate) ||
3308 !audio_formats_match(profileFormat, lConfig.format) ||
3309 (profileChannelMask != lConfig.channel_mask)) {
3310 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003311 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003312 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003313 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003314 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003315 }
Eric Laurent599c7582015-12-07 18:05:55 -08003316 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003317 }
3318
Eric Laurentc722f302014-12-10 11:21:49 -08003319 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003320
Eric Laurent599c7582015-12-07 18:05:55 -08003321 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003322 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003323
Eric Laurent599c7582015-12-07 18:05:55 -08003324 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003325}
3326
Eric Laurent4eb58f12018-12-07 16:41:02 -08003327status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003328{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003329 ALOGV("%s portId %d", __FUNCTION__, portId);
3330
3331 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3332 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003334 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003335 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003336 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003337 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338 if (client->active()) {
3339 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3340 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003341 }
3342
Eric Laurent8f42ea12018-08-08 09:08:25 -07003343 audio_session_t session = client->session();
3344
Eric Laurent4eb58f12018-12-07 16:41:02 -08003345 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346
Eric Laurent4eb58f12018-12-07 16:41:02 -08003347 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003348
Eric Laurent4eb58f12018-12-07 16:41:02 -08003349 status_t status = inputDesc->start();
3350 if (status != NO_ERROR) {
3351 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003352 }
Eric Laurente552edb2014-03-10 17:42:56 -07003353
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003354 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003355 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003356 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003357
Eric Laurent8f42ea12018-08-08 09:08:25 -07003358 // indicate active capture to sound trigger service if starting capture from a mic on
3359 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003360 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003361 if (device != nullptr) {
3362 status = setInputDevice(input, device, true /* force */);
3363 } else {
3364 ALOGW("%s no new input device can be found for descriptor %d",
3365 __FUNCTION__, inputDesc->getId());
3366 status = BAD_VALUE;
3367 }
Eric Laurente552edb2014-03-10 17:42:56 -07003368
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003369 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003370 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003371 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003372 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003373 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3374 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003376 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003377
François Gaffie11d30102018-11-02 16:09:09 +01003378 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3379 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003380 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003381 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003382 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003383
Eric Laurent8f42ea12018-08-08 09:08:25 -07003384 // automatically enable the remote submix output when input is started if not
3385 // used by a policy mix of type MIX_TYPE_RECORDERS
3386 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003387 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003388 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003389 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003390 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003391 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3392 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003393 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 if (address != "") {
3395 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3396 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003397 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003398 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003399 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003400 } else if (status != NO_ERROR) {
3401 // Restore client activity state.
3402 inputDesc->setClientActive(client, false);
3403 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003404 }
3405
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003406 ALOGV("%s input %d source = %d status = %d exit",
3407 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003408
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003409 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003410}
3411
Eric Laurent8fc147b2018-07-22 19:13:55 -07003412status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003413{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003414 ALOGV("%s portId %d", __FUNCTION__, portId);
3415
3416 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3417 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003418 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003419 return BAD_VALUE;
3420 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003421 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003422 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003423 if (!client->active()) {
3424 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003425 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003426 }
Carter Hsue6139d52021-07-08 10:30:20 +08003427 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003428 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003429
Eric Laurent8f42ea12018-08-08 09:08:25 -07003430 inputDesc->stop();
3431 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003432 auto current_source = inputDesc->source();
3433 setInputDevice(input, getNewInputDevice(inputDesc),
3434 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003435 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003436 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003437 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003438 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003439 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3440 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003441 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003442 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003443
3444 // automatically disable the remote submix output when input is stopped if not
3445 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003446 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003447 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003448 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003450 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3451 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003452 }
3453 if (address != "") {
3454 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3455 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003456 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457 }
3458 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003459 resetInputDevice(input);
3460
3461 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3462 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003463 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3464 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003465 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003466 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003467 }
3468 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003469 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003470 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003471}
3472
Eric Laurent8fc147b2018-07-22 19:13:55 -07003473void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003474{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003475 ALOGV("%s portId %d", __FUNCTION__, portId);
3476
3477 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3478 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003479 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003480 return;
3481 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003482 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003483 audio_io_handle_t input = inputDesc->mIoHandle;
3484
Eric Laurent8f42ea12018-08-08 09:08:25 -07003485 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003486
Andy Hung39efb7a2018-09-26 15:39:28 -07003487 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003488
3489 // If no more clients are present in this session, park effects to an orphan chain
3490 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3491 if (clientsOnSession.size() == 0) {
3492 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3493 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003494 if (inputDesc->getClientCount() > 0) {
3495 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003496 return;
3497 }
3498
Eric Laurent05b90f82014-08-27 15:32:29 -07003499 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003500 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003501 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003502}
3503
Eric Laurent8f42ea12018-08-08 09:08:25 -07003504void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003505{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003506 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003507
3508 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003509 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003510 }
3511}
3512
Eric Laurent8f42ea12018-08-08 09:08:25 -07003513void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3514{
3515 stopInput(portId);
3516 releaseInput(portId);
3517}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003518
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003519bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3520 if (input->clientsList().size() == 0
3521 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3522 return true;
3523 }
3524 for (const auto& client : input->clientsList()) {
3525 sp<DeviceDescriptor> device =
3526 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3527 client->session());
3528 if (!input->supportedDevices().contains(device)) {
3529 return true;
3530 }
3531 }
3532 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3533 return false;
3534}
3535
Eric Laurent0dd51852019-04-19 18:18:58 -07003536void AudioPolicyManager::checkCloseInputs() {
3537 // After connecting or disconnecting an input device, close input if:
3538 // - it has no client (was just opened to check profile) OR
3539 // - none of its supported devices are connected anymore OR
3540 // - one of its clients cannot be routed to one of its supported
3541 // devices anymore. Otherwise update device selection
3542 std::vector<audio_io_handle_t> inputsToClose;
3543 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003544 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003545 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003546 }
3547 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003548 for (const audio_io_handle_t handle : inputsToClose) {
3549 ALOGV("%s closing input %d", __func__, handle);
3550 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003551 }
Eric Laurentd4692962014-05-05 18:13:44 -07003552}
3553
Vlad Popa87e0e582024-05-20 18:49:20 -07003554status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3555 const char *address __unused,
3556 bool enabled,
3557 audio_stream_type_t streamToDriveAbs)
3558{
Vlad Popaa536eb32024-07-18 16:00:35 -07003559 if (!enabled) {
3560 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3561 return NO_ERROR;
3562 }
3563
Vlad Popa87e0e582024-05-20 18:49:20 -07003564 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3565 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3566 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3567 toString(streamToDriveAbs).c_str());
3568 return BAD_VALUE;
3569 }
3570
Vlad Popaa536eb32024-07-18 16:00:35 -07003571 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003572 return NO_ERROR;
3573}
3574
François Gaffie251c7f02018-11-07 10:41:08 +01003575void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003576{
3577 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003578 if (indexMin < 0 || indexMax < 0) {
3579 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3580 return;
3581 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003582 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003583
3584 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003585 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3586 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003587 continue;
3588 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003589 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003590 }
Eric Laurente552edb2014-03-10 17:42:56 -07003591}
3592
Eric Laurente0720872014-03-11 09:30:41 -07003593status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003594 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003595 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003596 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003597{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003598 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003599 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3600 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3601 return NO_ERROR;
3602 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303603 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3604 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003605 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003606}
3607
Eric Laurente0720872014-03-11 09:30:41 -07003608status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003609 int *index,
3610 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003611{
François Gaffiec005e562018-11-06 15:04:49 +01003612 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3613 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003614 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003615 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003616 deviceTypes = mEngine->getOutputDevicesForStream(
3617 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003618 }
jiabin9a3361e2019-10-01 09:38:30 -07003619 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003620}
3621
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003622status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003623 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003624 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003625 audio_devices_t device)
3626{
3627 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003628 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3629 if (group == VOLUME_GROUP_NONE) {
3630 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003631 return BAD_VALUE;
3632 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003633 ALOGV("%s: group %d matching with %s index %d",
3634 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003635 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3636 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3637 __FUNCTION__, toString(attributes).c_str());
3638 return NO_ERROR;
3639 }
François Gaffiecfe17322018-11-07 13:41:29 +01003640 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003641 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003642 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003643 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3644 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3645 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3646 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003647 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3648
Vlad Popa1e865e62024-08-15 19:11:42 -07003649
3650 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003651 if (status != NO_ERROR) {
3652 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3653 return status;
3654 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003655
jiabin9a3361e2019-10-01 09:38:30 -07003656 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003657 auto curCurvAttrs = curves.getAttributes();
3658 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3659 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003660 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003661 } else if (!curves.getStreamTypes().empty()) {
3662 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003663 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003664 } else {
3665 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3666 return BAD_VALUE;
3667 }
jiabin9a3361e2019-10-01 09:38:30 -07003668 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3669 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003670
François Gaffiecfe17322018-11-07 13:41:29 +01003671 // update volume on all outputs and streams matching the following:
3672 // - The requested stream (or a stream matching for volume control) is active on the output
3673 // - The device (or devices) selected by the engine for this stream includes
3674 // the requested device
3675 // - For non default requested device, currently selected device on the output is either the
3676 // requested device or one of the devices selected by the engine for this stream
3677 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3678 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003679 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003680 for (size_t i = 0; i < mOutputs.size(); i++) {
3681 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003682 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003683
jiabin9a3361e2019-10-01 09:38:30 -07003684 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3685 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003686 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003687
3688 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003689 continue;
3690 }
3691 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3692 curDevices.find(device) == curDevices.end()) {
3693 continue;
3694 }
3695 bool applyVolume = false;
3696 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3697 curSrcDevices.insert(device);
3698 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003699 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3700 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003701 } else {
3702 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3703 }
3704 if (!applyVolume) {
3705 continue; // next output
3706 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003707 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3708 // If a higher priority strategy is active, and the output is routed to a device with a
3709 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003710 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003711 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003712 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003713 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003714 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003715 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3716 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3717 false /*preferredDevice*/);
3718 if (activeClients.empty()) {
3719 continue;
3720 }
3721 bool isPreempted = false;
3722 bool isHigherPriority = productStrategy < strategy;
3723 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003724 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003725 ALOGV("%s: Strategy=%d (\nrequester:\n"
3726 " group %d, volumeGroup=%d attributes=%s)\n"
3727 " higher priority source active:\n"
3728 " volumeGroup=%d attributes=%s) \n"
3729 " on output %zu, bailing out", __func__, productStrategy,
3730 group, group, toString(attributes).c_str(),
3731 client->volumeSource(), toString(client->attributes()).c_str(), i);
3732 applyVolume = false;
3733 isPreempted = true;
3734 break;
3735 }
3736 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003737 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003738 applyVolume = true;
3739 }
3740 }
3741 if (isPreempted || applyVolume) {
3742 break;
3743 }
3744 }
3745 if (!applyVolume) {
3746 continue; // next output
3747 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003748 }
François Gaffieed91f582020-01-31 10:35:37 +01003749 //FIXME: workaround for truncated touch sounds
3750 // delayed volume change for system stream to be removed when the problem is
3751 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003752 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003753 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003754 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3755 if (volStatus != NO_ERROR) {
3756 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003757 }
3758 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003759
3760 // update voice volume if the an active call route exists
3761 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3762 && (curSrcDevices.find(
3763 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3764 != curSrcDevices.end())) {
3765 bool isVoiceVolSrc;
3766 bool isBtScoVolSrc;
3767 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3768 isVoiceVolSrc, isBtScoVolSrc, __func__)
3769 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003770 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3771 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3772 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003773 }
3774 }
3775
François Gaffiecfe17322018-11-07 13:41:29 +01003776 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3777 return status;
3778}
3779
François Gaffieaaac0fd2018-11-22 17:56:39 +01003780status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003781 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003782 audio_devices_t device,
3783 IVolumeCurves &volumeCurves)
3784{
3785 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3786 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003787 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3788 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003789 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303790 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3791 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003792 return BAD_VALUE;
3793 }
3794 if (!audio_is_output_device(device)) {
3795 return BAD_VALUE;
3796 }
3797
3798 // Force max volume if stream cannot be muted
3799 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3800
Vlad Popa1e865e62024-08-15 19:11:42 -07003801 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003802 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003803 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003804 return NO_ERROR;
3805}
3806
3807status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3808 int &index,
3809 audio_devices_t device)
3810{
3811 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3812 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003813 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003814 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003815 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003816 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003817 }
jiabin9a3361e2019-10-01 09:38:30 -07003818 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003819}
3820
3821status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3822 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003823 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003824{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003825 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003826 return BAD_VALUE;
3827 }
jiabin9a3361e2019-10-01 09:38:30 -07003828 index = curves.getVolumeIndex(deviceTypes);
3829 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003830 return NO_ERROR;
3831}
3832
3833status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3834 int &index)
3835{
3836 index = getVolumeCurves(attr).getVolumeIndexMin();
3837 return NO_ERROR;
3838}
3839
3840status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3841 int &index)
3842{
3843 index = getVolumeCurves(attr).getVolumeIndexMax();
3844 return NO_ERROR;
3845}
3846
Eric Laurent36829f92017-04-07 19:04:42 -07003847audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003848{
3849 // select one output among several suitable for global effects.
3850 // The priority is as follows:
3851 // 1: An offloaded output. If the effect ends up not being offloadable,
3852 // AudioFlinger will invalidate the track and the offloaded output
3853 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003854 // 2: Spatializer output if the stereo spatializer feature enabled
3855 // 3: A deep buffer output
3856 // 4: The primary output
3857 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003858
François Gaffiec005e562018-11-06 15:04:49 +01003859 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3860 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003861 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003862
Eric Laurent36829f92017-04-07 19:04:42 -07003863 if (outputs.size() == 0) {
3864 return AUDIO_IO_HANDLE_NONE;
3865 }
Eric Laurente552edb2014-03-10 17:42:56 -07003866
Eric Laurent36829f92017-04-07 19:04:42 -07003867 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3868 bool activeOnly = true;
3869
3870 while (output == AUDIO_IO_HANDLE_NONE) {
3871 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003872 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003873 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3874 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3875
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003876 for (audio_io_handle_t outputLoop : outputs) {
3877 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003878 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003879 continue;
3880 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003881 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003882 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003883 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003884 outputOffloaded = outputLoop;
3885 }
3886 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3887 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3888 outputSpatializer = outputLoop;
3889 }
Eric Laurent36829f92017-04-07 19:04:42 -07003890 }
3891 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003892 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003893 }
3894 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003895 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003896 }
3897 }
3898 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3899 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003900 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3901 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003902 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3903 output = outputDeepBuffer;
3904 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3905 output = outputPrimary;
3906 } else {
3907 output = outputs[0];
3908 }
3909 activeOnly = false;
3910 }
3911
3912 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003913 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3914 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003915 mMusicEffectOutput = output;
3916 }
3917
3918 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003919 return output;
3920}
3921
Eric Laurent36829f92017-04-07 19:04:42 -07003922audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3923{
3924 return selectOutputForMusicEffects();
3925}
3926
Eric Laurente0720872014-03-11 09:30:41 -07003927status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003928 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003929 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003930 int session,
3931 int id)
3932{
Shunkai Yao29d10572024-03-19 04:31:47 +00003933 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003934 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003935 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003936 index = mInputs.indexOfKey(io);
3937 if (index < 0) {
3938 ALOGW("registerEffect() unknown io %d", io);
3939 return INVALID_OPERATION;
3940 }
Eric Laurente552edb2014-03-10 17:42:56 -07003941 }
3942 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003943 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3944 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3945 || strategy == PRODUCT_STRATEGY_NONE));
3946 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003947}
3948
Eric Laurentc241b0d2018-11-28 09:08:49 -08003949status_t AudioPolicyManager::unregisterEffect(int id)
3950{
3951 if (mEffects.getEffect(id) == nullptr) {
3952 return INVALID_OPERATION;
3953 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003954 if (mEffects.isEffectEnabled(id)) {
3955 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3956 setEffectEnabled(id, false);
3957 }
3958 return mEffects.unregisterEffect(id);
3959}
3960
3961status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3962{
3963 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3964 if (effect == nullptr) {
3965 return INVALID_OPERATION;
3966 }
3967
3968 status_t status = mEffects.setEffectEnabled(id, enabled);
3969 if (status == NO_ERROR) {
3970 mInputs.trackEffectEnabled(effect, enabled);
3971 }
3972 return status;
3973}
3974
Eric Laurent6c796322019-04-09 14:13:17 -07003975
3976status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3977{
3978 mEffects.moveEffects(ids, io);
3979 return NO_ERROR;
3980}
3981
Eric Laurentc75307b2015-03-17 15:29:32 -07003982bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3983{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003984 auto vs = toVolumeSource(stream, false);
3985 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003986}
3987
3988bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3989{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003990 auto vs = toVolumeSource(stream, false);
3991 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003992}
3993
Eric Laurente0720872014-03-11 09:30:41 -07003994bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003995{
3996 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003997 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003998 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003999 return true;
4000 }
4001 }
4002 return false;
4003}
4004
Eric Laurent275e8e92014-11-30 15:14:47 -08004005// Register a list of custom mixes with their attributes and format.
4006// When a mix is registered, corresponding input and output profiles are
4007// added to the remote submix hw module. The profile contains only the
4008// parameters (sampling rate, format...) specified by the mix.
4009// The corresponding input remote submix device is also connected.
4010//
4011// When a remote submix device is connected, the address is checked to select the
4012// appropriate profile and the corresponding input or output stream is opened.
4013//
4014// When capture starts, getInputForAttr() will:
4015// - 1 look for a mix matching the address passed in attribtutes tags if any
4016// - 2 if none found, getDeviceForInputSource() will:
4017// - 2.1 look for a mix matching the attributes source
4018// - 2.2 if none found, default to device selection by policy rules
4019// At this time, the corresponding output remote submix device is also connected
4020// and active playback use cases can be transferred to this mix if needed when reconnecting
4021// after AudioTracks are invalidated
4022//
4023// When playback starts, getOutputForAttr() will:
4024// - 1 look for a mix matching the address passed in attribtutes tags if any
4025// - 2 if none found, look for a mix matching the attributes usage
4026// - 3 if none found, default to device and output selection by policy rules.
4027
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004028status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004029{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4031 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004032 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004033 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004034 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 // examine each mix's route type
4036 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004037 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004038 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4039 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4040 ALOGE("Unsupported Policy Mix %zu of %zu: "
4041 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4042 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004043 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004044 break;
4045 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004046 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4047 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004048 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004049 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4050 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004051 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004052 rSubmixModule = mHwModules.getModuleFromName(
4053 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4054 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004055 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004056 i);
4057 res = INVALID_OPERATION;
4058 break;
4059 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004060 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004061
Eric Laurent97ac8712018-07-27 18:59:02 -07004062 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004063 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004064 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004065 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004066 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4067 } else {
4068 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4069 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004070 }
François Gaffie036e1e92015-03-19 10:16:24 +01004071
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004072 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004073 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004074 res = INVALID_OPERATION;
4075 break;
4076 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004077 audio_config_t outputConfig = mix.mFormat;
4078 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004079 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4080 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004081 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4082 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004083 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004084 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4085 audio_is_linear_pcm(outputConfig.format)
4086 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004087 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004088 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4089 audio_is_linear_pcm(inputConfig.format)
4090 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004091
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004092 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004093 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004094 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004095 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004096 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004097 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004098 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004099 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4100 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004101 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004102 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004103 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004104
4105 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4106 mix.mDeviceType, mix.mDeviceAddress,
4107 String8(), AUDIO_FORMAT_DEFAULT);
4108 if (device == nullptr) {
4109 res = INVALID_OPERATION;
4110 break;
4111 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004112
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004113 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004114 // First try to find an already opened output supporting the device
4115 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004116 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004117
Eric Laurentc529cf62020-04-17 18:19:10 -07004118 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004119 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004120 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004121 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004122 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004123 } else {
4124 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004125 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004126 }
4127 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004128 // If no output found, try to find a direct output profile supporting the device
4129 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4130 sp<HwModule> module = mHwModules[i];
4131 for (size_t j = 0;
4132 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4133 j++) {
4134 sp<IOProfile> profile = module->getOutputProfiles()[j];
4135 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4136 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4137 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004138 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004139 res = INVALID_OPERATION;
4140 } else {
4141 foundOutput = true;
4142 }
4143 }
4144 }
4145 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004146 if (res != NO_ERROR) {
4147 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004148 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004149 res = INVALID_OPERATION;
4150 break;
4151 } else if (!foundOutput) {
4152 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004153 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004154 res = INVALID_OPERATION;
4155 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004156 } else {
4157 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004158 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004159 }
Eric Laurentc722f302014-12-10 11:21:49 -08004160 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004161 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004162 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004163 if (audio_flags::audio_mix_ownership()) {
4164 // Only unregister mixes that were actually registered to not accidentally unregister
4165 // mixes that already existed previously.
4166 unregisterPolicyMixes(registeredMixes);
4167 registeredMixes.clear();
4168 } else {
4169 unregisterPolicyMixes(mixes);
4170 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004171 } else if (checkOutputs) {
4172 checkForDeviceAndOutputChanges();
4173 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004174 }
4175 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004176}
4177
4178status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4179{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004180 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004181 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004182 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004183 sp<HwModule> rSubmixModule;
4184 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004185 for (const auto& mix : mixes) {
4186 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004187
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004188 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004189 rSubmixModule = mHwModules.getModuleFromName(
4190 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4191 if (rSubmixModule == 0) {
4192 res = INVALID_OPERATION;
4193 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004194 }
4195 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004196
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004197 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004198
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004199 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004200 res = INVALID_OPERATION;
4201 continue;
4202 }
4203
Marvin Ramin0783e202024-03-05 12:45:50 +01004204 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004205 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004206 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4207 status_t currentRes =
4208 setDeviceConnectionStateInt(device,
4209 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4210 address.c_str(),
4211 "remote-submix",
4212 AUDIO_FORMAT_DEFAULT);
4213 if (!audio_flags::audio_mix_ownership()) {
4214 res = currentRes;
4215 }
4216 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004217 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004218 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004219 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004220 }
4221 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004222 }
jiabin5740f082019-08-19 15:08:30 -07004223 rSubmixModule->removeOutputProfile(address.c_str());
4224 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004225
Kevin Rocard153f92d2018-12-18 18:33:28 -08004226 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004227 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004228 res = INVALID_OPERATION;
4229 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004230 } else {
4231 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004232 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004233 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004234 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004235
4236 if (res == NO_ERROR && checkOutputs) {
4237 checkForDeviceAndOutputChanges();
4238 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004239 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004240 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004241}
4242
Marvin Raminbdefaf02023-11-01 09:10:32 +01004243status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4244 if (!audio_flags::audio_mix_test_api()) {
4245 return INVALID_OPERATION;
4246 }
4247
4248 _aidl_return.clear();
4249 _aidl_return.reserve(mPolicyMixes.size());
4250 for (const auto &policyMix: mPolicyMixes) {
4251 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4252 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4253 policyMix->mCbFlags);
4254 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004255 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004256 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004257 }
4258
Vlad Popaa5d73f32024-03-08 16:05:38 -08004259 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004260 return OK;
4261}
4262
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004263status_t AudioPolicyManager::updatePolicyMix(
4264 const AudioMix& mix,
4265 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4266 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4267 if (res == NO_ERROR) {
4268 checkForDeviceAndOutputChanges();
4269 updateCallAndOutputRouting();
4270 }
4271 return res;
4272}
4273
Mikhail Naganov100f0122018-11-29 11:22:16 -08004274void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4275{
4276 size_t i = 0;
4277 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4278 for (const auto& fmt : mManualSurroundFormats) {
4279 if (i++ != 0) dst->append(", ");
4280 std::string sfmt;
4281 FormatConverter::toString(fmt, sfmt);
4282 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4283 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4284 }
4285}
4286
Eric Laurentc529cf62020-04-17 18:19:10 -07004287// Returns true if all devices types match the predicate and are supported by one HW module
4288bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004289 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004290 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004291 const char *context,
4292 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004293 for (size_t i = 0; i < devices.size(); i++) {
4294 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004295 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004296 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004297 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004298 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004299 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004300 return false;
4301 }
4302 }
4303 return true;
4304}
4305
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004306void AudioPolicyManager::changeOutputDevicesMuteState(
4307 const AudioDeviceTypeAddrVector& devices) {
4308 ALOGVV("%s() num devices %zu", __func__, devices.size());
4309
4310 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4311 getSoftwareOutputsForDevices(devices);
4312
4313 for (size_t i = 0; i < outputs.size(); i++) {
4314 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4315 DeviceVector prevDevices = outputDesc->devices();
4316 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4317 }
4318}
4319
4320std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4321 const AudioDeviceTypeAddrVector& devices) const
4322{
4323 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4324 DeviceVector deviceDescriptors;
4325 for (size_t j = 0; j < devices.size(); j++) {
4326 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4327 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4328 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4329 ALOGE("%s: device type %#x address %s not supported or not an output device",
4330 __func__, devices[j].mType, devices[j].getAddress());
4331 continue;
4332 }
4333 deviceDescriptors.add(desc);
4334 }
4335 for (size_t i = 0; i < mOutputs.size(); i++) {
4336 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4337 continue;
4338 }
4339 outputs.push_back(mOutputs.valueAt(i));
4340 }
4341 return outputs;
4342}
4343
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004344status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004345 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004346 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004347 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4348 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004349 }
4350 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004351 if (res != NO_ERROR) {
4352 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4353 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004354 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004355
4356 checkForDeviceAndOutputChanges();
4357 updateCallAndOutputRouting();
4358
4359 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004360}
4361
4362status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4363 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004364 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4365 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004366 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004367 __FUNCTION__, uid);
4368 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004369 }
4370
Eric Laurentc529cf62020-04-17 18:19:10 -07004371 checkForDeviceAndOutputChanges();
4372 updateCallAndOutputRouting();
4373
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004374 return res;
4375}
4376
Eric Laurent2517af32020-11-25 15:31:27 +01004377
jiabin0a488932020-08-07 17:32:40 -07004378status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4379 device_role_t role,
4380 const AudioDeviceTypeAddrVector &devices) {
4381 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4382 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004383
Eric Laurentc529cf62020-04-17 18:19:10 -07004384 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004385 return BAD_VALUE;
4386 }
jiabin0a488932020-08-07 17:32:40 -07004387 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004388 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004389 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4390 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004391 return status;
4392 }
4393
4394 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004395
4396 bool forceVolumeReeval = false;
4397 // FIXME: workaround for truncated touch sounds
4398 // to be removed when the problem is handled by system UI
4399 uint32_t delayMs = 0;
4400 if (strategy == mCommunnicationStrategy) {
4401 forceVolumeReeval = true;
4402 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4403 updateInputRouting();
4404 }
4405 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004406
4407 return NO_ERROR;
4408}
4409
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004410void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4411 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004412{
4413 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004414 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004415 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004416 // Only apply special touch sound delay once
4417 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004418 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004419 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004420 for (size_t i = 0; i < mOutputs.size(); i++) {
4421 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4422 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004423 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4424 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004425 // As done in setDeviceConnectionState, we could also fix default device issue by
4426 // preventing the force re-routing in case of default dev that distinguishes on address.
4427 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004428 bool newDevicesNotEmpty = !newDevices.isEmpty();
4429 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4430 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004431 // If the device is using preferred mixer attributes, the output need to reopen
4432 // with default configuration when the new selected devices are different from
4433 // current routing devices.
4434 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4435 continue;
4436 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304437
jiabin2361ed82024-09-20 17:36:31 +00004438 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4439 newDevicesNotEmpty /*force*/, delayMs,
4440 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4441 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004442 // Only apply special touch sound delay once
4443 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004444 }
4445 if (forceVolumeReeval && !newDevices.isEmpty()) {
4446 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4447 }
4448 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004449 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004450 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004451}
4452
Eric Laurent2517af32020-11-25 15:31:27 +01004453void AudioPolicyManager::updateInputRouting() {
4454 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304455 // Skip for hotword recording as the input device switch
4456 // is handled within sound trigger HAL
4457 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4458 continue;
4459 }
Eric Laurent2517af32020-11-25 15:31:27 +01004460 auto newDevice = getNewInputDevice(activeDesc);
4461 // Force new input selection if the new device can not be reached via current input
4462 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4463 setInputDevice(activeDesc->mIoHandle, newDevice);
4464 } else {
4465 closeInput(activeDesc->mIoHandle);
4466 }
4467 }
4468}
4469
Paul Wang5d7cdb52022-11-22 09:45:06 +00004470status_t
4471AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4472 device_role_t role,
4473 const AudioDeviceTypeAddrVector &devices) {
4474 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4475 dumpAudioDeviceTypeAddrVector(devices).c_str());
4476
Eric Laurent78fedbf2023-03-09 14:40:44 +01004477 if (!areAllDevicesSupported(
4478 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004479 return BAD_VALUE;
4480 }
4481 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4482 if (status != NO_ERROR) {
4483 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4484 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4485 return status;
4486 }
4487
4488 checkForDeviceAndOutputChanges();
4489
4490 bool forceVolumeReeval = false;
4491 // TODO(b/263479999): workaround for truncated touch sounds
4492 // to be removed when the problem is handled by system UI
4493 uint32_t delayMs = 0;
4494 if (strategy == mCommunnicationStrategy) {
4495 forceVolumeReeval = true;
4496 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4497 updateInputRouting();
4498 }
4499 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4500
4501 return NO_ERROR;
4502}
4503
4504status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4505 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004506{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004507 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004508
Paul Wang5d7cdb52022-11-22 09:45:06 +00004509 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004510 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004511 ALOGW_IF(status != NAME_NOT_FOUND,
4512 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004513 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004514 return status;
4515 }
4516
4517 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004518
4519 bool forceVolumeReeval = false;
4520 // FIXME: workaround for truncated touch sounds
4521 // to be removed when the problem is handled by system UI
4522 uint32_t delayMs = 0;
4523 if (strategy == mCommunnicationStrategy) {
4524 forceVolumeReeval = true;
4525 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4526 updateInputRouting();
4527 }
4528 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004529
4530 return NO_ERROR;
4531}
4532
jiabin0a488932020-08-07 17:32:40 -07004533status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4534 device_role_t role,
4535 AudioDeviceTypeAddrVector &devices) {
4536 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004537}
4538
Jiabin Huang3b98d322020-09-03 17:54:16 +00004539status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4540 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4541 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4542 dumpAudioDeviceTypeAddrVector(devices).c_str());
4543
Mikhail Naganov55773032020-10-01 15:08:13 -07004544 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004545 return BAD_VALUE;
4546 }
4547 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4548 ALOGW_IF(status != NO_ERROR,
4549 "Engine could not set preferred devices %s for audio source %d role %d",
4550 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4551
Wenyu Zhang47655d22024-10-01 12:24:53 +00004552 if (status == NO_ERROR) {
4553 updateInputRouting();
4554 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004555 return status;
4556}
4557
4558status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4559 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4560 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4561 dumpAudioDeviceTypeAddrVector(devices).c_str());
4562
Mikhail Naganov55773032020-10-01 15:08:13 -07004563 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004564 return BAD_VALUE;
4565 }
4566 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4567 ALOGW_IF(status != NO_ERROR,
4568 "Engine could not add preferred devices %s for audio source %d role %d",
4569 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4570
Eric Laurent2517af32020-11-25 15:31:27 +01004571 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004572 return status;
4573}
4574
4575status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4576 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4577{
4578 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4579 dumpAudioDeviceTypeAddrVector(devices).c_str());
4580
Eric Laurent78fedbf2023-03-09 14:40:44 +01004581 if (!areAllDevicesSupported(
4582 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004583 return BAD_VALUE;
4584 }
4585
4586 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4587 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004588 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004589 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004590 if (status == NO_ERROR) {
4591 updateInputRouting();
4592 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004593 return status;
4594}
4595
4596status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4597 device_role_t role) {
4598 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4599
4600 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004601 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004602 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004603 if (status == NO_ERROR) {
4604 updateInputRouting();
4605 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004606 return status;
4607}
4608
4609status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4610 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4611 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4612}
4613
Oscar Azucena90e77632019-11-27 17:12:28 -08004614status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004615 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004616 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004617 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4618 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004619 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004620 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4621 if (status != NO_ERROR) {
4622 ALOGE("%s() could not set device affinity for userId %d",
4623 __FUNCTION__, userId);
4624 return status;
4625 }
4626
4627 // reevaluate outputs for all devices
4628 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004629 changeOutputDevicesMuteState(devices);
4630 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4631 true /* skipDelays */);
4632 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004633
4634 return NO_ERROR;
4635}
4636
4637status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004638 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004639 AudioDeviceTypeAddrVector devices;
4640 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004641 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4642 if (status != NO_ERROR) {
4643 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4644 __FUNCTION__, userId);
4645 return status;
4646 }
4647
4648 // reevaluate outputs for all devices
4649 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004650 changeOutputDevicesMuteState(devices);
4651 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4652 true /* skipDelays */);
4653 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004654
4655 return NO_ERROR;
4656}
4657
Andy Hungc29d82b2018-10-05 12:23:17 -07004658void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004659{
Andy Hungc29d82b2018-10-05 12:23:17 -07004660 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004661 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004662 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004663 std::string stateLiteral;
4664 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004665 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004666 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4667 "communications", "media", "record", "dock", "system",
4668 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4669 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4670 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004671 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4672 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4673 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4674 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4675 dst->append(" (MANUAL: ");
4676 dumpManualSurroundFormats(dst);
4677 dst->append(")");
4678 }
4679 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004680 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004681 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4682 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004683 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004684 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004685
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004686 dst->append("\n");
4687 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4688 dst->append("\n");
4689 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004690 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004691 mOutputs.dump(dst);
4692 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004693 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004694 mAudioPatches.dump(dst);
4695 mPolicyMixes.dump(dst);
4696 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004697
Kevin Rocardb99cc752019-03-21 20:52:24 -07004698 dst->appendFormat(" AllowedCapturePolicies:\n");
4699 for (auto& policy : mAllowedCapturePolicies) {
4700 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4701 }
4702
jiabina84c3d32022-12-02 18:59:55 +00004703 dst->appendFormat(" Preferred mixer audio configuration:\n");
4704 for (const auto it : mPreferredMixerAttrInfos) {
4705 dst->appendFormat(" - device port id: %d\n", it.first);
4706 for (const auto preferredMixerInfoIt : it.second) {
4707 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4708 preferredMixerInfoIt.second->dump(dst);
4709 }
4710 }
4711
François Gaffiec005e562018-11-06 15:04:49 +01004712 dst->appendFormat("\nPolicy Engine dump:\n");
4713 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004714
4715 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4716 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4717 dst->appendFormat(" - device type: %s, driving stream %d\n",
4718 dumpDeviceTypes({it.first}).c_str(),
4719 mEngine->getVolumeGroupForAttributes(it.second));
4720 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004721}
4722
4723status_t AudioPolicyManager::dump(int fd)
4724{
4725 String8 result;
4726 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004727 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004728 return NO_ERROR;
4729}
4730
Kevin Rocardb99cc752019-03-21 20:52:24 -07004731status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4732{
4733 mAllowedCapturePolicies[uid] = capturePolicy;
4734 return NO_ERROR;
4735}
4736
Eric Laurente552edb2014-03-10 17:42:56 -07004737// This function checks for the parameters which can be offloaded.
4738// This can be enhanced depending on the capability of the DSP and policy
4739// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004740audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004741{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004742 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004743 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004744 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004745 offloadInfo.format,
4746 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4747 offloadInfo.has_video);
4748
jiabin2b9d5a12021-12-10 01:06:29 +00004749 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004750 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004751 }
4752
4753 // See if there is a profile to support this.
4754 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004755 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004756 offloadInfo.sample_rate,
4757 offloadInfo.format,
4758 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004759 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4760 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004761 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4762 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4763 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004764 if (profile == nullptr) {
4765 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4766 }
4767 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4768 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4769 }
4770 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004771}
4772
Michael Chana94fbb22018-04-24 14:31:19 +10004773bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4774 const audio_attributes_t& attributes) {
4775 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004776 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004777 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4778 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004779 config.sample_rate,
4780 config.format,
4781 config.channel_mask,
4782 output_flags,
4783 true /* directOnly */);
4784 ALOGV("%s() profile %sfound with name: %s, "
4785 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4786 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004787 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004788 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004789
4790 // also try the MSD module if compatible profile not found
4791 if (profile == nullptr) {
4792 profile = getMsdProfileForOutput(outputDevices,
4793 config.sample_rate,
4794 config.format,
4795 config.channel_mask,
4796 output_flags,
4797 true /* directOnly */);
4798 ALOGV("%s() MSD profile %sfound with name: %s, "
4799 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4800 __FUNCTION__, profile != 0 ? "" : "NOT ",
4801 (profile != 0 ? profile->getTagName().c_str() : "null"),
4802 config.sample_rate, config.format, config.channel_mask, output_flags);
4803 }
4804 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004805}
4806
jiabin2b9d5a12021-12-10 01:06:29 +00004807bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4808 bool durationIgnored) {
4809 if (mMasterMono) {
4810 return false; // no offloading if mono is set.
4811 }
4812
4813 // Check if offload has been disabled
4814 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4815 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4816 return false;
4817 }
4818
4819 // Check if stream type is music, then only allow offload as of now.
4820 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4821 {
4822 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4823 return false;
4824 }
4825
4826 //TODO: enable audio offloading with video when ready
4827 const bool allowOffloadWithVideo =
4828 property_get_bool("audio.offload.video", false /* default_value */);
4829 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4830 ALOGV("%s: has_video == true, returning false", __func__);
4831 return false;
4832 }
4833
4834 //If duration is less than minimum value defined in property, return false
4835 const int min_duration_secs = property_get_int32(
4836 "audio.offload.min.duration.secs", -1 /* default_value */);
4837 if (!durationIgnored) {
4838 if (min_duration_secs >= 0) {
4839 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4840 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4841 __func__, min_duration_secs);
4842 return false;
4843 }
4844 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4845 ALOGV("%s: Offload denied by duration < default min(=%u)",
4846 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4847 return false;
4848 }
4849 }
4850
4851 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4852 // creating an offloaded track and tearing it down immediately after start when audioflinger
4853 // detects there is an active non offloadable effect.
4854 // FIXME: We should check the audio session here but we do not have it in this context.
4855 // This may prevent offloading in rare situations where effects are left active by apps
4856 // in the background.
4857 if (mEffects.isNonOffloadableEffectEnabled()) {
4858 return false;
4859 }
4860
4861 return true;
4862}
4863
4864audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4865 const audio_config_t *config) {
4866 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4867 offloadInfo.format = config->format;
4868 offloadInfo.sample_rate = config->sample_rate;
4869 offloadInfo.channel_mask = config->channel_mask;
4870 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4871 offloadInfo.has_video = false;
4872 offloadInfo.is_streaming = false;
4873 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4874
4875 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4876 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4877 audio_flags_to_audio_output_flags(attr->flags, &flags);
4878 // only retain flags that will drive compressed offload or passthrough
4879 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4880 if (offloadPossible) {
4881 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4882 }
4883 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4884
Dorin Drimusfae3c642022-03-17 18:36:30 +01004885 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004886 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4887 [this, attr](sp<DeviceDescriptor> device) {
4888 return getPreferredMixerAttributesInfo(
4889 device->getId(),
4890 mEngine->getProductStrategyForAttributes(*attr),
4891 true /*activeBitPerfectPreferred*/) != nullptr;
4892 })) {
4893 // Bit-perfect playback is active on one of the selected devices, direct output will
4894 // be rejected at this instant.
4895 return AUDIO_DIRECT_NOT_SUPPORTED;
4896 }
jiabin2b9d5a12021-12-10 01:06:29 +00004897 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004898 DeviceVector outputDevices = engineOutputDevices;
4899 // the MSD module checks for different conditions and output devices
4900 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4901 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4902 continue;
4903 }
4904 outputDevices = getMsdAudioOutDevices();
4905 }
jiabin2b9d5a12021-12-10 01:06:29 +00004906 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004907 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004908 config->sample_rate, nullptr /*updatedSamplingRate*/,
4909 config->format, nullptr /*updatedFormat*/,
4910 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004911 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004912 continue;
4913 }
4914 // reject profiles not corresponding to a device currently available
4915 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4916 continue;
4917 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004918 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4919 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004920 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004921 != AUDIO_DIRECT_NOT_SUPPORTED) {
4922 // Already reports offload gapless supported. No need to report offload support.
4923 continue;
4924 }
4925 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4926 != AUDIO_OUTPUT_FLAG_NONE) {
4927 // If offload gapless is reported, no need to report offload support.
4928 directMode = (audio_direct_mode_t) ((directMode &
4929 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4930 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4931 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004932 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004933 }
4934 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004935 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004936 }
4937 }
4938 }
4939 return directMode;
4940}
4941
Dorin Drimusf2196d82022-01-03 12:11:18 +01004942status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4943 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004944 if (mEffects.isNonOffloadableEffectEnabled()) {
4945 return OK;
4946 }
jiabinf1c73972022-04-14 16:28:52 -07004947 DeviceVector devices;
4948 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004949 if (status != OK) {
4950 return status;
4951 }
4952 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4953 if (devices.empty()) {
4954 return OK; // no output devices for the attributes
4955 }
jiabinf1c73972022-04-14 16:28:52 -07004956 return getProfilesForDevices(devices, audioProfilesVector,
4957 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004958}
4959
jiabina84c3d32022-12-02 18:59:55 +00004960status_t AudioPolicyManager::getSupportedMixerAttributes(
4961 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4962 ALOGV("%s, portId=%d", __func__, portId);
4963 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4964 if (deviceDescriptor == nullptr) {
4965 ALOGE("%s the requested device is currently unavailable", __func__);
4966 return BAD_VALUE;
4967 }
jiabin96daffc2023-05-11 17:51:55 +00004968 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4969 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4970 deviceDescriptor->type());
4971 return BAD_VALUE;
4972 }
jiabina84c3d32022-12-02 18:59:55 +00004973 for (const auto& hwModule : mHwModules) {
4974 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4975 if (curProfile->supportsDevice(deviceDescriptor)) {
4976 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4977 }
4978 }
4979 }
4980 return NO_ERROR;
4981}
4982
4983status_t AudioPolicyManager::setPreferredMixerAttributes(
4984 const audio_attributes_t *attr,
4985 audio_port_handle_t portId,
4986 uid_t uid,
4987 const audio_mixer_attributes_t *mixerAttributes) {
4988 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4989 "mixerBehavior=%d}, uid=%d, portId=%u",
4990 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4991 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4992 mixerAttributes->mixer_behavior, uid, portId);
4993 if (attr->usage != AUDIO_USAGE_MEDIA) {
4994 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4995 return BAD_VALUE;
4996 }
4997 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4998 if (deviceDescriptor == nullptr) {
4999 ALOGE("%s the requested device is currently unavailable", __func__);
5000 return BAD_VALUE;
5001 }
5002 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5003 ALOGE("%s(%d), type=%d, is not a usb output device",
5004 __func__, portId, deviceDescriptor->type());
5005 return BAD_VALUE;
5006 }
5007
5008 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5009 audio_flags_to_audio_output_flags(attr->flags, &flags);
5010 flags = (audio_output_flags_t) (flags |
5011 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5012 sp<IOProfile> profile = nullptr;
5013 DeviceVector devices(deviceDescriptor);
5014 for (const auto& hwModule : mHwModules) {
5015 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5016 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005017 && curProfile->getCompatibilityScore(
5018 devices,
5019 mixerAttributes->config.sample_rate,
5020 nullptr /*updatedSamplingRate*/,
5021 mixerAttributes->config.format,
5022 nullptr /*updatedFormat*/,
5023 mixerAttributes->config.channel_mask,
5024 nullptr /*updatedChannelMask*/,
5025 flags,
5026 false /*exactMatchRequiredForInputFlags*/)
5027 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005028 profile = curProfile;
5029 break;
5030 }
5031 }
5032 }
5033 if (profile == nullptr) {
5034 ALOGE("%s, there is no compatible profile found", __func__);
5035 return BAD_VALUE;
5036 }
5037
5038 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5039 sp<PreferredMixerAttributesInfo>::make(
5040 uid, portId, profile, flags, *mixerAttributes);
5041 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5042 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5043
5044 // If 1) there is any client from the preferred mixer configuration owner that is currently
5045 // active and matches the strategy and 2) current output is on the preferred device and the
5046 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5047 // configuration.
5048 std::vector<audio_io_handle_t> outputsToReopen;
5049 for (size_t i = 0; i < mOutputs.size(); i++) {
5050 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005051 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5052 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005053 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005054 } else {
5055 for (const auto &client: output->getActiveClients()) {
5056 if (client->uid() == uid && client->strategy() == strategy) {
5057 client->setIsInvalid();
5058 outputsToReopen.push_back(output->mIoHandle);
5059 }
jiabina84c3d32022-12-02 18:59:55 +00005060 }
5061 }
5062 }
5063 }
5064 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5065 config.sample_rate = mixerAttributes->config.sample_rate;
5066 config.channel_mask = mixerAttributes->config.channel_mask;
5067 config.format = mixerAttributes->config.format;
5068 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005069 sp<SwAudioOutputDescriptor> desc =
5070 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5071 if (desc == nullptr) {
5072 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5073 continue;
5074 }
jiabin220eea12024-05-17 17:55:20 +00005075 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005076 }
5077
5078 return NO_ERROR;
5079}
5080
5081sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005082 audio_port_handle_t devicePortId,
5083 product_strategy_t strategy,
5084 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005085 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5086 if (it == mPreferredMixerAttrInfos.end()) {
5087 return nullptr;
5088 }
jiabind9a58d32023-06-01 17:57:30 +00005089 if (activeBitPerfectPreferred) {
5090 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005091 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005092 return info;
5093 }
5094 }
jiabina84c3d32022-12-02 18:59:55 +00005095 }
jiabind9a58d32023-06-01 17:57:30 +00005096 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5097 return strategyMatchedMixerAttrInfoIt == it->second.end()
5098 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005099}
5100
5101status_t AudioPolicyManager::getPreferredMixerAttributes(
5102 const audio_attributes_t *attr,
5103 audio_port_handle_t portId,
5104 audio_mixer_attributes_t* mixerAttributes) {
5105 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5106 portId, mEngine->getProductStrategyForAttributes(*attr));
5107 if (info == nullptr) {
5108 return NAME_NOT_FOUND;
5109 }
5110 *mixerAttributes = info->getMixerAttributes();
5111 return NO_ERROR;
5112}
5113
5114status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5115 audio_port_handle_t portId,
5116 uid_t uid) {
5117 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5118 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5119 if (preferredMixerAttrInfo == nullptr) {
5120 return NAME_NOT_FOUND;
5121 }
5122 if (preferredMixerAttrInfo->getUid() != uid) {
5123 ALOGE("%s, requested uid=%d, owned uid=%d",
5124 __func__, uid, preferredMixerAttrInfo->getUid());
5125 return PERMISSION_DENIED;
5126 }
5127 mPreferredMixerAttrInfos[portId].erase(strategy);
5128 if (mPreferredMixerAttrInfos[portId].empty()) {
5129 mPreferredMixerAttrInfos.erase(portId);
5130 }
5131
5132 // Reconfig existing output
5133 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5134 for (size_t i = 0; i < mOutputs.size(); i++) {
5135 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5136 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5137 }
5138 }
5139 for (const auto output : potentialOutputsToReopen) {
5140 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5141 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5142 preferredMixerAttrInfo->getFlags())) {
5143 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5144 }
5145 }
5146 return NO_ERROR;
5147}
5148
Eric Laurent6a94d692014-05-20 11:18:06 -07005149status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5150 audio_port_type_t type,
5151 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005152 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005153 unsigned int *generation)
5154{
jiabin19cdba52020-11-24 11:28:58 -08005155 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5156 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005157 return BAD_VALUE;
5158 }
5159 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005160 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005161 *num_ports = 0;
5162 }
5163
5164 size_t portsWritten = 0;
5165 size_t portsMax = *num_ports;
5166 *num_ports = 0;
5167 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005168 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5169 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005171 for (const auto& dev : mAvailableOutputDevices) {
5172 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005173 continue;
5174 }
5175 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005176 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005177 }
5178 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 }
5181 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005182 for (const auto& dev : mAvailableInputDevices) {
5183 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005184 continue;
5185 }
5186 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005187 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005188 }
5189 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 }
5192 }
5193 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5194 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5195 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5196 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5197 }
5198 *num_ports += mInputs.size();
5199 }
5200 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005201 size_t numOutputs = 0;
5202 for (size_t i = 0; i < mOutputs.size(); i++) {
5203 if (!mOutputs[i]->isDuplicated()) {
5204 numOutputs++;
5205 if (portsWritten < portsMax) {
5206 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5207 }
5208 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 }
Eric Laurent84c70242014-06-23 08:46:27 -07005210 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 }
5212 }
jiabina84c3d32022-12-02 18:59:55 +00005213
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005215 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 return NO_ERROR;
5217}
5218
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005219status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5220 std::vector<media::AudioPortFw>* _aidl_return) {
5221 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5222 audio_port_v7 port;
5223 dev->toAudioPort(&port);
5224 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5225 _aidl_return->push_back(std::move(aidlPort));
5226 return OK;
5227 };
5228
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005229 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005230 for (const auto& dev : module->getDeclaredDevices()) {
5231 if (role == media::AudioPortRole::NONE ||
5232 ((role == media::AudioPortRole::SOURCE)
5233 == audio_is_input_device(dev->type()))) {
5234 RETURN_STATUS_IF_ERROR(pushPort(dev));
5235 }
5236 }
5237 }
5238 return OK;
5239}
5240
jiabin19cdba52020-11-24 11:28:58 -08005241status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005242{
Eric Laurent99fcae42018-05-17 16:59:18 -07005243 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5244 return BAD_VALUE;
5245 }
5246 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5247 if (dev != 0) {
5248 dev->toAudioPort(port);
5249 return NO_ERROR;
5250 }
5251 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5252 if (dev != 0) {
5253 dev->toAudioPort(port);
5254 return NO_ERROR;
5255 }
5256 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5257 if (out != 0) {
5258 out->toAudioPort(port);
5259 return NO_ERROR;
5260 }
5261 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5262 if (in != 0) {
5263 in->toAudioPort(port);
5264 return NO_ERROR;
5265 }
5266 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005267}
5268
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005269status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5270 audio_patch_handle_t *handle,
5271 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005272{
François Gaffieafd4cea2019-11-18 15:50:22 +01005273 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 if (handle == NULL || patch == NULL) {
5275 return BAD_VALUE;
5276 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005277 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005278 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005279 return BAD_VALUE;
5280 }
5281 // only one source per audio patch supported for now
5282 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 return INVALID_OPERATION;
5284 }
Eric Laurent874c42872014-08-08 15:13:39 -07005285 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 return INVALID_OPERATION;
5287 }
Eric Laurent874c42872014-08-08 15:13:39 -07005288 for (size_t i = 0; i < patch->num_sinks; i++) {
5289 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5290 return INVALID_OPERATION;
5291 }
5292 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005293
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005294 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5295 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5296 if (srcDevice == nullptr || sinkDevice == nullptr) {
5297 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5298 return BAD_VALUE;
5299 }
5300 ALOGV("%s between source %s and sink %s", __func__,
5301 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5302 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5303 // Default attributes, default volume priority, not to infer with non raw audio patches.
5304 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5305 const struct audio_port_config *source = &patch->sources[0];
5306 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005307 new SourceClientDescriptor(
5308 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5309 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005310 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005311 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005312
5313 status_t status =
5314 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5315
5316 if (status != NO_ERROR) {
5317 return INVALID_OPERATION;
5318 }
5319 mAudioSources.add(portId, sourceDesc);
5320 return NO_ERROR;
5321}
5322
5323status_t AudioPolicyManager::connectAudioSourceToSink(
5324 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5325 const struct audio_patch *patch,
5326 audio_patch_handle_t &handle,
5327 uid_t uid, uint32_t delayMs)
5328{
5329 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5330 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5331 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5332 return INVALID_OPERATION;
5333 }
5334 sourceDesc->connect(handle, sinkDevice);
5335 if (isMsdPatch(handle)) {
5336 return NO_ERROR;
5337 }
5338 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5339 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5340 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5341 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5342 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5343 goto FailurePatchAdded;
5344 }
5345 status = swOutput->start();
5346 if (status != NO_ERROR) {
5347 goto FailureSourceAdded;
5348 }
5349 swOutput->addClient(sourceDesc);
5350 status = startSource(swOutput, sourceDesc, &delayMs);
5351 if (status != NO_ERROR) {
5352 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5353 goto FailureSourceActive;
5354 }
5355 if (delayMs != 0) {
5356 usleep(delayMs * 1000);
5357 }
5358 return NO_ERROR;
5359
5360FailureSourceActive:
5361 swOutput->stop();
5362 releaseOutput(sourceDesc->portId());
5363FailureSourceAdded:
5364 sourceDesc->setSwOutput(nullptr);
5365FailurePatchAdded:
5366 releaseAudioPatchInternal(handle);
5367 return INVALID_OPERATION;
5368}
5369
5370status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5371 audio_patch_handle_t *handle,
5372 uid_t uid, uint32_t delayMs,
5373 const sp<SourceClientDescriptor>& sourceDesc)
5374{
5375 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 sp<AudioPatch> patchDesc;
5377 ssize_t index = mAudioPatches.indexOfKey(*handle);
5378
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5380 patch->sources[0].role,
5381 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005382#if LOG_NDEBUG == 0
5383 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005384 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5385 patch->sinks[i].role,
5386 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005387 }
5388#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005389
5390 if (index >= 0) {
5391 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005392 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5393 __func__, mUidCached, patchDesc->getUid(), uid);
5394 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 return INVALID_OPERATION;
5396 }
5397 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005398 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005399 }
5400
5401 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005402 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005403 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005404 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 return BAD_VALUE;
5406 }
Eric Laurent84c70242014-06-23 08:46:27 -07005407 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5408 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005409 if (patchDesc != 0) {
5410 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005411 ALOGV("%s source id differs for patch current id %d new id %d",
5412 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 return BAD_VALUE;
5414 }
5415 }
Eric Laurent874c42872014-08-08 15:13:39 -07005416 DeviceVector devices;
5417 for (size_t i = 0; i < patch->num_sinks; i++) {
5418 // Only support mix to devices connection
5419 // TODO add support for mix to mix connection
5420 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005421 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005422 return INVALID_OPERATION;
5423 }
5424 sp<DeviceDescriptor> devDesc =
5425 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5426 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005427 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005428 return BAD_VALUE;
5429 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005430
jiabin66acc432024-02-06 00:57:36 +00005431 if (outputDesc->mProfile->getCompatibilityScore(
5432 DeviceVector(devDesc),
5433 patch->sources[0].sample_rate,
5434 nullptr, // updatedSamplingRate
5435 patch->sources[0].format,
5436 nullptr, // updatedFormat
5437 patch->sources[0].channel_mask,
5438 nullptr, // updatedChannelMask
5439 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005440 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005441 return INVALID_OPERATION;
5442 }
5443 devices.add(devDesc);
5444 }
5445 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 return INVALID_OPERATION;
5447 }
Eric Laurent874c42872014-08-08 15:13:39 -07005448
Eric Laurent6a94d692014-05-20 11:18:06 -07005449 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005450 ALOGV("%s setting device %s on output %d",
5451 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305452 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005453 index = mAudioPatches.indexOfKey(*handle);
5454 if (index >= 0) {
5455 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005456 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 }
5458 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005459 patchDesc->setUid(uid);
5460 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 return INVALID_OPERATION;
5464 }
5465 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5466 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5467 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005468 // only one sink supported when connecting an input device to a mix
5469 if (patch->num_sinks > 1) {
5470 return INVALID_OPERATION;
5471 }
François Gaffie53615e22015-03-19 09:24:12 +01005472 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005473 if (inputDesc == NULL) {
5474 return BAD_VALUE;
5475 }
5476 if (patchDesc != 0) {
5477 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5478 return BAD_VALUE;
5479 }
5480 }
François Gaffie11d30102018-11-02 16:09:09 +01005481 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005482 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005483 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005484 return BAD_VALUE;
5485 }
5486
jiabin66acc432024-02-06 00:57:36 +00005487 if (inputDesc->mProfile->getCompatibilityScore(
5488 DeviceVector(device),
5489 patch->sinks[0].sample_rate,
5490 nullptr, /*updatedSampleRate*/
5491 patch->sinks[0].format,
5492 nullptr, /*updatedFormat*/
5493 patch->sinks[0].channel_mask,
5494 nullptr, /*updatedChannelMask*/
5495 // FIXME for the parameter type,
5496 // and the NONE
5497 (audio_output_flags_t)
5498 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005499 return INVALID_OPERATION;
5500 }
5501 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005502 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005503 device->toString().c_str(), inputDesc->mIoHandle);
5504 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005505 index = mAudioPatches.indexOfKey(*handle);
5506 if (index >= 0) {
5507 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005508 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005509 }
5510 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005511 patchDesc->setUid(uid);
5512 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005513 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005514 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 return INVALID_OPERATION;
5516 }
5517 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5518 // device to device connection
5519 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005520 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005521 return BAD_VALUE;
5522 }
5523 }
François Gaffie11d30102018-11-02 16:09:09 +01005524 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005526 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005527 return BAD_VALUE;
5528 }
Eric Laurent874c42872014-08-08 15:13:39 -07005529
Eric Laurent6a94d692014-05-20 11:18:06 -07005530 //update source and sink with our own data as the data passed in the patch may
5531 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005532 PatchBuilder patchBuilder;
5533 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005534
5535 // if first sink is to MSD, establish single MSD patch
5536 if (getMsdAudioOutDevices().contains(
5537 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5538 ALOGV("%s patching to MSD", __FUNCTION__);
5539 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5540 goto installPatch;
5541 }
5542
François Gaffieafd4cea2019-11-18 15:50:22 +01005543 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5544 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005545
Eric Laurent874c42872014-08-08 15:13:39 -07005546 for (size_t i = 0; i < patch->num_sinks; i++) {
5547 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005548 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005549 return INVALID_OPERATION;
5550 }
François Gaffie11d30102018-11-02 16:09:09 +01005551 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005552 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005553 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005554 return BAD_VALUE;
5555 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005556 audio_port_config sinkPortConfig = {};
5557 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5558 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005559
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005560 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5561 // volume management purpose (tracking activity)
5562 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5563 // in config XML to reach the sink so that is can be declared as available.
5564 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005565 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005566 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005567 // take care of dynamic routing for SwOutput selection,
5568 audio_attributes_t attributes = sourceDesc->attributes();
5569 audio_stream_type_t stream = sourceDesc->stream();
5570 audio_attributes_t resultAttr;
5571 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5572 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005573 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5574 config.channel_mask =
5575 (audio_channel_mask_get_representation(sourceMask)
5576 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5577 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005578 config.format = sourceDesc->config().format;
5579 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5580 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5581 bool isRequestedDeviceForExclusiveUse = false;
5582 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005583 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005584 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005585 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5586 &stream, sourceDesc->uid(), &config, &flags,
5587 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005588 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005589 if (output == AUDIO_IO_HANDLE_NONE) {
5590 ALOGV("%s no output for device %s",
5591 __FUNCTION__, sinkDevice->toString().c_str());
5592 return INVALID_OPERATION;
5593 }
5594 outputDesc = mOutputs.valueFor(output);
5595 if (outputDesc->isDuplicated()) {
5596 ALOGE("%s output is duplicated", __func__);
5597 return INVALID_OPERATION;
5598 }
François Gaffie7e39df22022-04-26 12:48:49 +02005599 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5600 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005601 } else {
5602 // Same for "raw patches" aka created from createAudioPatch API
5603 SortedVector<audio_io_handle_t> outputs =
5604 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5605 // if the sink device is reachable via an opened output stream, request to
5606 // go via this output stream by adding a second source to the patch
5607 // description
5608 output = selectOutput(outputs);
5609 if (output == AUDIO_IO_HANDLE_NONE) {
5610 ALOGE("%s no output available for internal patch sink", __func__);
5611 return INVALID_OPERATION;
5612 }
5613 outputDesc = mOutputs.valueFor(output);
5614 if (outputDesc->isDuplicated()) {
5615 ALOGV("%s output for device %s is duplicated",
5616 __func__, sinkDevice->toString().c_str());
5617 return INVALID_OPERATION;
5618 }
François Gaffie7e39df22022-04-26 12:48:49 +02005619 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005620 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005621 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005622 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005623 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005624 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005625 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5626 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005627 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5628 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005629 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005630 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005631 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005632 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005633 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005634 return INVALID_OPERATION;
5635 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005636 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005637 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005638 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005639 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005640 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005641 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005642 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005643 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5644 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005645 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005646 }
Eric Laurent83b88082014-06-20 18:31:16 -07005647 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005648 }
5649 // TODO: check from routing capabilities in config file and other conflicting patches
5650
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005651installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005652 status_t status = installPatch(
5653 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005654 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005655 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005656 return INVALID_OPERATION;
5657 }
5658 } else {
5659 return BAD_VALUE;
5660 }
5661 } else {
5662 return BAD_VALUE;
5663 }
5664 return NO_ERROR;
5665}
5666
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005667status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005668{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005669 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005670 ssize_t index = mAudioPatches.indexOfKey(handle);
5671
5672 if (index < 0) {
5673 return BAD_VALUE;
5674 }
5675 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005676 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5677 __func__, mUidCached, patchDesc->getUid(), uid);
5678 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005679 return INVALID_OPERATION;
5680 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005681 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5682 for (size_t i = 0; i < mAudioSources.size(); i++) {
5683 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5684 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5685 portId = sourceDesc->portId();
5686 break;
5687 }
5688 }
5689 return portId != AUDIO_PORT_HANDLE_NONE ?
5690 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005691}
Eric Laurent6a94d692014-05-20 11:18:06 -07005692
François Gaffieafd4cea2019-11-18 15:50:22 +01005693status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005694 uint32_t delayMs,
5695 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005696{
5697 ALOGV("%s patch %d", __func__, handle);
5698 if (mAudioPatches.indexOfKey(handle) < 0) {
5699 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5700 return BAD_VALUE;
5701 }
5702 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005703 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005704 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005705 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005706 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005707 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005708 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005709 return BAD_VALUE;
5710 }
5711
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305712 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005713 getNewOutputDevices(outputDesc, true /*fromCache*/),
5714 true,
5715 0,
5716 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005717 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5718 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005719 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005720 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005721 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005722 return BAD_VALUE;
5723 }
5724 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005725 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005726 true,
5727 NULL);
5728 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005729 status_t status =
5730 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5731 ALOGV("%s patch panel returned %d patchHandle %d",
5732 __func__, status, patchDesc->getAfHandle());
5733 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005734 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005735 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005736 // SW or HW Bridge
5737 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5738 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005739 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005740 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5741 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5742 outputDesc = sourceDesc->swOutput().promote();
5743 }
5744 if (outputDesc == nullptr) {
5745 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5746 // releaseOutput has already called closeOutput in case of direct output
5747 return NO_ERROR;
5748 }
François Gaffie7e39df22022-04-26 12:48:49 +02005749 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005750 // While using a HwBridge, force reconsidering device only if not reusing an existing
5751 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005752 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005753 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5754 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5755 // Reconsider device only for cases:
5756 // 1 / Active Output
5757 // 2 / Inactive Output previously hosting HwBridge
5758 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5759 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5760 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305761 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005762 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5763 outputDesc->devices(),
5764 force,
5765 0,
5766 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005767 } else {
5768 return BAD_VALUE;
5769 }
5770 } else {
5771 return BAD_VALUE;
5772 }
5773 return NO_ERROR;
5774}
5775
5776status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5777 struct audio_patch *patches,
5778 unsigned int *generation)
5779{
François Gaffie53615e22015-03-19 09:24:12 +01005780 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005781 return BAD_VALUE;
5782 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005783 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005784 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005785}
5786
Eric Laurente1715a42014-05-20 11:30:42 -07005787status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005788{
Eric Laurente1715a42014-05-20 11:30:42 -07005789 ALOGV("setAudioPortConfig()");
5790
5791 if (config == NULL) {
5792 return BAD_VALUE;
5793 }
5794 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5795 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005796 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5797 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005798 }
5799
Eric Laurenta121f902014-06-03 13:32:54 -07005800 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005801 if (config->type == AUDIO_PORT_TYPE_MIX) {
5802 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005803 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005804 if (outputDesc == NULL) {
5805 return BAD_VALUE;
5806 }
Eric Laurent84c70242014-06-23 08:46:27 -07005807 ALOG_ASSERT(!outputDesc->isDuplicated(),
5808 "setAudioPortConfig() called on duplicated output %d",
5809 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005810 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005811 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005812 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005813 if (inputDesc == NULL) {
5814 return BAD_VALUE;
5815 }
Eric Laurenta121f902014-06-03 13:32:54 -07005816 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005817 } else {
5818 return BAD_VALUE;
5819 }
5820 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5821 sp<DeviceDescriptor> deviceDesc;
5822 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5823 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5824 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5825 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5826 } else {
5827 return BAD_VALUE;
5828 }
5829 if (deviceDesc == NULL) {
5830 return BAD_VALUE;
5831 }
Eric Laurenta121f902014-06-03 13:32:54 -07005832 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005833 } else {
5834 return BAD_VALUE;
5835 }
5836
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005837 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005838 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5839 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005840 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005841 audioPortConfig->toAudioPortConfig(&newConfig, config);
5842 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005843 }
Eric Laurenta121f902014-06-03 13:32:54 -07005844 if (status != NO_ERROR) {
5845 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005846 }
Eric Laurente1715a42014-05-20 11:30:42 -07005847
5848 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005849}
5850
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005851void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5852{
Eric Laurentd60560a2015-04-10 11:31:20 -07005853 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005854 clearAudioPatches(uid);
5855 clearSessionRoutes(uid);
5856}
5857
Eric Laurent6a94d692014-05-20 11:18:06 -07005858void AudioPolicyManager::clearAudioPatches(uid_t uid)
5859{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005860 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005861 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005862 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005863 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005864 }
5865 }
5866}
5867
François Gaffiec005e562018-11-06 15:04:49 +01005868void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005869{
François Gaffiec005e562018-11-06 15:04:49 +01005870 // Take the first attributes following the product strategy as it is used to retrieve the routed
5871 // device. All attributes wihin a strategy follows the same "routing strategy"
5872 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5873 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005874 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005875 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005876 for (size_t j = 0; j < mOutputs.size(); j++) {
5877 if (mOutputs.keyAt(j) == ouptutToSkip) {
5878 continue;
5879 }
5880 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005881 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005882 continue;
5883 }
5884 // If the default device for this strategy is on another output mix,
5885 // invalidate all tracks in this strategy to force re connection.
5886 // Otherwise select new device on the output mix.
5887 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005888 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005889 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005890 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005891 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005892 // If the device is using preferred mixer attributes, the output need to reopen
5893 // with default configuration when the new selected devices are different from
5894 // current routing devices.
5895 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5896 continue;
5897 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305898 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005899 }
5900 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005901 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005902}
5903
5904void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5905{
5906 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005907 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005908 for (size_t i = 0; i < mOutputs.size(); i++) {
5909 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005910 for (const auto& client : outputDesc->getClientIterable()) {
5911 if (client->hasPreferredDevice() && client->uid() == uid) {
5912 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005913 auto clientStrategy = client->strategy();
5914 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5915 end(affectedStrategies)) {
5916 continue;
5917 }
5918 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005919 }
5920 }
5921 }
5922 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005923 for (const auto& strategy : affectedStrategies) {
5924 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005925 }
5926
5927 // remove input routes associated with this uid
5928 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005929 for (size_t i = 0; i < mInputs.size(); i++) {
5930 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005931 for (const auto& client : inputDesc->getClientIterable()) {
5932 if (client->hasPreferredDevice() && client->uid() == uid) {
5933 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5934 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005935 }
5936 }
5937 }
5938 // reroute inputs if necessary
5939 SortedVector<audio_io_handle_t> inputsToClose;
5940 for (size_t i = 0; i < mInputs.size(); i++) {
5941 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005942 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005943 inputsToClose.add(inputDesc->mIoHandle);
5944 }
5945 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005946 for (const auto& input : inputsToClose) {
5947 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005948 }
5949}
5950
Eric Laurentd60560a2015-04-10 11:31:20 -07005951void AudioPolicyManager::clearAudioSources(uid_t uid)
5952{
5953 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005954 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5955 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005956 stopAudioSource(mAudioSources.keyAt(i));
5957 }
5958 }
5959}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005960
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005961status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5962 audio_io_handle_t *ioHandle,
5963 audio_devices_t *device)
5964{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005965 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5966 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005967 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005968 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5969 if (deviceDesc == nullptr) {
5970 return INVALID_OPERATION;
5971 }
5972 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005973
François Gaffiedf372692015-03-19 10:43:27 +01005974 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005975}
5976
Eric Laurentd60560a2015-04-10 11:31:20 -07005977status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005978 const audio_attributes_t *attributes,
5979 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005980 uid_t uid) {
5981 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005982 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005983}
5984
5985status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5986 const audio_attributes_t *attributes,
5987 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005988 uid_t uid, bool internal, bool isCallRx,
5989 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005990{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005991 ALOGV("%s", __FUNCTION__);
5992 *portId = AUDIO_PORT_HANDLE_NONE;
5993
5994 if (source == NULL || attributes == NULL || portId == NULL) {
5995 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5996 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005997 return BAD_VALUE;
5998 }
5999
Eric Laurentd60560a2015-04-10 11:31:20 -07006000 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6001 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006002 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6003 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006004 return INVALID_OPERATION;
6005 }
6006
François Gaffie11d30102018-11-02 16:09:09 +01006007 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006008 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006009 String8(source->ext.device.address),
6010 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006011 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006012 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006013 return BAD_VALUE;
6014 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006015
jiabin4ef93452019-09-10 14:29:54 -07006016 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006017
François Gaffieaaac0fd2018-11-22 17:56:39 +01006018 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006019 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006020 mEngine->getStreamTypeForAttributes(*attributes),
6021 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006022 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006023
David Lif85c5e32024-07-01 13:14:10 +00006024 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006025 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006026 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006027 }
6028 return status;
6029}
6030
David Lif85c5e32024-07-01 13:14:10 +00006031status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6032 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006033{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006034 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006035
6036 // make sure we only have one patch per source.
6037 disconnectAudioSource(sourceDesc);
6038
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006039 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006040 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6041 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6042 sourceDesc->srcDevice()->type(),
6043 String8(sourceDesc->srcDevice()->address().c_str()),
6044 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006045 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006046 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006047 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006048 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006049 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6050 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6051 return INVALID_OPERATION;
6052 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006053 PatchBuilder patchBuilder;
6054 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6055 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006056
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006057 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006058 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006059}
6060
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006061status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006062{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006063 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6064 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006065 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006066 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006067 return BAD_VALUE;
6068 }
6069 status_t status = disconnectAudioSource(sourceDesc);
6070
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006071 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006072 return status;
6073}
6074
Andy Hung2ddee192015-12-18 17:34:44 -08006075status_t AudioPolicyManager::setMasterMono(bool mono)
6076{
6077 if (mMasterMono == mono) {
6078 return NO_ERROR;
6079 }
6080 mMasterMono = mono;
6081 // if enabling mono we close all offloaded devices, which will invalidate the
6082 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6083 // for recreating the new AudioTrack as non-offloaded PCM.
6084 //
6085 // If disabling mono, we leave all tracks as is: we don't know which clients
6086 // and tracks are able to be recreated as offloaded. The next "song" should
6087 // play back offloaded.
6088 if (mMasterMono) {
6089 Vector<audio_io_handle_t> offloaded;
6090 for (size_t i = 0; i < mOutputs.size(); ++i) {
6091 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6092 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6093 offloaded.push(desc->mIoHandle);
6094 }
6095 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006096 for (const auto& handle : offloaded) {
6097 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006098 }
6099 }
6100 // update master mono for all remaining outputs
6101 for (size_t i = 0; i < mOutputs.size(); ++i) {
6102 updateMono(mOutputs.keyAt(i));
6103 }
6104 return NO_ERROR;
6105}
6106
6107status_t AudioPolicyManager::getMasterMono(bool *mono)
6108{
6109 *mono = mMasterMono;
6110 return NO_ERROR;
6111}
6112
Eric Laurentac9cef52017-06-09 15:46:26 -07006113float AudioPolicyManager::getStreamVolumeDB(
6114 audio_stream_type_t stream, int index, audio_devices_t device)
6115{
Vlad Popa9d482762024-06-21 16:40:23 -07006116 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6117 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006118}
6119
jiabin81772902018-04-02 17:52:27 -07006120status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6121 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006122 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006123{
Kriti Dang6537def2021-03-02 13:46:59 +01006124 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6125 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006126 return BAD_VALUE;
6127 }
Kriti Dang6537def2021-03-02 13:46:59 +01006128 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6129 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006130
6131 size_t formatsWritten = 0;
6132 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006133
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006134 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006135 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6136 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006137 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006138 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006139 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006140 bool formatEnabled = true;
6141 switch (forceUse) {
6142 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006143 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006144 break;
6145 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6146 formatEnabled = false;
6147 break;
6148 default: // AUTO or ALWAYS => true
6149 break;
jiabin81772902018-04-02 17:52:27 -07006150 }
6151 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6152 }
jiabin81772902018-04-02 17:52:27 -07006153 }
6154 return NO_ERROR;
6155}
6156
Kriti Dang6537def2021-03-02 13:46:59 +01006157status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6158 audio_format_t *surroundFormats) {
6159 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6160 return BAD_VALUE;
6161 }
6162 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6163 __func__, *numSurroundFormats, surroundFormats);
6164
6165 size_t formatsWritten = 0;
6166 size_t formatsMax = *numSurroundFormats;
6167 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6168
6169 // Return formats from all device profiles that have already been resolved by
6170 // checkOutputsForDevice().
6171 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6172 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6173 audio_devices_t deviceType = device->type();
6174 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6175 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006176 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6177 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006178 continue;
6179 }
6180 // Formats reported by sink devices
6181 std::unordered_set<audio_format_t> formatset;
6182 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6183 formatset.insert(it->second.begin(), it->second.end());
6184 }
6185
6186 // Formats hard-coded in the in policy configuration file (if any).
6187 FormatVector encodedFormats = device->encodedFormats();
6188 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6189 // Filter the formats which are supported by the vendor hardware.
6190 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006191 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006192 formats.insert(*it);
6193 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006194 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006195 if (pair.second.count(*it) != 0) {
6196 formats.insert(pair.first);
6197 break;
6198 }
6199 }
6200 }
6201 }
6202 }
6203 *numSurroundFormats = formats.size();
6204 for (const auto& format: formats) {
6205 if (formatsWritten < formatsMax) {
6206 surroundFormats[formatsWritten++] = format;
6207 }
6208 }
6209 return NO_ERROR;
6210}
6211
jiabin81772902018-04-02 17:52:27 -07006212status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6213{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006214 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006215 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6216 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006217 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006218 return BAD_VALUE;
6219 }
6220
Mikhail Naganov100f0122018-11-29 11:22:16 -08006221 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6222 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006223 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006224 return INVALID_OPERATION;
6225 }
6226
Mikhail Naganov100f0122018-11-29 11:22:16 -08006227 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006228 return NO_ERROR;
6229 }
6230
Mikhail Naganov100f0122018-11-29 11:22:16 -08006231 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006232 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006233 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006234 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006235 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006236 }
6237 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006238 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006239 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006240 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006241 }
6242 }
6243
6244 sp<SwAudioOutputDescriptor> outputDesc;
6245 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006246 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6247 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006248 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6249 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006250 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006251 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006252 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006253 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6254 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006255 name.c_str(),
6256 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006257 if (status != NO_ERROR) {
6258 continue;
6259 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006260 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006261 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6262 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006263 name.c_str(),
6264 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006265 profileUpdated |= (status == NO_ERROR);
6266 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006267 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006268 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006269 AUDIO_DEVICE_IN_HDMI);
6270 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6271 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006272 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006273 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006274 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6275 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6276 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006277 name.c_str(),
6278 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006279 if (status != NO_ERROR) {
6280 continue;
6281 }
6282 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6283 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6284 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006285 name.c_str(),
6286 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006287 profileUpdated |= (status == NO_ERROR);
6288 }
6289
jiabin81772902018-04-02 17:52:27 -07006290 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006291 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006292 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006293 }
6294
6295 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6296}
6297
Eric Laurent5ada82e2019-08-29 17:53:54 -07006298void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006299{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006300 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006301 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006302 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006303 }
6304}
6305
jiabin6012f912018-11-02 17:06:30 -07006306bool AudioPolicyManager::isHapticPlaybackSupported()
6307{
6308 for (const auto& hwModule : mHwModules) {
6309 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6310 for (const auto &outProfile : outputProfiles) {
6311 struct audio_port audioPort;
6312 outProfile->toAudioPort(&audioPort);
6313 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6314 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6315 return true;
6316 }
6317 }
6318 }
6319 }
6320 return false;
6321}
6322
Carter Hsu325a8eb2022-01-19 19:56:51 +08006323bool AudioPolicyManager::isUltrasoundSupported()
6324{
6325 bool hasUltrasoundOutput = false;
6326 bool hasUltrasoundInput = false;
6327 for (const auto& hwModule : mHwModules) {
6328 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6329 if (!hasUltrasoundOutput) {
6330 for (const auto &outProfile : outputProfiles) {
6331 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6332 hasUltrasoundOutput = true;
6333 break;
6334 }
6335 }
6336 }
6337
6338 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6339 if (!hasUltrasoundInput) {
6340 for (const auto &inputProfile : inputProfiles) {
6341 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6342 hasUltrasoundInput = true;
6343 break;
6344 }
6345 }
6346 }
6347
6348 if (hasUltrasoundOutput && hasUltrasoundInput)
6349 return true;
6350 }
6351 return false;
6352}
6353
Atneya Nair698f5ef2022-12-15 16:15:09 -08006354bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6355{
6356 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6357 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6358 for (const auto& hwModule : mHwModules) {
6359 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6360 for (const auto &inputProfile : inputProfiles) {
6361 if ((inputProfile->getFlags() & mask) == mask) {
6362 return true;
6363 }
6364 }
6365 }
6366 return false;
6367}
6368
Eric Laurent8340e672019-11-06 11:01:08 -08006369bool AudioPolicyManager::isCallScreenModeSupported()
6370{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006371 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006372}
6373
6374
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006375status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006376{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006377 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006378 if (!sourceDesc->isConnected()) {
6379 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6380 return NO_ERROR;
6381 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006382 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6383 if (swOutput != 0) {
6384 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006385 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006386 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006387 }
jiabinbce0c1d2020-10-05 11:20:18 -07006388 if (releaseOutput(sourceDesc->portId())) {
6389 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6390 // no need to release audio patch here but just return NO_ERROR.
6391 return NO_ERROR;
6392 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006393 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006394 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006395 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006396 // close Hwoutput and remove from mHwOutputs
6397 } else {
6398 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6399 }
6400 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006401 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006402 sourceDesc->disconnect();
6403 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006404}
6405
François Gaffiec005e562018-11-06 15:04:49 +01006406sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6407 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006408{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006409 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006410 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006411 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006412 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006413 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6414 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006415 source = sourceDesc;
6416 break;
6417 }
6418 }
6419 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006420}
6421
Eric Laurentb4f42a92022-01-17 17:37:31 +01006422bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006423 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006424 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006425{
6426 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6427 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006428 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006429 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006430 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6431 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6432 return false;
6433 }
6434 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6435 return false;
6436 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006437 }
6438
Eric Laurentd332bc82023-08-04 11:45:23 +02006439 // The caller can have the audio config criteria ignored by either passing a null ptr or
6440 // the AUDIO_CONFIG_INITIALIZER value.
6441 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006442 // some positional channel masks and PCM format and for stereo if low latency performance
6443 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006444
6445 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006446 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006447 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6448 ? audio_channel_mask_contains_stereo(config->channel_mask)
6449 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006450 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006451 return false;
6452 }
6453 if (!audio_is_linear_pcm(config->format)) {
6454 return false;
6455 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006456 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6457 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6458 return false;
6459 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006460 }
6461
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006462 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006463 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006464 if (profile == nullptr) {
6465 return false;
6466 }
6467
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006468 return true;
6469}
6470
Shunkai Yao4c3af932024-04-26 04:12:21 +00006471// The Spatializer output is compatible with Haptic use cases if:
6472// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6473// with client if client haptic channel bits were set, or
6474// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6475// including the haptic bits or creating the HapticGenerator effect for same session.
6476bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6477 const audio_config_t* config, audio_session_t sessionId) const {
6478 const auto clientHapticChannel =
6479 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6480 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6481 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6482
6483 if (threadOutputHapticChannel) {
6484 // check format and sampleRate match if client haptic channel mask exist
6485 if (clientHapticChannel) {
6486 return mSpatializerOutput->getFormat() == config->format &&
6487 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6488 }
6489 return true;
6490 } else {
6491 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6492 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6493 // HapticGenerator effect for this session) are not supported.
6494 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006495 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006496 }
6497}
6498
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006499void AudioPolicyManager::checkVirtualizerClientRoutes() {
6500 std::set<audio_stream_type_t> streamsToInvalidate;
6501 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006502 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6503 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006504 audio_attributes_t attr = client->attributes();
6505 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6506 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6507 audio_config_base_t clientConfig = client->config();
6508 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006509 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006510 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006511 streamsToInvalidate.insert(client->stream());
6512 }
6513 }
6514 }
6515
jiabinc44b3462022-12-08 12:52:31 -08006516 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006517}
6518
Eric Laurente191d1b2022-04-15 11:59:25 +02006519
6520bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6521 const sp<SwAudioOutputDescriptor>& outputDesc) {
6522 if (outputDesc->isDuplicated()) {
6523 return false;
6524 }
6525 DeviceVector devices = outputDesc->supportedDevices();
6526 for (size_t i = 0; i < mOutputs.size(); i++) {
6527 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6528 if (desc == outputDesc || desc->isDuplicated()) {
6529 continue;
6530 }
6531 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6532 if (!sharedDevices.isEmpty()
6533 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6534 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6535 return false;
6536 }
6537 }
6538 return true;
6539}
6540
6541
Eric Laurentfa0f6742021-08-17 18:39:44 +02006542status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006543 const audio_attributes_t *attr,
6544 audio_io_handle_t *output) {
6545 *output = AUDIO_IO_HANDLE_NONE;
6546
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006547 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6548 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6549 audio_config_t *configPtr = nullptr;
6550 audio_config_t config;
6551 if (mixerConfig != nullptr) {
6552 config = audio_config_initializer(mixerConfig);
6553 configPtr = &config;
6554 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006555 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006556 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006557 return BAD_VALUE;
6558 }
6559
6560 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006561 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006562 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006563 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006564 return BAD_VALUE;
6565 }
6566
Eric Laurente191d1b2022-04-15 11:59:25 +02006567 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006568 for (size_t i = 0; i < mOutputs.size(); i++) {
6569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006570 if (!desc->isDuplicated()
6571 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6572 spatializerOutputs.push_back(desc);
6573 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006574 }
6575 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006576 mSpatializerOutput.clear();
6577 bool outputsChanged = false;
6578 for (const auto& desc : spatializerOutputs) {
6579 if (desc->mProfile == profile
6580 && (configPtr == nullptr
6581 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6582 mSpatializerOutput = desc;
6583 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6584 } else {
6585 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6586 " and devices %s", __func__, desc->mIoHandle,
6587 configPtr != nullptr ? configPtr->channel_mask : 0,
6588 devices.toString().c_str());
6589 closeOutput(desc->mIoHandle);
6590 outputsChanged = true;
6591 }
Eric Laurent39095982021-08-24 18:29:27 +02006592 }
6593
Eric Laurente191d1b2022-04-15 11:59:25 +02006594 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006595 sp<SwAudioOutputDescriptor> desc =
6596 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006597 if (desc != nullptr) {
6598 mSpatializerOutput = desc;
6599 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006600 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006601 }
6602
6603 checkVirtualizerClientRoutes();
6604
Eric Laurente191d1b2022-04-15 11:59:25 +02006605 if (outputsChanged) {
6606 mPreviousOutputs = mOutputs;
6607 mpClientInterface->onAudioPortListUpdate();
6608 }
6609
6610 if (mSpatializerOutput == nullptr) {
6611 ALOGV("%s could not open spatializer output with requested config", __func__);
6612 return BAD_VALUE;
6613 }
Eric Laurent39095982021-08-24 18:29:27 +02006614 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006615 ALOGV("%s returning new spatializer output %d", __func__, *output);
6616 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006617}
6618
Eric Laurentfa0f6742021-08-17 18:39:44 +02006619status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6620 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006621 return INVALID_OPERATION;
6622 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006623 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006624 return BAD_VALUE;
6625 }
Eric Laurent39095982021-08-24 18:29:27 +02006626
Eric Laurente191d1b2022-04-15 11:59:25 +02006627 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6628 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6629 closeOutput(mSpatializerOutput->mIoHandle);
6630 //from now on mSpatializerOutput is null
6631 checkVirtualizerClientRoutes();
6632 }
Eric Laurent39095982021-08-24 18:29:27 +02006633
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006634 return NO_ERROR;
6635}
6636
Eric Laurente552edb2014-03-10 17:42:56 -07006637// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006638// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006639// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006640uint32_t AudioPolicyManager::nextAudioPortGeneration()
6641{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006642 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006643}
6644
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006645AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006646 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006647 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006648 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006649 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006650 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006651 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006652 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006653 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006654 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006655 mAudioPortGeneration(1),
6656 mBeaconMuteRefCount(0),
6657 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006658 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006659 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006660 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006661 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006662{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006663}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006664
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006665status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006666 if (mEngine == nullptr) {
6667 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006668 }
6669 mEngine->setObserver(this);
6670 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006671 if (status != NO_ERROR) {
6672 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6673 return status;
6674 }
François Gaffie2110e042015-03-24 08:41:51 +01006675
jiabin29230182023-04-04 21:02:36 +00006676 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6677 // at the end of this function.
6678 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006679 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6680 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6681
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006682 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006683 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006684 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006685
Eric Laurent3a4311c2014-03-17 12:00:47 -07006686 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006687 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6688 defaultOutputDevice == nullptr ||
6689 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6690 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6691 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006692 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006693 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006694 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006695
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006696 // Silence ALOGV statements
6697 property_set("log.tag." LOG_TAG, "D");
6698
Eric Laurente552edb2014-03-10 17:42:56 -07006699 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006700 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006701}
6702
Eric Laurente0720872014-03-11 09:30:41 -07006703AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006704{
Eric Laurente552edb2014-03-10 17:42:56 -07006705 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006706 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006707 }
6708 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006709 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006710 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006711 mAvailableOutputDevices.clear();
6712 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006713 mOutputs.clear();
6714 mInputs.clear();
6715 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006716 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006717 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006718}
6719
Eric Laurente0720872014-03-11 09:30:41 -07006720status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006721{
Eric Laurent87ffa392015-05-22 10:32:38 -07006722 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006723}
6724
Eric Laurente552edb2014-03-10 17:42:56 -07006725// ---
6726
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006727void AudioPolicyManager::onNewAudioModulesAvailable()
6728{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006729 DeviceVector newDevices;
6730 onNewAudioModulesAvailableInt(&newDevices);
6731 if (!newDevices.empty()) {
6732 nextAudioPortGeneration();
6733 mpClientInterface->onAudioPortListUpdate();
6734 }
6735}
6736
6737void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6738{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006739 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006740 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6741 continue;
6742 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006743 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006744 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6745 handle != AUDIO_MODULE_HANDLE_NONE) {
6746 hwModule->setHandle(handle);
6747 } else {
6748 ALOGW("could not load HW module %s", hwModule->getName());
6749 continue;
6750 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006751 }
6752 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006753 // open all output streams needed to access attached devices.
6754 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006755 // This also validates mAvailableOutputDevices list
6756 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6757 if (!outProfile->canOpenNewIo()) {
6758 ALOGE("Invalid Output profile max open count %u for profile %s",
6759 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6760 continue;
6761 }
6762 if (!outProfile->hasSupportedDevices()) {
6763 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6764 continue;
6765 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006766 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6767 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006768 mTtsOutputAvailable = true;
6769 }
6770
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006771 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006772 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006773 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006774 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6775 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006776 } else {
6777 // choose first device present in profile's SupportedDevices also part of
6778 // mAvailableOutputDevices.
6779 if (availProfileDevices.isEmpty()) {
6780 continue;
6781 }
6782 supportedDevice = availProfileDevices.itemAt(0);
6783 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006784 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006785 continue;
6786 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306787
6788 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6789 && availProfileDevices.areAllDevicesAttached()) {
6790 ALOGV("%s skip opening output for mmap profile %s", __func__,
6791 outProfile->getTagName().c_str());
6792 continue;
6793 }
6794
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006795 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6796 mpClientInterface);
6797 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006798 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006799 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006800 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6801 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006802 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006803 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006804 if (status != NO_ERROR) {
6805 ALOGW("Cannot open output stream for devices %s on hw module %s",
6806 supportedDevice->toString().c_str(), hwModule->getName());
6807 continue;
6808 }
6809 for (const auto &device : availProfileDevices) {
6810 // give a valid ID to an attached device once confirmed it is reachable
6811 if (!device->isAttached()) {
6812 device->attach(hwModule);
6813 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006814 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006815 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006816 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6817 }
6818 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006819 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006820 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6821 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006822 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006823 }
Eric Laurent39095982021-08-24 18:29:27 +02006824 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006825 outputDesc->close();
6826 } else {
6827 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306828 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006829 DeviceVector(supportedDevice),
6830 true,
6831 0,
6832 NULL);
6833 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006834 }
6835 // open input streams needed to access attached devices to validate
6836 // mAvailableInputDevices list
6837 for (const auto& inProfile : hwModule->getInputProfiles()) {
6838 if (!inProfile->canOpenNewIo()) {
6839 ALOGE("Invalid Input profile max open count %u for profile %s",
6840 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6841 continue;
6842 }
6843 if (!inProfile->hasSupportedDevices()) {
6844 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6845 continue;
6846 }
6847 // chose first device present in profile's SupportedDevices also part of
6848 // available input devices
6849 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006850 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006851 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006852 ALOGV("%s: Input device list is empty! for profile %s",
6853 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006854 continue;
6855 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306856
6857 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6858 && availProfileDevices.areAllDevicesAttached()) {
6859 ALOGV("%s skip opening input for mmap profile %s", __func__,
6860 inProfile->getTagName().c_str());
6861 continue;
6862 }
6863
Eric Laurentc71b11b2024-06-03 12:54:53 +00006864 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6865 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006866
6867 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6868 status_t status = inputDesc->open(nullptr,
6869 availProfileDevices.itemAt(0),
6870 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306871 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006872 &input);
6873 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306874 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6875 __func__, availProfileDevices.toString().c_str(),
6876 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006877 continue;
6878 }
6879 for (const auto &device : availProfileDevices) {
6880 // give a valid ID to an attached device once confirmed it is reachable
6881 if (!device->isAttached()) {
6882 device->attach(hwModule);
6883 device->importAudioPortAndPickAudioProfile(inProfile, true);
6884 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006885 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006886 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6887 }
6888 }
6889 inputDesc->close();
6890 }
6891 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006892
6893 // Check if spatializer outputs can be closed until used.
6894 // mOutputs vector never contains duplicated outputs at this point.
6895 std::vector<audio_io_handle_t> outputsClosed;
6896 for (size_t i = 0; i < mOutputs.size(); i++) {
6897 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6898 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6899 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6900 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006901 nextAudioPortGeneration();
6902 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6903 if (index >= 0) {
6904 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6905 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6906 patchDesc->getAfHandle(), 0);
6907 mAudioPatches.removeItemsAt(index);
6908 mpClientInterface->onAudioPatchListUpdate();
6909 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006910 desc->close();
6911 }
6912 }
6913 for (auto output : outputsClosed) {
6914 removeOutput(output);
6915 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006916}
6917
Eric Laurent98e38192018-02-15 18:31:53 -08006918void AudioPolicyManager::addOutput(audio_io_handle_t output,
6919 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006920{
Eric Laurent1c333e22014-05-20 10:48:17 -07006921 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006922 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006923 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006924 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006925 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006926}
6927
François Gaffie53615e22015-03-19 09:24:12 +01006928void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6929{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006930 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6931 ALOGV("%s: removing primary output", __func__);
6932 mPrimaryOutput = nullptr;
6933 }
François Gaffie53615e22015-03-19 09:24:12 +01006934 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006935 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006936}
6937
Eric Laurent98e38192018-02-15 18:31:53 -08006938void AudioPolicyManager::addInput(audio_io_handle_t input,
6939 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006940{
Eric Laurent1c333e22014-05-20 10:48:17 -07006941 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006942 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006943}
Eric Laurente552edb2014-03-10 17:42:56 -07006944
François Gaffie11d30102018-11-02 16:09:09 +01006945status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006946 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006947 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006948{
François Gaffie11d30102018-11-02 16:09:09 +01006949 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006950 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006951 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006952
François Gaffie11d30102018-11-02 16:09:09 +01006953 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006954 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006955 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006956 }
Eric Laurente552edb2014-03-10 17:42:56 -07006957
Eric Laurent3b73df72014-03-11 09:06:29 -07006958 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006959 // first call getAudioPort to get the supported attributes from the HAL
6960 struct audio_port_v7 port = {};
6961 device->toAudioPort(&port);
6962 status_t status = mpClientInterface->getAudioPort(&port);
6963 if (status == NO_ERROR) {
6964 device->importAudioPort(port);
6965 }
6966
6967 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006968 for (size_t i = 0; i < mOutputs.size(); i++) {
6969 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006970 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006971 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006972 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6973 mOutputs.keyAt(i), device->toString().c_str());
6974 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006975 }
6976 }
6977 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006978 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006979 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006980 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6981 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006982 if (profile->supportsDevice(device)) {
6983 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306984 ALOGV("%s(): adding profile %s from module %s",
6985 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006986 }
6987 }
6988 }
6989
Eric Laurent7b279bb2015-12-14 10:18:23 -08006990 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006991
Eric Laurente552edb2014-03-10 17:42:56 -07006992 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006993 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006994 return BAD_VALUE;
6995 }
6996
6997 // open outputs for matching profiles if needed. Direct outputs are also opened to
6998 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6999 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007000 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007001
7002 // nothing to do if one output is already opened for this profile
7003 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007004 for (j = 0; j < outputs.size(); j++) {
7005 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007006 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007007 // matching profile: save the sample rates, format and channel masks supported
7008 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007009 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007010 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007011 }
Eric Laurente552edb2014-03-10 17:42:56 -07007012 break;
7013 }
7014 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007015 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007016 continue;
7017 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307018 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7019 ALOGV("%s skip opening output for mmap profile %s",
7020 __func__, profile->getTagName().c_str());
7021 continue;
7022 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007023 if (!profile->canOpenNewIo()) {
7024 ALOGW("Max Output number %u already opened for this profile %s",
7025 profile->maxOpenCount, profile->getTagName().c_str());
7026 continue;
7027 }
7028
Eric Laurent83efe1c2017-07-09 16:51:08 -07007029 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007030 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007031 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7032 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007033 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007034 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007035 profiles.removeAt(profile_index);
7036 profile_index--;
7037 } else {
7038 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007039 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007040 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007041 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7042 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007043 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007044 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007045
François Gaffie11d30102018-11-02 16:09:09 +01007046 if (device_distinguishes_on_address(deviceType)) {
7047 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7048 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307049 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7050 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007051 }
Eric Laurente552edb2014-03-10 17:42:56 -07007052 ALOGV("checkOutputsForDevice(): adding output %d", output);
7053 }
7054 }
7055
7056 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007057 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007058 return BAD_VALUE;
7059 }
Eric Laurentd4692962014-05-05 18:13:44 -07007060 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007061 // check if one opened output is not needed any more after disconnecting one device
7062 for (size_t i = 0; i < mOutputs.size(); i++) {
7063 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007064 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007065 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007066 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007067 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007068 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007069 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007070 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7071 mOutputs.keyAt(i));
7072 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007073 }
Eric Laurente552edb2014-03-10 17:42:56 -07007074 }
7075 }
Eric Laurentd4692962014-05-05 18:13:44 -07007076 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007077 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007078 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7079 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007080 if (!profile->supportsDevice(device)) {
7081 continue;
7082 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307083 ALOGV("%s(): clearing direct output profile %s on module %s",
7084 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007085 profile->clearAudioProfiles();
7086 if (!profile->hasDynamicAudioProfile()) {
7087 continue;
7088 }
7089 // When a device is disconnected, if there is an IOProfile that contains dynamic
7090 // profiles and supports the disconnected device, call getAudioPort to repopulate
7091 // the capabilities of the devices that is supported by the IOProfile.
7092 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7093 if (supportedDevice == device ||
7094 !mAvailableOutputDevices.contains(supportedDevice)) {
7095 continue;
7096 }
7097 struct audio_port_v7 port;
7098 supportedDevice->toAudioPort(&port);
7099 status_t status = mpClientInterface->getAudioPort(&port);
7100 if (status == NO_ERROR) {
7101 supportedDevice->importAudioPort(port);
7102 }
Eric Laurente552edb2014-03-10 17:42:56 -07007103 }
7104 }
7105 }
7106 }
7107 return NO_ERROR;
7108}
7109
François Gaffie11d30102018-11-02 16:09:09 +01007110status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007111 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007112{
François Gaffie11d30102018-11-02 16:09:09 +01007113 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007114 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007115 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007116 }
7117
Eric Laurentd4692962014-05-05 18:13:44 -07007118 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007119 sp<AudioInputDescriptor> desc;
7120
jiabinbf5f4262023-04-12 21:48:34 +00007121 // first call getAudioPort to get the supported attributes from the HAL
7122 struct audio_port_v7 port = {};
7123 device->toAudioPort(&port);
7124 status_t status = mpClientInterface->getAudioPort(&port);
7125 if (status == NO_ERROR) {
7126 device->importAudioPort(port);
7127 }
7128
Eric Laurent0dd51852019-04-19 18:18:58 -07007129 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007130 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007131 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007132 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007133 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007134 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007135 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007136
François Gaffie11d30102018-11-02 16:09:09 +01007137 if (profile->supportsDevice(device)) {
7138 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307139 ALOGV("%s : adding profile %s from module %s", __func__,
7140 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007141 }
7142 }
7143 }
7144
Eric Laurent0dd51852019-04-19 18:18:58 -07007145 if (profiles.isEmpty()) {
7146 ALOGW("%s: No input profile available for device %s",
7147 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007148 return BAD_VALUE;
7149 }
7150
7151 // open inputs for matching profiles if needed. Direct inputs are also opened to
7152 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7153 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7154
Eric Laurent1c333e22014-05-20 10:48:17 -07007155 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007156
Eric Laurentd4692962014-05-05 18:13:44 -07007157 // nothing to do if one input is already opened for this profile
7158 size_t input_index;
7159 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7160 desc = mInputs.valueAt(input_index);
7161 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007162 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007163 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007164 }
Eric Laurentd4692962014-05-05 18:13:44 -07007165 break;
7166 }
7167 }
7168 if (input_index != mInputs.size()) {
7169 continue;
7170 }
7171
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307172 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7173 ALOGV("%s skip opening input for mmap profile %s",
7174 __func__, profile->getTagName().c_str());
7175 continue;
7176 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007177 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307178 ALOGW("%s Max Input number %u already opened for this profile %s",
7179 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007180 continue;
7181 }
7182
Eric Laurentc71b11b2024-06-03 12:54:53 +00007183 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007184 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307185 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307186 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7187 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007188
Eric Laurentcf2c0212014-07-25 16:20:43 -07007189 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007190 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007191 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007192 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007193 mpClientInterface->setParameters(input, String8(param));
7194 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007195 }
jiabin12537fc2023-10-12 17:56:08 +00007196 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007197 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307198 ALOGW("%s direct input missing param for profile %s", __func__,
7199 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007200 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007201 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007202 }
7203
Eric Laurent0dd51852019-04-19 18:18:58 -07007204 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007205 addInput(input, desc);
7206 }
7207 } // endif input != 0
7208
Eric Laurentcf2c0212014-07-25 16:20:43 -07007209 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307210 ALOGW("%s could not open input for device %s on profile %s", __func__,
7211 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007212 profiles.removeAt(profile_index);
7213 profile_index--;
7214 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007215 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007216 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007217 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307218 ALOGV("%s: adding input %d for profile %s", __func__,
7219 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007220
7221 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307222 ALOGV("%s: closing input %d for profile %s", __func__,
7223 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007224 closeInput(input);
7225 }
Eric Laurentd4692962014-05-05 18:13:44 -07007226 }
7227 } // end scan profiles
7228
7229 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007230 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007231 return BAD_VALUE;
7232 }
7233 } else {
7234 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007235 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007236 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007237 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007238 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007239 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007240 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007241 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307242 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7243 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007244 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007245 }
7246 }
7247 }
7248 } // end disconnect
7249
7250 return NO_ERROR;
7251}
7252
7253
Eric Laurente0720872014-03-11 09:30:41 -07007254void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007255{
7256 ALOGV("closeOutput(%d)", output);
7257
François Gaffie1c878552018-11-22 16:53:21 +01007258 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7259 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007260 ALOGW("closeOutput() unknown output %d", output);
7261 return;
7262 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007263 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007264 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007265
Eric Laurente552edb2014-03-10 17:42:56 -07007266 // look for duplicated outputs connected to the output being removed.
7267 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007268 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7269 if (dupOutput->isDuplicated() &&
7270 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7271 sp<SwAudioOutputDescriptor> remainingOutput =
7272 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007273 // As all active tracks on duplicated output will be deleted,
7274 // and as they were also referenced on the other output, the reference
7275 // count for their stream type must be adjusted accordingly on
7276 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007277 const bool wasActive = remainingOutput->isActive();
7278 // Note: no-op on the closing output where all clients has already been set inactive
7279 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007280 // stop() will be a no op if the output is still active but is needed in case all
7281 // active streams refcounts where cleared above
7282 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007283 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007284 }
Eric Laurente552edb2014-03-10 17:42:56 -07007285 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7286 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7287
7288 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007289 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007290 }
7291 }
7292
Eric Laurent05b90f82014-08-27 15:32:29 -07007293 nextAudioPortGeneration();
7294
François Gaffie1c878552018-11-22 16:53:21 +01007295 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007296 if (index >= 0) {
7297 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007298 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7299 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007300 mAudioPatches.removeItemsAt(index);
7301 mpClientInterface->onAudioPatchListUpdate();
7302 }
7303
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007304 if (closingOutputWasActive) {
7305 closingOutput->stop();
7306 }
François Gaffie1c878552018-11-22 16:53:21 +01007307 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007308 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007309 for (const auto device : closingOutput->devices()) {
7310 device->setPreferredConfig(nullptr);
7311 }
7312 }
Eric Laurente552edb2014-03-10 17:42:56 -07007313
François Gaffie53615e22015-03-19 09:24:12 +01007314 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007315 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007316 if (closingOutput == mSpatializerOutput) {
7317 mSpatializerOutput.clear();
7318 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007319
7320 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7321 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007322 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007323 bool directOutputOpen = false;
7324 for (size_t i = 0; i < mOutputs.size(); i++) {
7325 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7326 directOutputOpen = true;
7327 break;
7328 }
7329 }
7330 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007331 ALOGV("no direct outputs open, reset MSD patches");
7332 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7333 // how output devices for patching are resolved. Avoid by caching and reusing the
7334 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7335 // devices to patch to. This may be complicated by the fact that devices may become
7336 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007337 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007338 }
7339 }
jiabin220eea12024-05-17 17:55:20 +00007340
7341 if (closingOutput->mPreferredAttrInfo != nullptr) {
7342 closingOutput->mPreferredAttrInfo->resetActiveClient();
7343 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007344}
7345
7346void AudioPolicyManager::closeInput(audio_io_handle_t input)
7347{
7348 ALOGV("closeInput(%d)", input);
7349
7350 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7351 if (inputDesc == NULL) {
7352 ALOGW("closeInput() unknown input %d", input);
7353 return;
7354 }
7355
Eric Laurent6a94d692014-05-20 11:18:06 -07007356 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007357
François Gaffie11d30102018-11-02 16:09:09 +01007358 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007359 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007360 if (index >= 0) {
7361 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007362 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7363 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007364 mAudioPatches.removeItemsAt(index);
7365 mpClientInterface->onAudioPatchListUpdate();
7366 }
7367
François Gaffie6ebbce02023-07-19 13:27:53 +02007368 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007369 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007370 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007371
François Gaffie11d30102018-11-02 16:09:09 +01007372 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7373 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007374 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007375 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007376 }
Eric Laurente552edb2014-03-10 17:42:56 -07007377}
7378
François Gaffie11d30102018-11-02 16:09:09 +01007379SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7380 const DeviceVector &devices,
7381 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007382{
7383 SortedVector<audio_io_handle_t> outputs;
7384
François Gaffie11d30102018-11-02 16:09:09 +01007385 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007386 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007387 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007388 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007389 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007390 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007391 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007392 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007393 outputs.add(openOutputs.keyAt(i));
7394 }
7395 }
7396 return outputs;
7397}
7398
Mikhail Naganov37977152018-07-11 15:54:44 -07007399void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7400{
7401 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7402 // output is suspended before any tracks are moved to it
7403 checkA2dpSuspend();
7404 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007405 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007406 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007407 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007408 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007409 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7410 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7411 // configuration changes will ultimately be rerouted correctly. We can still avoid
7412 // unnecessary rerouting by caching and reusing the arguments to
7413 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7414 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007415 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007416 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007417 // an event that changed routing likely occurred, inform upper layers
7418 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007419}
7420
François Gaffiec005e562018-11-06 15:04:49 +01007421bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7422 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007423{
François Gaffiec005e562018-11-06 15:04:49 +01007424 return mEngine->getProductStrategyForAttributes(lAttr) ==
7425 mEngine->getProductStrategyForAttributes(rAttr);
7426}
7427
Francois Gaffieff1eb522020-05-06 18:37:04 +02007428void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7429{
7430 for (size_t i = 0; i < mAudioSources.size(); i++) {
7431 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7432 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007433 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007434 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007435 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007436 }
7437 }
7438}
7439
7440void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7441{
7442 for (size_t i = 0; i < mAudioSources.size(); i++) {
7443 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7444 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7445 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7446 disconnectAudioSource(sourceDesc);
7447 }
7448 }
7449}
7450
François Gaffiec005e562018-11-06 15:04:49 +01007451void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7452{
7453 auto psId = mEngine->getProductStrategyForAttributes(attr);
7454
7455 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7456 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007457
François Gaffie11d30102018-11-02 16:09:09 +01007458 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7459 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007460
Eric Laurentc209fe42020-06-05 18:11:23 -07007461 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007462 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007463 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007464 // take into account dynamic audio policies related changes: if a client is now associated
7465 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007466 // invalidate clients on outputs that do not support all the newly selected devices for the
7467 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007468 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007469 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007470 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007471 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007472 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007473
Eric Laurentc209fe42020-06-05 18:11:23 -07007474 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7475 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7476 continue;
7477 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007478 if (!desc->supportsAllDevices(newDevices)) {
7479 invalidatedOutputs.push_back(desc);
7480 break;
7481 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007482 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007483 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007484 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7485 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7486 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007487 if (status == OK) {
7488 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7489 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7490 maxLatency = desc->latency();
7491 }
7492 invalidatedOutputs.push_back(desc);
7493 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007494 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007495 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007496 }
7497 }
7498
Eric Laurent56ed8842022-11-15 16:04:41 +01007499 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007500 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7501 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007502 for (audio_io_handle_t srcOut : srcOutputs) {
7503 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007504 if (desc == nullptr) continue;
7505
7506 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007507 maxLatency = desc->latency();
7508 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007509
Eric Laurent56ed8842022-11-15 16:04:41 +01007510 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007511 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007512 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007513 // a client on a non direct outputs has necessarily a linear PCM format
7514 // so we can call selectOutput() safely
7515 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7516 client->flags(),
7517 client->config().format,
7518 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007519 client->config().sample_rate,
7520 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007521 if (newOutput != srcOut) {
7522 invalidate = true;
7523 break;
7524 }
7525 } else {
7526 sp<IOProfile> profile = getProfileForOutput(newDevices,
7527 client->config().sample_rate,
7528 client->config().format,
7529 client->config().channel_mask,
7530 client->flags(),
7531 true /* directOnly */);
7532 if (profile != desc->mProfile) {
7533 invalidate = true;
7534 break;
7535 }
7536 }
7537 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007538 // mute strategy while moving tracks from one output to another
7539 if (invalidate) {
7540 invalidatedOutputs.push_back(desc);
7541 if (desc->isStrategyActive(psId)) {
7542 setStrategyMute(psId, true, desc);
7543 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7544 newDevices.types());
7545 }
Eric Laurente552edb2014-03-10 17:42:56 -07007546 }
François Gaffiec005e562018-11-06 15:04:49 +01007547 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007548 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007549 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007550 }
Eric Laurente552edb2014-03-10 17:42:56 -07007551 }
7552
Eric Laurent56ed8842022-11-15 16:04:41 +01007553 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7554 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7555 std::to_string(srcOutputs[0]).c_str(),
7556 std::to_string(dstOutputs[0]).c_str());
7557
François Gaffiec005e562018-11-06 15:04:49 +01007558 // Move effects associated to this stream from previous output to new output
7559 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007560 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007561 }
François Gaffiec005e562018-11-06 15:04:49 +01007562 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007563 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007564 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007565 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007566 desc->setTracksInvalidatedStatusByStrategy(psId);
7567 }
Eric Laurente552edb2014-03-10 17:42:56 -07007568 }
7569 }
7570}
7571
Eric Laurente0720872014-03-11 09:30:41 -07007572void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007573{
François Gaffiec005e562018-11-06 15:04:49 +01007574 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7575 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7576 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007577 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007578 }
Eric Laurente552edb2014-03-10 17:42:56 -07007579}
7580
Kevin Rocard153f92d2018-12-18 18:33:28 -08007581void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007582 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007583 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007584 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007585 for (size_t i = 0; i < mOutputs.size(); i++) {
7586 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7587 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007588 sp<AudioPolicyMix> primaryMix;
7589 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007590 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007591 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7592 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7593 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007594 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7595 for (auto &secondaryMix : secondaryMixes) {
7596 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7597 if (outputDesc != nullptr &&
7598 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7599 secondaryDescs.push_back(outputDesc);
7600 }
7601 }
7602
jiabinc44b3462022-12-08 12:52:31 -08007603 if (status != OK &&
7604 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7605 // When it failed to query secondary output, only invalidate the client that is not
7606 // MMAP. The reason is that MMAP stream will not support secondary output.
7607 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007608 } else if (!std::equal(
7609 client->getSecondaryOutputs().begin(),
7610 client->getSecondaryOutputs().end(),
7611 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007612 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7613 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007614 // If the format is not PCM, the tracks should be invalidated to get correct
7615 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007616 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007617 } else {
7618 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7619 std::vector<audio_io_handle_t> secondaryOutputIds;
7620 for (const auto &secondaryDesc: secondaryDescs) {
7621 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7622 weakSecondaryDescs.push_back(secondaryDesc);
7623 }
7624 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7625 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007626 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007627 }
7628 }
7629 }
jiabin10a03f12021-05-07 23:46:28 +00007630 if (!trackSecondaryOutputs.empty()) {
7631 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7632 }
jiabinc44b3462022-12-08 12:52:31 -08007633 if (!clientsToInvalidate.empty()) {
7634 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7635 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007636 }
7637}
7638
Eric Laurent2517af32020-11-25 15:31:27 +01007639bool AudioPolicyManager::isScoRequestedForComm() const {
7640 AudioDeviceTypeAddrVector devices;
7641 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7642 for (const auto &device : devices) {
7643 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7644 return true;
7645 }
7646 }
7647 return false;
7648}
7649
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007650bool AudioPolicyManager::isHearingAidUsedForComm() const {
7651 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7652 true /*fromCache*/);
7653 for (const auto &device : devices) {
7654 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7655 return true;
7656 }
7657 }
7658 return false;
7659}
7660
7661
Eric Laurente0720872014-03-11 09:30:41 -07007662void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007663{
François Gaffie53615e22015-03-19 09:24:12 +01007664 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007665 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007666 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007667 return;
7668 }
7669
Eric Laurent3a4311c2014-03-17 12:00:47 -07007670 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007671 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7672 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007673 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007674
7675 // if suspended, restore A2DP output if:
7676 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007677 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007678 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007679 //
Eric Laurentf732e072016-08-03 19:30:28 -07007680 // if not suspended, suspend A2DP output if:
7681 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007682 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007683 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007684 //
7685 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007686 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007687 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007688 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007689 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007690
7691 mpClientInterface->restoreOutput(a2dpOutput);
7692 mA2dpSuspended = false;
7693 }
7694 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007695 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007696 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007697 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007698 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007699
7700 mpClientInterface->suspendOutput(a2dpOutput);
7701 mA2dpSuspended = true;
7702 }
7703 }
7704}
7705
François Gaffie11d30102018-11-02 16:09:09 +01007706DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7707 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007708{
François Gaffiedb1755b2023-09-01 11:50:35 +02007709 if (outputDesc == nullptr) {
7710 return DeviceVector{};
7711 }
François Gaffie11d30102018-11-02 16:09:09 +01007712
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007713 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007714 if (index >= 0) {
7715 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007716 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007717 ALOGV("%s device %s forced by patch %d", __func__,
7718 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7719 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007720 }
7721 }
7722
Dean Wheatley514b4312020-06-17 21:45:00 +10007723 // Do not retrieve engine device for outputs through MSD
7724 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7725 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7726 return outputDesc->devices();
7727 }
7728
Eric Laurent97ac8712018-07-27 18:59:02 -07007729 // Honor explicit routing requests only if no client using default routing is active on this
7730 // input: a specific app can not force routing for other apps by setting a preferred device.
7731 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007732 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007733 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007734 if (device != nullptr) {
7735 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007736 }
7737
François Gaffiea807ef92018-11-05 10:44:33 +01007738 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7739 // of setForceUse / Default Bus device here
7740 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7741 if (device != nullptr) {
7742 return DeviceVector(device);
7743 }
7744
François Gaffiedb1755b2023-09-01 11:50:35 +02007745 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007746 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7747 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307748 auto hasStreamActive = [&](auto stream) {
7749 return hasStream(streams, stream) && isStreamActive(stream, 0);
7750 };
Eric Laurent484e9272018-06-07 17:29:23 -07007751
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307752 auto doGetOutputDevicesForVoice = [&]() {
7753 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007754 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307755 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007756 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7757 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307758 };
7759
7760 // With low-latency playing on speaker, music on WFD, when the first low-latency
7761 // output is stopped, getNewOutputDevices checks for a product strategy
7762 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007763 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307764 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7765 // stream is associated to the output descriptor.
7766 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7767 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7768 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7769 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007770 // Retrieval of devices for voice DL is done on primary output profile, cannot
7771 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007772 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007773 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7774 break;
7775 }
Eric Laurente552edb2014-03-10 17:42:56 -07007776 }
François Gaffiec005e562018-11-06 15:04:49 +01007777 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007778 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007779}
7780
François Gaffie11d30102018-11-02 16:09:09 +01007781sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7782 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007783{
François Gaffie11d30102018-11-02 16:09:09 +01007784 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007785
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007786 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007787 if (index >= 0) {
7788 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007789 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007790 ALOGV("getNewInputDevice() device %s forced by patch %d",
7791 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7792 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007793 }
7794 }
7795
Eric Laurent97ac8712018-07-27 18:59:02 -07007796 // Honor explicit routing requests only if no client using default routing is active on this
7797 // input: a specific app can not force routing for other apps by setting a preferred device.
7798 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007799 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7800 if (device != nullptr) {
7801 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007802 }
7803
Eric Laurentdc95a252018-04-12 12:46:56 -07007804 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007805 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007806 audio_attributes_t attributes;
7807 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007808 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007809 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7810 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007811 attributes = topClient->attributes();
7812 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007813 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007814 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007815 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7816 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007817 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007818 }
7819
Francois Gaffie716e1432019-01-14 16:58:59 +01007820 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7821 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007822 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007823 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007824 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007825 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007826
Eric Laurente552edb2014-03-10 17:42:56 -07007827 return device;
7828}
7829
Eric Laurent794fde22016-03-11 09:50:45 -08007830bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7831 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007832 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007833}
7834
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007835status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007836 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007837 if (devices == nullptr) {
7838 return BAD_VALUE;
7839 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007840
Andy Hung6d23c0f2022-02-16 09:37:15 -08007841 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007842 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7843 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007844 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007845 for (const auto& device : curDevices) {
7846 devices->push_back(device->getDeviceTypeAddr());
7847 }
7848 return NO_ERROR;
7849}
7850
Eric Laurente0720872014-03-11 09:30:41 -07007851void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007852 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007853 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007854 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007855 updateDevicesAndOutputs();
7856 break;
7857 default:
7858 break;
7859 }
7860}
7861
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007862uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007863
7864 // skip beacon mute management if a dedicated TTS output is available
7865 if (mTtsOutputAvailable) {
7866 return 0;
7867 }
7868
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007869 switch(event) {
7870 case STARTING_OUTPUT:
7871 mBeaconMuteRefCount++;
7872 break;
7873 case STOPPING_OUTPUT:
7874 if (mBeaconMuteRefCount > 0) {
7875 mBeaconMuteRefCount--;
7876 }
7877 break;
7878 case STARTING_BEACON:
7879 mBeaconPlayingRefCount++;
7880 break;
7881 case STOPPING_BEACON:
7882 if (mBeaconPlayingRefCount > 0) {
7883 mBeaconPlayingRefCount--;
7884 }
7885 break;
7886 }
7887
7888 if (mBeaconMuteRefCount > 0) {
7889 // any playback causes beacon to be muted
7890 return setBeaconMute(true);
7891 } else {
7892 // no other playback: unmute when beacon starts playing, mute when it stops
7893 return setBeaconMute(mBeaconPlayingRefCount == 0);
7894 }
7895}
7896
7897uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7898 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7899 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7900 // keep track of muted state to avoid repeating mute/unmute operations
7901 if (mBeaconMuted != mute) {
7902 // mute/unmute AUDIO_STREAM_TTS on all outputs
7903 ALOGV("\t muting %d", mute);
7904 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007905 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7906 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7907 ALOGV("\t no tts volume source available");
7908 return 0;
7909 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007910 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007911 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007912 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7913 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007914 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007915 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007916 maxLatency = latency;
7917 }
7918 }
7919 mBeaconMuted = mute;
7920 return maxLatency;
7921 }
7922 return 0;
7923}
7924
Eric Laurente0720872014-03-11 09:30:41 -07007925void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007926{
François Gaffiec005e562018-11-06 15:04:49 +01007927 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007928 mPreviousOutputs = mOutputs;
7929}
7930
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007931uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007932 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007933 uint32_t delayMs)
7934{
7935 // mute/unmute strategies using an incompatible device combination
7936 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7937 // if unmuting, unmute only after the specified delay
7938 if (outputDesc->isDuplicated()) {
7939 return 0;
7940 }
7941
7942 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007943 DeviceVector devices = outputDesc->devices();
7944 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007945
François Gaffiec005e562018-11-06 15:04:49 +01007946 auto productStrategies = mEngine->getOrderedProductStrategies();
7947 for (const auto &productStrategy : productStrategies) {
7948 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7949 DeviceVector curDevices =
7950 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7951 curDevices = curDevices.filter(outputDesc->supportedDevices());
7952 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007953 bool doMute = false;
7954
François Gaffiec005e562018-11-06 15:04:49 +01007955 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007956 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007957 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7958 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007959 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007960 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007961 }
Eric Laurent99401132014-05-07 19:48:15 -07007962 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007963 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007964 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007965 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007966 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007967 continue;
7968 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307969 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007970 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7971 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7972 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007973 if (mute) {
7974 // FIXME: should not need to double latency if volume could be applied
7975 // immediately by the audioflinger mixer. We must account for the delay
7976 // between now and the next time the audioflinger thread for this output
7977 // will process a buffer (which corresponds to one buffer size,
7978 // usually 1/2 or 1/4 of the latency).
7979 if (muteWaitMs < desc->latency() * 2) {
7980 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007981 }
7982 }
7983 }
7984 }
7985 }
7986 }
7987
Eric Laurent99401132014-05-07 19:48:15 -07007988 // temporary mute output if device selection changes to avoid volume bursts due to
7989 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007990 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007991 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007992
Eric Laurentdc462862016-07-19 12:29:53 -07007993 if (muteWaitMs < tempMuteWaitMs) {
7994 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007995 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007996
7997 // If recommended duration is defined, replace temporary mute duration to avoid
7998 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7999 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8000 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8001 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8002 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8003
François Gaffieaaac0fd2018-11-22 17:56:39 +01008004 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8005 // make sure that we do not start the temporary mute period too early in case of
8006 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008007 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8008 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8009 delayMs + tempMuteDurationMs,
8010 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008011 }
8012 }
8013
Eric Laurente552edb2014-03-10 17:42:56 -07008014 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8015 if (muteWaitMs > delayMs) {
8016 muteWaitMs -= delayMs;
8017 usleep(muteWaitMs * 1000);
8018 return muteWaitMs;
8019 }
8020 return 0;
8021}
8022
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308023uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8024 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008025 const DeviceVector &devices,
8026 bool force,
8027 int delayMs,
8028 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008029 bool requiresMuteCheck, bool requiresVolumeCheck,
8030 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008031{
jiabin3ff8d7d2022-12-13 06:27:44 +00008032 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308033 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8034 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8035 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008036 uint32_t muteWaitMs;
8037
8038 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308039 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008040 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308041 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008042 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008043 return muteWaitMs;
8044 }
Eric Laurente552edb2014-03-10 17:42:56 -07008045
8046 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008047 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008048 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008049 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008050
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308051 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8052 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008053
8054 if (!filteredDevices.isEmpty()) {
8055 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008056 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008057
8058 // if the outputs are not materially active, there is no need to mute.
8059 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008060 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008061 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308062 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8063 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008064 muteWaitMs = 0;
8065 }
Eric Laurente552edb2014-03-10 17:42:56 -07008066
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008067 bool outputRouted = outputDesc->isRouted();
8068
Eric Laurent79ea9582020-06-11 18:49:24 -07008069 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8070 // output profile or if new device is not supported AND previous device(s) is(are) still
8071 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008072 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308073 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8074 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008075 // restore previous device after evaluating strategy mute state
8076 outputDesc->setDevices(prevDevices);
8077 return muteWaitMs;
8078 }
8079
Eric Laurente552edb2014-03-10 17:42:56 -07008080 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008081 // the requested device is AUDIO_DEVICE_NONE
8082 // OR the requested device is the same as current device
8083 // AND force is not specified
8084 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008085 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008086 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308087 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8088 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8089 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008090 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308091 ALOGV("%s %s setting same device on routed output, force apply volumes",
8092 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008093 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8094 }
Eric Laurente552edb2014-03-10 17:42:56 -07008095 return muteWaitMs;
8096 }
8097
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308098 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8099 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008100
Eric Laurente552edb2014-03-10 17:42:56 -07008101 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008102 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008103 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008104 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008105 PatchBuilder patchBuilder;
8106 patchBuilder.addSource(outputDesc);
8107 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8108 for (const auto &filteredDevice : filteredDevices) {
8109 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008110 }
8111
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008112 // Add half reported latency to delayMs when muteWaitMs is null in order
8113 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008114 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8115 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8116 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008117 }
Eric Laurente552edb2014-03-10 17:42:56 -07008118
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008119 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8120 if (!skipMuteDelay) {
8121 // update stream volumes according to new device
8122 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8123 }
Eric Laurente552edb2014-03-10 17:42:56 -07008124
8125 return muteWaitMs;
8126}
8127
Eric Laurentc75307b2015-03-17 15:29:32 -07008128status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008129 int delayMs,
8130 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008131{
Eric Laurent6a94d692014-05-20 11:18:06 -07008132 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008133 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8134 return INVALID_OPERATION;
8135 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008136 if (patchHandle) {
8137 index = mAudioPatches.indexOfKey(*patchHandle);
8138 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008139 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008140 }
8141 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008142 return INVALID_OPERATION;
8143 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008144 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008145 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008146 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008147 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008148 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008149 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008150 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008151 return status;
8152}
8153
8154status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008155 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008156 bool force,
8157 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008158{
8159 status_t status = NO_ERROR;
8160
Eric Laurent1f2f2232014-06-02 12:01:23 -07008161 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008162 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8163 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008164
François Gaffie11d30102018-11-02 16:09:09 +01008165 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008166 PatchBuilder patchBuilder;
8167 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008168 // AUDIO_SOURCE_HOTWORD is for internal use only:
8169 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008170 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8171 auto result = usecase;
8172 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8173 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8174 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008175 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008176 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008177 if (audio_is_remote_submix_device(device->type())) {
8178 // remote submix HAL does not support audio conversion, need source device
8179 // audio config to match the sink input descriptor audio config, otherwise AIDL
8180 // HAL patching will fail
8181 audio_port_config srcDevicePortConfig = {};
8182 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8183 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8184 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8185 srcDevicePortConfig.format = inputDesc->getFormat();
8186 patchBuilder.addSource(srcDevicePortConfig);
8187 } else {
8188 patchBuilder.addSource(device);
8189 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008190 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008191 }
8192 }
8193 return status;
8194}
8195
Eric Laurent6a94d692014-05-20 11:18:06 -07008196status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8197 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008198{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008199 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008200 ssize_t index;
8201 if (patchHandle) {
8202 index = mAudioPatches.indexOfKey(*patchHandle);
8203 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008204 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008205 }
8206 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008207 return INVALID_OPERATION;
8208 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008209 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008210 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008211 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008212 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008213 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008214 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008215 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008216 return status;
8217}
8218
François Gaffie11d30102018-11-02 16:09:09 +01008219sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008220 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008221 audio_format_t& format,
8222 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008223 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008224{
8225 // Choose an input profile based on the requested capture parameters: select the first available
8226 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008227 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008228
Atneya Nair0f0a8032022-12-12 16:20:12 -08008229 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8230 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8231 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8232
8233 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008234
jiabin2fd710d2022-05-02 23:20:22 +00008235 for (;;) {
8236 sp<IOProfile> firstInexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008237 uint32_t inexactSamplingRate = 0;
8238 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8239 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008240 uint32_t updatedSamplingRate = 0;
8241 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8242 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8243 for (const auto& hwModule : mHwModules) {
8244 for (const auto& profile : hwModule->getInputProfiles()) {
8245 // profile->log();
8246 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008247 if (profile->getCompatibilityScore(
8248 DeviceVector(device),
8249 samplingRate,
8250 &updatedSamplingRate,
8251 format,
8252 &updatedFormat,
8253 channelMask,
8254 &updatedChannelMask,
8255 // FIXME ugly cast
8256 (audio_output_flags_t) flags,
8257 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8258 samplingRate = updatedSamplingRate;
8259 format = updatedFormat;
8260 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008261 return profile;
8262 }
jiabin66acc432024-02-06 00:57:36 +00008263 if (firstInexact == nullptr
8264 && profile->getCompatibilityScore(
8265 DeviceVector(device),
8266 samplingRate,
8267 &updatedSamplingRate,
8268 format,
8269 &updatedFormat,
8270 channelMask,
8271 &updatedChannelMask,
8272 // FIXME ugly cast
8273 (audio_output_flags_t) flags,
8274 false /*exactMatchRequiredForInputFlags*/)
8275 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008276 firstInexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008277 inexactSamplingRate = updatedSamplingRate;
8278 inexactFormat = updatedFormat;
8279 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008280 }
8281 }
8282 }
8283
8284 if (firstInexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008285 samplingRate = inexactSamplingRate;
8286 format = inexactFormat;
8287 channelMask = inexactChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008288 return firstInexact;
8289 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8290 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8291 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8292 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8293 flags = AUDIO_INPUT_FLAG_NONE;
8294 } else { // fail
8295 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8296 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8297 samplingRate, format, channelMask, oriFlags);
8298 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008299 }
8300 }
jiabin2fd710d2022-05-02 23:20:22 +00008301
8302 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008303}
8304
Vlad Popa87e0e582024-05-20 18:49:20 -07008305float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8306 VolumeSource volumeSource,
8307 int index,
8308 const DeviceTypeSet &deviceTypes)
8309{
8310 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8311 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8312 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8313
8314 if (com_android_media_audio_abs_volume_index_fix()) {
8315 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8316 mAbsoluteVolumeDrivingStreams.end()) {
8317 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8318 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8319 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8320 ALOGD("%s: no group matching with %s", __FUNCTION__,
8321 toString(attributesToDriveAbs).c_str());
8322 return volumeDb;
8323 }
8324
8325 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8326 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8327 if (vsToDriveAbs == volumeSource) {
8328 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008329 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008330 } else {
8331 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8332 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8333 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8334 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8335 curvesAbs.getVolumeIndexMax());
8336 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8337 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8338 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8339 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8340 return newVolumeDb;
8341 }
8342 }
8343 return volumeDb;
8344 } else {
8345 return volumeDb;
8346 }
8347}
8348
François Gaffieaaac0fd2018-11-22 17:56:39 +01008349float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8350 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008351 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008352 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008353 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008354 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008355{
Vlad Popa9d482762024-06-21 16:40:23 -07008356 float volumeDb;
8357 if (adjustAttenuation) {
8358 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8359 } else {
8360 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8361 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008362 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8363 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8364
8365 if (!computeInternalInteraction) {
8366 return volumeDb;
8367 }
8368
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008369 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8370 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8371 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8372 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008373 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8374 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8375 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8376 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8377 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008378 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008379 mOutputs.isActive(ringVolumeSrc, 0)) {
8380 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008381 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008382 adjustAttenuation,
8383 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008384 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008385 }
8386
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008387 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008388 if ((volumeSource != callVolumeSrc && (isInCall() ||
8389 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008390 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008391 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8392 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008393 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8394 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8395 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008396 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008397 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008398 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008399 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008400 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008401 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008402 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008403 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8404 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8405 // programmatically muted.
8406 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8407 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8408 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008409 bool exemptFromCapping =
8410 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8411 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008412 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8413 volumeSource, volumeDb);
8414 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008415 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8416 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8417 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008418 }
8419 }
Eric Laurente552edb2014-03-10 17:42:56 -07008420 // if a headset is connected, apply the following rules to ring tones and notifications
8421 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008422 // - always attenuate notifications volume by 6dB
8423 // - attenuate ring tones volume by 6dB unless music is not playing and
8424 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008425 // - if music is playing, always limit the volume to current music volume,
8426 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008427 if (!Intersection(deviceTypes,
8428 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8429 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008430 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8431 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008432 ((volumeSource == alarmVolumeSrc ||
8433 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008434 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8435 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8436 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008437 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8438 curves.canBeMuted()) {
8439
Eric Laurente552edb2014-03-10 17:42:56 -07008440 // when the phone is ringing we must consider that music could have been paused just before
8441 // by the music application and behave as if music was active if the last music track was
8442 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008443 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8444 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008445 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008446 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008447 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8448 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008449 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008450 float musicVolDb = computeVolume(musicCurves,
8451 musicVolumeSrc,
8452 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008453 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008454 adjustAttenuation,
8455 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008456 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8457 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8458 if (volumeDb > minVolDb) {
8459 volumeDb = minVolDb;
8460 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008461 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008462 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8463 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008464 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8465 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8466 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8467 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008468 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008469 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008470 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8471 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008472 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8473 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008474 }
8475 }
jiabin9a3361e2019-10-01 09:38:30 -07008476 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008477 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008478 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008479 }
8480 }
8481
François Gaffie43c73442018-11-08 08:21:55 +01008482 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008483}
8484
Eric Laurent3839bc02018-07-10 18:33:34 -07008485int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008486 VolumeSource fromVolumeSource,
8487 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008488{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008489 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008490 return srcIndex;
8491 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008492 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8493 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008494 float minSrc = (float)srcCurves.getVolumeIndexMin();
8495 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8496 float minDst = (float)dstCurves.getVolumeIndexMin();
8497 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008498
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008499 // preserve mute request or correct range
8500 if (srcIndex < minSrc) {
8501 if (srcIndex == 0) {
8502 return 0;
8503 }
8504 srcIndex = minSrc;
8505 } else if (srcIndex > maxSrc) {
8506 srcIndex = maxSrc;
8507 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008508 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8509}
8510
François Gaffieaaac0fd2018-11-22 17:56:39 +01008511status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8512 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008513 int index,
8514 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008515 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008516 int delayMs,
8517 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008518{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008519 // APM is single threaded, and single instance.
8520 static std::set<IVolumeCurves*> invalidCurvesReported;
8521
François Gaffieaaac0fd2018-11-22 17:56:39 +01008522 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008523 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008524 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8525 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008526 return NO_ERROR;
8527 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008528
Eric Laurentae6e88c2024-01-10 14:42:57 +01008529 bool isVoiceVolSrc;
8530 bool isBtScoVolSrc;
8531 if (!isVolumeConsistentForCalls(
8532 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008533 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008534 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008535 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008536 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008537
jiabin9a3361e2019-10-01 09:38:30 -07008538 if (deviceTypes.empty()) {
8539 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008540 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008541 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008542 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008543 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008544
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008545 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008546 if (!invalidCurvesReported.count(&curves)) {
8547 invalidCurvesReported.insert(&curves);
8548 String8 dump;
8549 curves.dump(&dump);
8550 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8551 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008552 return BAD_VALUE;
8553 }
8554
jiabin9a3361e2019-10-01 09:38:30 -07008555 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008556 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008557 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008558 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008559 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8560 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008561 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8562 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008563 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008564 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008565
8566 bool muted;
8567 if (!com_android_media_audio_ring_my_car()) {
8568 muted = (index == 0) && (volumeDb != 0.0f);
8569 } else {
8570 muted = curves.isMuted();
8571 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008572 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8573 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008574
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008575 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008576 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8577 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8578 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008579 }
Eric Laurente552edb2014-03-10 17:42:56 -07008580 return NO_ERROR;
8581}
8582
Eric Laurentae6e88c2024-01-10 14:42:57 +01008583void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008584 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008585 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008586
8587 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8588 index = 0;
8589 }
8590
chenxin2095559032024-06-15 13:59:29 +08008591 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008592 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008593 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008594 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8595 } else {
8596 voiceVolume = index == 0 ? 0.0 : 1.0;
8597 }
8598 if (voiceVolume != mLastVoiceVolume) {
8599 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8600 mLastVoiceVolume = voiceVolume;
8601 }
8602}
8603
8604bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8605 const DeviceTypeSet& deviceTypes,
8606 bool& isVoiceVolSrc,
8607 bool& isBtScoVolSrc,
8608 const char* caller) {
8609 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008610 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8611
Eric Laurentae6e88c2024-01-10 14:42:57 +01008612 const bool isScoRequested = isScoRequestedForComm();
8613 const bool isHAUsed = isHearingAidUsedForComm();
8614
Vlad Popa695b76b2024-06-14 16:49:25 -07008615 if (com_android_media_audio_replace_stream_bt_sco()) {
8616 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8617 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8618 (isScoRequested || isHAUsed);
8619 return true;
8620 }
8621
8622 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008623 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8624
8625 if ((callVolSrc != btScoVolSrc) &&
8626 ((isVoiceVolSrc && isScoRequested) ||
8627 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8628 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8629 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8630 volumeSource, isScoRequested ? " " : " not ");
8631 return false;
8632 }
8633 return true;
8634}
8635
Eric Laurentc75307b2015-03-17 15:29:32 -07008636void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008637 const DeviceTypeSet& deviceTypes,
8638 int delayMs,
8639 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008640{
jiabincd510522020-01-22 09:40:55 -08008641 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008642 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8643 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008644 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008645 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008646 }
8647}
8648
François Gaffiec005e562018-11-06 15:04:49 +01008649void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8650 bool on,
8651 const sp<AudioOutputDescriptor>& outputDesc,
8652 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008653 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008654{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008655 std::vector<VolumeSource> sourcesToMute;
8656 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8657 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8658 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008659 VolumeSource source = toVolumeSource(attributes, false);
8660 if ((source != VOLUME_SOURCE_NONE) &&
8661 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8662 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008663 sourcesToMute.push_back(source);
8664 }
Eric Laurente552edb2014-03-10 17:42:56 -07008665 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008666 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008667 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008668 }
8669
Eric Laurente552edb2014-03-10 17:42:56 -07008670}
8671
Vlad Popa1e865e62024-08-15 19:11:42 -07008672void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8673 bool on,
8674 const sp<AudioOutputDescriptor>& outputDesc,
8675 int delayMs,
8676 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008677{
jiabin9a3361e2019-10-01 09:38:30 -07008678 if (deviceTypes.empty()) {
8679 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008680 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008681 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008682 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008683 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008684 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008685 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008686 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8687 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008688 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008689 }
8690 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008691 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8692 // ignored
8693 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008694 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008695 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008696 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008697 return;
8698 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008699 if (outputDesc->decMuteCount(volumeSource) == 0) {
8700 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008701 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008702 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008703 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008704 delayMs);
8705 }
8706 }
8707}
8708
François Gaffie53615e22015-03-19 09:24:12 +01008709bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8710{
François Gaffiec005e562018-11-06 15:04:49 +01008711 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008712 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8713 return true;
8714 }
8715
8716 // has known usage?
8717 switch (paa->usage) {
8718 case AUDIO_USAGE_UNKNOWN:
8719 case AUDIO_USAGE_MEDIA:
8720 case AUDIO_USAGE_VOICE_COMMUNICATION:
8721 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8722 case AUDIO_USAGE_ALARM:
8723 case AUDIO_USAGE_NOTIFICATION:
8724 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8725 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8726 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8727 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8728 case AUDIO_USAGE_NOTIFICATION_EVENT:
8729 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8730 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8731 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8732 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008733 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008734 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008735 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008736 case AUDIO_USAGE_EMERGENCY:
8737 case AUDIO_USAGE_SAFETY:
8738 case AUDIO_USAGE_VEHICLE_STATUS:
8739 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008740 break;
8741 default:
8742 return false;
8743 }
8744 return true;
8745}
8746
François Gaffie2110e042015-03-24 08:41:51 +01008747audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8748{
8749 return mEngine->getForceUse(usage);
8750}
8751
Eric Laurent96d1dda2022-03-14 17:14:19 +01008752bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008753 return isStateInCall(mEngine->getPhoneState());
8754}
8755
Eric Laurent96d1dda2022-03-14 17:14:19 +01008756bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008757 return is_state_in_call(state);
8758}
8759
Eric Laurentf9cccec2022-11-16 19:12:00 +01008760bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008761 audio_mode_t mode = mEngine->getPhoneState();
8762 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008763 || (mode == AUDIO_MODE_CALL_SCREEN)
8764 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008765}
8766
Eric Laurentf9cccec2022-11-16 19:12:00 +01008767bool AudioPolicyManager::isInCallOrScreening() const {
8768 audio_mode_t mode = mEngine->getPhoneState();
8769 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8770}
8771
Eric Laurentd60560a2015-04-10 11:31:20 -07008772void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8773{
8774 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008775 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008776 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008777 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008778 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008779 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008780 }
8781 }
8782
8783 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8784 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8785 bool release = false;
8786 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8787 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8788 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8789 source->ext.device.type == deviceDesc->type()) {
8790 release = true;
8791 }
8792 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008793 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008794 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8795 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8796 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008797 sink->ext.device.type == deviceDesc->type() &&
8798 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8799 || strncmp(sink->ext.device.address, address,
8800 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008801 release = true;
8802 }
8803 }
8804 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008805 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8806 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008807 }
8808 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008809
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008810 mInputs.clearSessionRoutesForDevice(deviceDesc);
8811
Francois Gaffie716e1432019-01-14 16:58:59 +01008812 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008813}
8814
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008815void AudioPolicyManager::modifySurroundFormats(
8816 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008817 std::unordered_set<audio_format_t> enforcedSurround(
8818 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008819 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008820 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008821 allSurround.insert(pair.first);
8822 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8823 }
Phil Burk09bc4612016-02-24 15:58:15 -08008824
8825 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8826 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008827 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008828 // This is the resulting set of formats depending on the surround mode:
8829 // 'all surround' = allSurround
8830 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8831 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8832 // 'manual surround' = mManualSurroundFormats
8833 // AUTO: formats v 'enforced surround'
8834 // ALWAYS: formats v 'all surround' v 'enforced surround'
8835 // NEVER: formats ^ 'non-surround'
8836 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008837
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008838 std::unordered_set<audio_format_t> formatSet;
8839 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8840 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008841 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008842 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008843 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008844 formatSet.insert(*formatIter);
8845 }
8846 }
8847 } else {
8848 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8849 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008850 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008851
jiabin81772902018-04-02 17:52:27 -07008852 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008853 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008854 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8855 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8856 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008857 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008858 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8859 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8860 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008861 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008862 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008863 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008864 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008865 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008866 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008867}
8868
jiabin06e4bab2019-07-29 10:13:34 -07008869void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8870 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008871 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8872 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8873
8874 // If NEVER, then remove support for channelMasks > stereo.
8875 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008876 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8877 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008878 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008879 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008880 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008881 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008882 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008883 }
8884 }
jiabin81772902018-04-02 17:52:27 -07008885 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8886 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8887 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008888 bool supports5dot1 = false;
8889 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008890 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008891 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8892 supports5dot1 = true;
8893 break;
8894 }
8895 }
8896 // If not then add 5.1 support.
8897 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008898 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008899 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008900 }
Phil Burk09bc4612016-02-24 15:58:15 -08008901 }
8902}
8903
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008904void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008905 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008906 const sp<IOProfile>& profile) {
8907 if (!profile->hasDynamicAudioProfile()) {
8908 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008909 }
François Gaffie112b0af2015-11-19 16:13:25 +01008910
jiabin12537fc2023-10-12 17:56:08 +00008911 audio_port_v7 devicePort;
8912 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008913
jiabin12537fc2023-10-12 17:56:08 +00008914 audio_port_v7 mixPort;
8915 profile->toAudioPort(&mixPort);
8916 mixPort.ext.mix.handle = ioHandle;
8917
8918 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8919 if (status != NO_ERROR) {
8920 ALOGE("%s failed to query the attributes of the mix port", __func__);
8921 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008922 }
jiabin12537fc2023-10-12 17:56:08 +00008923
8924 std::set<audio_format_t> supportedFormats;
8925 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8926 supportedFormats.insert(mixPort.audio_profiles[i].format);
8927 }
8928 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8929 mReportedFormatsMap[devDesc] = formats;
8930
8931 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008932 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8933 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008934 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8935 modifySurroundFormats(devDesc, &formats);
8936 size_t modifiedNumProfiles = 0;
8937 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8938 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8939 formats.end()) {
8940 // Skip the format that is not present after modifying surround formats.
8941 continue;
8942 }
8943 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8944 sizeof(struct audio_profile));
8945 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8946 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8947 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8948 modifySurroundChannelMasks(&channels);
8949 std::copy(channels.begin(), channels.end(),
8950 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8951 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8952 }
8953 mixPort.num_audio_profiles = modifiedNumProfiles;
8954 }
8955 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008956}
Eric Laurentd60560a2015-04-10 11:31:20 -07008957
Mikhail Naganovdc769682018-05-04 15:34:08 -07008958status_t AudioPolicyManager::installPatch(const char *caller,
8959 audio_patch_handle_t *patchHandle,
8960 AudioIODescriptorInterface *ioDescriptor,
8961 const struct audio_patch *patch,
8962 int delayMs)
8963{
8964 ssize_t index = mAudioPatches.indexOfKey(
8965 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8966 *patchHandle : ioDescriptor->getPatchHandle());
8967 sp<AudioPatch> patchDesc;
8968 status_t status = installPatch(
8969 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8970 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008971 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008972 }
8973 return status;
8974}
8975
8976status_t AudioPolicyManager::installPatch(const char *caller,
8977 ssize_t index,
8978 audio_patch_handle_t *patchHandle,
8979 const struct audio_patch *patch,
8980 int delayMs,
8981 uid_t uid,
8982 sp<AudioPatch> *patchDescPtr)
8983{
8984 sp<AudioPatch> patchDesc;
8985 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8986 if (index >= 0) {
8987 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008988 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008989 }
8990
8991 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8992 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8993 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8994 if (status == NO_ERROR) {
8995 if (index < 0) {
8996 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008997 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008998 } else {
8999 patchDesc->mPatch = *patch;
9000 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009001 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009002 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009003 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009004 }
9005 nextAudioPortGeneration();
9006 mpClientInterface->onAudioPatchListUpdate();
9007 }
9008 if (patchDescPtr) *patchDescPtr = patchDesc;
9009 return status;
9010}
9011
jiabinbce0c1d2020-10-05 11:20:18 -07009012bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9013{
9014 const TrackClientVector activeClients = output->getActiveClients();
9015 if (activeClients.empty()) {
9016 return true;
9017 }
9018 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9019 if (index < 0) {
9020 ALOGE("%s, no audio patch found while there are active clients on output %d",
9021 __func__, output->getId());
9022 return false;
9023 }
9024 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9025 DeviceVector routedDevices;
9026 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9027 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9028 patchDesc->mPatch.sinks[i].id);
9029 if (device == nullptr) {
9030 ALOGE("%s, no audio device found with id(%d)",
9031 __func__, patchDesc->mPatch.sinks[i].id);
9032 return false;
9033 }
9034 routedDevices.add(device);
9035 }
9036 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009037 if (client->isInvalid()) {
9038 // No need to take care about invalidated clients.
9039 continue;
9040 }
jiabinbce0c1d2020-10-05 11:20:18 -07009041 sp<DeviceDescriptor> preferredDevice =
9042 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9043 if (mEngine->getOutputDevicesForAttributes(
9044 client->attributes(), preferredDevice, false) == routedDevices) {
9045 return false;
9046 }
9047 }
9048 return true;
9049}
9050
9051sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009052 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009053 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9054 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009055{
9056 for (const auto& device : devices) {
9057 // TODO: This should be checking if the profile supports the device combo.
9058 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009059 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9060 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009061 return nullptr;
9062 }
9063 }
9064 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9065 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009066 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009067 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009068 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009069 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009070 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009071 return nullptr;
9072 }
jiabin14b50cc2023-12-13 19:01:52 +00009073 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9074 auto portConfig = desc->getConfig();
9075 for (const auto& device : devices) {
9076 device->setPreferredConfig(&portConfig);
9077 }
9078 }
jiabinbce0c1d2020-10-05 11:20:18 -07009079
9080 // Here is where the out_set_parameters() for card & device gets called
9081 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9082 const audio_devices_t deviceType = device->type();
9083 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009084 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009085 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9086 mpClientInterface->setParameters(output, String8(param));
9087 free(param);
9088 }
jiabin12537fc2023-10-12 17:56:08 +00009089 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009090 if (!profile->hasValidAudioProfile()) {
9091 ALOGW("%s() missing param", __func__);
9092 desc->close();
9093 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009094 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9095 // Reopen the output with the best audio profile picked by APM when the profile supports
9096 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009097 desc->close();
9098 output = AUDIO_IO_HANDLE_NONE;
9099 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9100 profile->pickAudioProfile(
9101 config.sample_rate, config.channel_mask, config.format);
9102 config.offload_info.sample_rate = config.sample_rate;
9103 config.offload_info.channel_mask = config.channel_mask;
9104 config.offload_info.format = config.format;
9105
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009106 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009107 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009108 if (status != NO_ERROR) {
9109 return nullptr;
9110 }
9111 }
9112
9113 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009114 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9115 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9116 hwModule->getHalVersionMajor() >= 3) {
9117 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9118 }
baek.kim -61c20122022-07-27 10:05:32 +00009119 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9120 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9121
jiabinbce0c1d2020-10-05 11:20:18 -07009122 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9123 sp<AudioPolicyMix> policyMix;
9124 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9125 policyMix->setOutput(desc);
9126 desc->mPolicyMix = policyMix;
9127 } else {
9128 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009129 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009130 }
9131
baek.kim -61c20122022-07-27 10:05:32 +00009132 } else if (hasPrimaryOutput() && speaker != nullptr
9133 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009134 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9135 // no duplicated output for:
9136 // - direct outputs
9137 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009138 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009139 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9140
9141 //TODO: configure audio effect output stage here
9142
9143 // open a duplicating output thread for the new output and the primary output
9144 sp<SwAudioOutputDescriptor> dupOutputDesc =
9145 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9146 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9147 if (status == NO_ERROR) {
9148 // add duplicated output descriptor
9149 addOutput(duplicatedOutput, dupOutputDesc);
9150 } else {
9151 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9152 mPrimaryOutput->mIoHandle, output);
9153 desc->close();
9154 removeOutput(output);
9155 nextAudioPortGeneration();
9156 return nullptr;
9157 }
9158 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009159 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9160 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9161 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009162 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009163 }
jiabinbce0c1d2020-10-05 11:20:18 -07009164 return desc;
9165}
9166
jiabinf1c73972022-04-14 16:28:52 -07009167status_t AudioPolicyManager::getDevicesForAttributes(
9168 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009169 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9170 // over any usage or content type also present in attr.
9171 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9172 attr.source != AUDIO_SOURCE_INVALID) {
9173 return getInputDevicesForAttributes(attr, devices);
9174 }
9175
jiabinf1c73972022-04-14 16:28:52 -07009176 // Devices are determined in the following precedence:
9177 //
9178 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9179 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9180 //
9181 // If no such dynamic policy then
9182 // 2) Devices containing an active client using setPreferredDevice
9183 // with same strategy as the attributes.
9184 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9185 //
9186 // If no corresponding active client with setPreferredDevice then
9187 // 3) Devices associated with the strategy determined by the attributes
9188 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9189 //
9190 // See related getOutputForAttrInt().
9191
9192 // check dynamic policies but only for primary descriptors (secondary not used for audible
9193 // audio routing, only used for duplication for playback capture)
9194 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009195 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009196 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009197 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9198 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9199 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009200 if (status != OK) {
9201 return status;
9202 }
9203
9204 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9205 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9206 // as they are unaffected by device/stream volume
9207 // (per SwAudioOutputDescriptor::isFixedVolume()).
9208 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9209 ) {
9210 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9211 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9212 devices.add(deviceDesc);
9213 } else {
9214 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9215 // which selects setPreferredDevice if active. This means forVolume call
9216 // will take an active setPreferredDevice, if such exists.
9217
9218 devices = mEngine->getOutputDevicesForAttributes(
9219 attr, nullptr /* preferredDevice */, false /* fromCache */);
9220 }
9221
9222 if (forVolume) {
9223 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9224 // for single volume control in AudioService (such relationship should exist if
9225 // SPEAKER_SAFE is present).
9226 //
9227 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9228 DeviceVector speakerSafeDevices =
9229 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9230 if (!speakerSafeDevices.isEmpty()) {
9231 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9232 devices.remove(speakerSafeDevices);
9233 }
9234 }
9235
9236 return NO_ERROR;
9237}
9238
wenyu zhang8558a332024-09-09 15:12:48 +00009239status_t AudioPolicyManager::getInputDevicesForAttributes(
9240 const audio_attributes_t &attr, DeviceVector &devices) {
9241 devices = DeviceVector(
9242 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9243 AUDIO_SESSION_NONE,
9244 nullptr /* mix */));
9245 return NO_ERROR;
9246}
9247
jiabinf1c73972022-04-14 16:28:52 -07009248status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9249 AudioProfileVector& audioProfiles,
9250 uint32_t flags,
9251 bool isInput) {
9252 for (const auto& hwModule : mHwModules) {
9253 // the MSD module checks for different conditions
9254 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9255 continue;
9256 }
9257 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9258 : hwModule->getOutputProfiles();
9259 for (const auto& profile : ioProfiles) {
9260 if (!profile->areAllDevicesSupported(devices) ||
9261 !profile->isCompatibleProfileForFlags(
9262 flags, false /*exactMatchRequiredForInputFlags*/)) {
9263 continue;
9264 }
9265 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9266 }
9267 }
9268
9269 if (!isInput) {
9270 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9271 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9272 if (msdModule != nullptr) {
9273 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9274 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9275 for (const auto &profile: msdModule->getOutputProfiles()) {
9276 if (!profile->asAudioPort()->isDirectOutput()) {
9277 continue;
9278 }
9279 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9280 }
9281 } else {
9282 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9283 }
9284 }
9285 }
9286
9287 return NO_ERROR;
9288}
9289
jiabin3ff8d7d2022-12-13 06:27:44 +00009290sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9291 const audio_config_t *config,
9292 audio_output_flags_t flags,
9293 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009294 closeOutput(outputDesc->mIoHandle);
9295 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9296 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9297 if (preferredOutput == nullptr) {
9298 ALOGE("%s failed to reopen output device=%d, caller=%s",
9299 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009300 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009301 return preferredOutput;
9302}
9303
9304void AudioPolicyManager::reopenOutputsWithDevices(
9305 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9306 for (const auto& [output, devices] : outputsToReopen) {
9307 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9308 closeOutput(output);
9309 openOutputWithProfileAndDevice(desc->mProfile, devices);
9310 }
jiabina84c3d32022-12-02 18:59:55 +00009311}
9312
jiabinc44b3462022-12-08 12:52:31 -08009313PortHandleVector AudioPolicyManager::getClientsForStream(
9314 audio_stream_type_t streamType) const {
9315 PortHandleVector clients;
9316 for (size_t i = 0; i < mOutputs.size(); ++i) {
9317 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9318 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9319 }
9320 return clients;
9321}
9322
9323void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9324 PortHandleVector clients;
9325 for (auto stream : streams) {
9326 PortHandleVector clientsForStream = getClientsForStream(stream);
9327 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9328 }
9329 mpClientInterface->invalidateTracks(clients);
9330}
9331
jiabin220eea12024-05-17 17:55:20 +00009332void AudioPolicyManager::updateClientsInternalMute(
9333 const sp<android::SwAudioOutputDescriptor> &desc) {
9334 if (!desc->isBitPerfect() ||
9335 !com::android::media::audioserver::
9336 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9337 // This is only used for bit perfect output now.
9338 return;
9339 }
9340 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9341 bool bitPerfectClientInternalMute = false;
9342 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9343 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9344 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9345 bitPerfectClient = client;
9346 continue;
9347 }
9348 bool muted = false;
9349 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9350 // System sound is muted.
9351 muted = true;
9352 } else {
9353 bitPerfectClientInternalMute = true;
9354 }
9355 if (client->setInternalMute(muted)) {
9356 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9357 if (!result.ok()) {
9358 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9359 continue;
9360 }
9361 media::TrackInternalMuteInfo info;
9362 info.portId = result.value();
9363 info.muted = client->getInternalMute();
9364 clientsInternalMute.push_back(std::move(info));
9365 }
9366 }
9367 if (bitPerfectClient != nullptr &&
9368 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9369 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9370 if (result.ok()) {
9371 media::TrackInternalMuteInfo info;
9372 info.portId = result.value();
9373 info.muted = bitPerfectClient->getInternalMute();
9374 clientsInternalMute.push_back(std::move(info));
9375 } else {
9376 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9377 __func__, bitPerfectClient->portId());
9378 }
9379 }
9380 if (!clientsInternalMute.empty()) {
9381 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9382 status != NO_ERROR) {
9383 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9384 }
9385 }
9386}
9387
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009388} // namespace android