blob: c0e5a423870c93e65e2fb8600c6b72266ef5d2e5 [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*/,
jiabin91beb492024-10-16 21:53:36 +00005025 flags)
jiabin66acc432024-02-06 00:57:36 +00005026 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005027 profile = curProfile;
5028 break;
5029 }
5030 }
5031 }
5032 if (profile == nullptr) {
5033 ALOGE("%s, there is no compatible profile found", __func__);
5034 return BAD_VALUE;
5035 }
5036
5037 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5038 sp<PreferredMixerAttributesInfo>::make(
5039 uid, portId, profile, flags, *mixerAttributes);
5040 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5041 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5042
5043 // If 1) there is any client from the preferred mixer configuration owner that is currently
5044 // active and matches the strategy and 2) current output is on the preferred device and the
5045 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5046 // configuration.
5047 std::vector<audio_io_handle_t> outputsToReopen;
5048 for (size_t i = 0; i < mOutputs.size(); i++) {
5049 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005050 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5051 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005052 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005053 } else {
5054 for (const auto &client: output->getActiveClients()) {
5055 if (client->uid() == uid && client->strategy() == strategy) {
5056 client->setIsInvalid();
5057 outputsToReopen.push_back(output->mIoHandle);
5058 }
jiabina84c3d32022-12-02 18:59:55 +00005059 }
5060 }
5061 }
5062 }
5063 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5064 config.sample_rate = mixerAttributes->config.sample_rate;
5065 config.channel_mask = mixerAttributes->config.channel_mask;
5066 config.format = mixerAttributes->config.format;
5067 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005068 sp<SwAudioOutputDescriptor> desc =
5069 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5070 if (desc == nullptr) {
5071 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5072 continue;
5073 }
jiabin220eea12024-05-17 17:55:20 +00005074 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005075 }
5076
5077 return NO_ERROR;
5078}
5079
5080sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005081 audio_port_handle_t devicePortId,
5082 product_strategy_t strategy,
5083 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005084 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5085 if (it == mPreferredMixerAttrInfos.end()) {
5086 return nullptr;
5087 }
jiabind9a58d32023-06-01 17:57:30 +00005088 if (activeBitPerfectPreferred) {
5089 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005090 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005091 return info;
5092 }
5093 }
jiabina84c3d32022-12-02 18:59:55 +00005094 }
jiabind9a58d32023-06-01 17:57:30 +00005095 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5096 return strategyMatchedMixerAttrInfoIt == it->second.end()
5097 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005098}
5099
5100status_t AudioPolicyManager::getPreferredMixerAttributes(
5101 const audio_attributes_t *attr,
5102 audio_port_handle_t portId,
5103 audio_mixer_attributes_t* mixerAttributes) {
5104 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5105 portId, mEngine->getProductStrategyForAttributes(*attr));
5106 if (info == nullptr) {
5107 return NAME_NOT_FOUND;
5108 }
5109 *mixerAttributes = info->getMixerAttributes();
5110 return NO_ERROR;
5111}
5112
5113status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5114 audio_port_handle_t portId,
5115 uid_t uid) {
5116 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5117 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5118 if (preferredMixerAttrInfo == nullptr) {
5119 return NAME_NOT_FOUND;
5120 }
5121 if (preferredMixerAttrInfo->getUid() != uid) {
5122 ALOGE("%s, requested uid=%d, owned uid=%d",
5123 __func__, uid, preferredMixerAttrInfo->getUid());
5124 return PERMISSION_DENIED;
5125 }
5126 mPreferredMixerAttrInfos[portId].erase(strategy);
5127 if (mPreferredMixerAttrInfos[portId].empty()) {
5128 mPreferredMixerAttrInfos.erase(portId);
5129 }
5130
5131 // Reconfig existing output
5132 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5133 for (size_t i = 0; i < mOutputs.size(); i++) {
5134 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5135 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5136 }
5137 }
5138 for (const auto output : potentialOutputsToReopen) {
5139 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5140 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5141 preferredMixerAttrInfo->getFlags())) {
5142 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5143 }
5144 }
5145 return NO_ERROR;
5146}
5147
Eric Laurent6a94d692014-05-20 11:18:06 -07005148status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5149 audio_port_type_t type,
5150 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005151 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005152 unsigned int *generation)
5153{
jiabin19cdba52020-11-24 11:28:58 -08005154 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5155 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 return BAD_VALUE;
5157 }
5158 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005159 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005160 *num_ports = 0;
5161 }
5162
5163 size_t portsWritten = 0;
5164 size_t portsMax = *num_ports;
5165 *num_ports = 0;
5166 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005167 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5168 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005169 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005170 for (const auto& dev : mAvailableOutputDevices) {
5171 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005172 continue;
5173 }
5174 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005175 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005176 }
5177 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005178 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 }
5180 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005181 for (const auto& dev : mAvailableInputDevices) {
5182 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005183 continue;
5184 }
5185 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005186 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005187 }
5188 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 }
5191 }
5192 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5193 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5194 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5195 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5196 }
5197 *num_ports += mInputs.size();
5198 }
5199 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005200 size_t numOutputs = 0;
5201 for (size_t i = 0; i < mOutputs.size(); i++) {
5202 if (!mOutputs[i]->isDuplicated()) {
5203 numOutputs++;
5204 if (portsWritten < portsMax) {
5205 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5206 }
5207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 }
Eric Laurent84c70242014-06-23 08:46:27 -07005209 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 }
5211 }
jiabina84c3d32022-12-02 18:59:55 +00005212
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005214 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 return NO_ERROR;
5216}
5217
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005218status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5219 std::vector<media::AudioPortFw>* _aidl_return) {
5220 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5221 audio_port_v7 port;
5222 dev->toAudioPort(&port);
5223 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5224 _aidl_return->push_back(std::move(aidlPort));
5225 return OK;
5226 };
5227
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005228 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005229 for (const auto& dev : module->getDeclaredDevices()) {
5230 if (role == media::AudioPortRole::NONE ||
5231 ((role == media::AudioPortRole::SOURCE)
5232 == audio_is_input_device(dev->type()))) {
5233 RETURN_STATUS_IF_ERROR(pushPort(dev));
5234 }
5235 }
5236 }
5237 return OK;
5238}
5239
jiabin19cdba52020-11-24 11:28:58 -08005240status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005241{
Eric Laurent99fcae42018-05-17 16:59:18 -07005242 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5243 return BAD_VALUE;
5244 }
5245 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5246 if (dev != 0) {
5247 dev->toAudioPort(port);
5248 return NO_ERROR;
5249 }
5250 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5251 if (dev != 0) {
5252 dev->toAudioPort(port);
5253 return NO_ERROR;
5254 }
5255 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5256 if (out != 0) {
5257 out->toAudioPort(port);
5258 return NO_ERROR;
5259 }
5260 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5261 if (in != 0) {
5262 in->toAudioPort(port);
5263 return NO_ERROR;
5264 }
5265 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005266}
5267
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005268status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5269 audio_patch_handle_t *handle,
5270 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005271{
François Gaffieafd4cea2019-11-18 15:50:22 +01005272 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 if (handle == NULL || patch == NULL) {
5274 return BAD_VALUE;
5275 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005276 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005277 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005278 return BAD_VALUE;
5279 }
5280 // only one source per audio patch supported for now
5281 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 return INVALID_OPERATION;
5283 }
Eric Laurent874c42872014-08-08 15:13:39 -07005284 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 return INVALID_OPERATION;
5286 }
Eric Laurent874c42872014-08-08 15:13:39 -07005287 for (size_t i = 0; i < patch->num_sinks; i++) {
5288 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5289 return INVALID_OPERATION;
5290 }
5291 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005292
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005293 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5294 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5295 if (srcDevice == nullptr || sinkDevice == nullptr) {
5296 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5297 return BAD_VALUE;
5298 }
5299 ALOGV("%s between source %s and sink %s", __func__,
5300 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5301 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5302 // Default attributes, default volume priority, not to infer with non raw audio patches.
5303 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5304 const struct audio_port_config *source = &patch->sources[0];
5305 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005306 new SourceClientDescriptor(
5307 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5308 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005309 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005310 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005311
5312 status_t status =
5313 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5314
5315 if (status != NO_ERROR) {
5316 return INVALID_OPERATION;
5317 }
5318 mAudioSources.add(portId, sourceDesc);
5319 return NO_ERROR;
5320}
5321
5322status_t AudioPolicyManager::connectAudioSourceToSink(
5323 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5324 const struct audio_patch *patch,
5325 audio_patch_handle_t &handle,
5326 uid_t uid, uint32_t delayMs)
5327{
5328 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5329 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5330 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5331 return INVALID_OPERATION;
5332 }
5333 sourceDesc->connect(handle, sinkDevice);
5334 if (isMsdPatch(handle)) {
5335 return NO_ERROR;
5336 }
5337 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5338 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5339 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5340 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5341 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5342 goto FailurePatchAdded;
5343 }
5344 status = swOutput->start();
5345 if (status != NO_ERROR) {
5346 goto FailureSourceAdded;
5347 }
5348 swOutput->addClient(sourceDesc);
5349 status = startSource(swOutput, sourceDesc, &delayMs);
5350 if (status != NO_ERROR) {
5351 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5352 goto FailureSourceActive;
5353 }
5354 if (delayMs != 0) {
5355 usleep(delayMs * 1000);
5356 }
5357 return NO_ERROR;
5358
5359FailureSourceActive:
5360 swOutput->stop();
5361 releaseOutput(sourceDesc->portId());
5362FailureSourceAdded:
5363 sourceDesc->setSwOutput(nullptr);
5364FailurePatchAdded:
5365 releaseAudioPatchInternal(handle);
5366 return INVALID_OPERATION;
5367}
5368
5369status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5370 audio_patch_handle_t *handle,
5371 uid_t uid, uint32_t delayMs,
5372 const sp<SourceClientDescriptor>& sourceDesc)
5373{
5374 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005375 sp<AudioPatch> patchDesc;
5376 ssize_t index = mAudioPatches.indexOfKey(*handle);
5377
François Gaffieafd4cea2019-11-18 15:50:22 +01005378 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5379 patch->sources[0].role,
5380 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005381#if LOG_NDEBUG == 0
5382 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005383 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5384 patch->sinks[i].role,
5385 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005386 }
5387#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005388
5389 if (index >= 0) {
5390 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005391 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5392 __func__, mUidCached, patchDesc->getUid(), uid);
5393 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005394 return INVALID_OPERATION;
5395 }
5396 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005397 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005398 }
5399
5400 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005401 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005403 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 return BAD_VALUE;
5405 }
Eric Laurent84c70242014-06-23 08:46:27 -07005406 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5407 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 if (patchDesc != 0) {
5409 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005410 ALOGV("%s source id differs for patch current id %d new id %d",
5411 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005412 return BAD_VALUE;
5413 }
5414 }
Eric Laurent874c42872014-08-08 15:13:39 -07005415 DeviceVector devices;
5416 for (size_t i = 0; i < patch->num_sinks; i++) {
5417 // Only support mix to devices connection
5418 // TODO add support for mix to mix connection
5419 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005420 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005421 return INVALID_OPERATION;
5422 }
5423 sp<DeviceDescriptor> devDesc =
5424 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5425 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005426 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005427 return BAD_VALUE;
5428 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005429
jiabin66acc432024-02-06 00:57:36 +00005430 if (outputDesc->mProfile->getCompatibilityScore(
5431 DeviceVector(devDesc),
5432 patch->sources[0].sample_rate,
5433 nullptr, // updatedSamplingRate
5434 patch->sources[0].format,
5435 nullptr, // updatedFormat
5436 patch->sources[0].channel_mask,
5437 nullptr, // updatedChannelMask
5438 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005439 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005440 return INVALID_OPERATION;
5441 }
5442 devices.add(devDesc);
5443 }
5444 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005445 return INVALID_OPERATION;
5446 }
Eric Laurent874c42872014-08-08 15:13:39 -07005447
Eric Laurent6a94d692014-05-20 11:18:06 -07005448 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005449 ALOGV("%s setting device %s on output %d",
5450 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305451 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005452 index = mAudioPatches.indexOfKey(*handle);
5453 if (index >= 0) {
5454 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005455 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005456 }
5457 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005458 patchDesc->setUid(uid);
5459 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005460 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005461 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005462 return INVALID_OPERATION;
5463 }
5464 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5465 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5466 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005467 // only one sink supported when connecting an input device to a mix
5468 if (patch->num_sinks > 1) {
5469 return INVALID_OPERATION;
5470 }
François Gaffie53615e22015-03-19 09:24:12 +01005471 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005472 if (inputDesc == NULL) {
5473 return BAD_VALUE;
5474 }
5475 if (patchDesc != 0) {
5476 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5477 return BAD_VALUE;
5478 }
5479 }
François Gaffie11d30102018-11-02 16:09:09 +01005480 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005481 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005482 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005483 return BAD_VALUE;
5484 }
5485
jiabin66acc432024-02-06 00:57:36 +00005486 if (inputDesc->mProfile->getCompatibilityScore(
5487 DeviceVector(device),
5488 patch->sinks[0].sample_rate,
5489 nullptr, /*updatedSampleRate*/
5490 patch->sinks[0].format,
5491 nullptr, /*updatedFormat*/
5492 patch->sinks[0].channel_mask,
5493 nullptr, /*updatedChannelMask*/
5494 // FIXME for the parameter type,
5495 // and the NONE
5496 (audio_output_flags_t)
5497 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005498 return INVALID_OPERATION;
5499 }
5500 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005501 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005502 device->toString().c_str(), inputDesc->mIoHandle);
5503 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005504 index = mAudioPatches.indexOfKey(*handle);
5505 if (index >= 0) {
5506 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005507 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005508 }
5509 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005510 patchDesc->setUid(uid);
5511 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005512 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005513 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005514 return INVALID_OPERATION;
5515 }
5516 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5517 // device to device connection
5518 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005519 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005520 return BAD_VALUE;
5521 }
5522 }
François Gaffie11d30102018-11-02 16:09:09 +01005523 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005524 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005525 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005526 return BAD_VALUE;
5527 }
Eric Laurent874c42872014-08-08 15:13:39 -07005528
Eric Laurent6a94d692014-05-20 11:18:06 -07005529 //update source and sink with our own data as the data passed in the patch may
5530 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005531 PatchBuilder patchBuilder;
5532 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005533
5534 // if first sink is to MSD, establish single MSD patch
5535 if (getMsdAudioOutDevices().contains(
5536 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5537 ALOGV("%s patching to MSD", __FUNCTION__);
5538 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5539 goto installPatch;
5540 }
5541
François Gaffieafd4cea2019-11-18 15:50:22 +01005542 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5543 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005544
Eric Laurent874c42872014-08-08 15:13:39 -07005545 for (size_t i = 0; i < patch->num_sinks; i++) {
5546 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005547 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005548 return INVALID_OPERATION;
5549 }
François Gaffie11d30102018-11-02 16:09:09 +01005550 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005551 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005552 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005553 return BAD_VALUE;
5554 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005555 audio_port_config sinkPortConfig = {};
5556 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5557 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005558
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005559 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5560 // volume management purpose (tracking activity)
5561 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5562 // in config XML to reach the sink so that is can be declared as available.
5563 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005564 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005565 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005566 // take care of dynamic routing for SwOutput selection,
5567 audio_attributes_t attributes = sourceDesc->attributes();
5568 audio_stream_type_t stream = sourceDesc->stream();
5569 audio_attributes_t resultAttr;
5570 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5571 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005572 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5573 config.channel_mask =
5574 (audio_channel_mask_get_representation(sourceMask)
5575 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5576 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005577 config.format = sourceDesc->config().format;
5578 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5579 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5580 bool isRequestedDeviceForExclusiveUse = false;
5581 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005582 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005583 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005584 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5585 &stream, sourceDesc->uid(), &config, &flags,
5586 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005587 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005588 if (output == AUDIO_IO_HANDLE_NONE) {
5589 ALOGV("%s no output for device %s",
5590 __FUNCTION__, sinkDevice->toString().c_str());
5591 return INVALID_OPERATION;
5592 }
5593 outputDesc = mOutputs.valueFor(output);
5594 if (outputDesc->isDuplicated()) {
5595 ALOGE("%s output is duplicated", __func__);
5596 return INVALID_OPERATION;
5597 }
François Gaffie7e39df22022-04-26 12:48:49 +02005598 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5599 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005600 } else {
5601 // Same for "raw patches" aka created from createAudioPatch API
5602 SortedVector<audio_io_handle_t> outputs =
5603 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5604 // if the sink device is reachable via an opened output stream, request to
5605 // go via this output stream by adding a second source to the patch
5606 // description
5607 output = selectOutput(outputs);
5608 if (output == AUDIO_IO_HANDLE_NONE) {
5609 ALOGE("%s no output available for internal patch sink", __func__);
5610 return INVALID_OPERATION;
5611 }
5612 outputDesc = mOutputs.valueFor(output);
5613 if (outputDesc->isDuplicated()) {
5614 ALOGV("%s output for device %s is duplicated",
5615 __func__, sinkDevice->toString().c_str());
5616 return INVALID_OPERATION;
5617 }
François Gaffie7e39df22022-04-26 12:48:49 +02005618 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005619 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005620 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005621 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005622 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005623 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005624 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5625 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005626 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5627 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005628 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005629 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005630 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005631 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005632 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005633 return INVALID_OPERATION;
5634 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005635 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005636 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005637 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005638 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005639 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005640 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005641 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005642 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5643 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005644 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005645 }
Eric Laurent83b88082014-06-20 18:31:16 -07005646 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005647 }
5648 // TODO: check from routing capabilities in config file and other conflicting patches
5649
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005650installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005651 status_t status = installPatch(
5652 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005653 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005654 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005655 return INVALID_OPERATION;
5656 }
5657 } else {
5658 return BAD_VALUE;
5659 }
5660 } else {
5661 return BAD_VALUE;
5662 }
5663 return NO_ERROR;
5664}
5665
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005666status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005667{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005668 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005669 ssize_t index = mAudioPatches.indexOfKey(handle);
5670
5671 if (index < 0) {
5672 return BAD_VALUE;
5673 }
5674 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005675 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5676 __func__, mUidCached, patchDesc->getUid(), uid);
5677 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005678 return INVALID_OPERATION;
5679 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005680 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5681 for (size_t i = 0; i < mAudioSources.size(); i++) {
5682 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5683 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5684 portId = sourceDesc->portId();
5685 break;
5686 }
5687 }
5688 return portId != AUDIO_PORT_HANDLE_NONE ?
5689 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005690}
Eric Laurent6a94d692014-05-20 11:18:06 -07005691
François Gaffieafd4cea2019-11-18 15:50:22 +01005692status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005693 uint32_t delayMs,
5694 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005695{
5696 ALOGV("%s patch %d", __func__, handle);
5697 if (mAudioPatches.indexOfKey(handle) < 0) {
5698 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5699 return BAD_VALUE;
5700 }
5701 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005702 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005703 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005704 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005705 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005706 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005707 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005708 return BAD_VALUE;
5709 }
5710
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305711 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005712 getNewOutputDevices(outputDesc, true /*fromCache*/),
5713 true,
5714 0,
5715 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005716 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5717 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005718 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005719 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005720 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005721 return BAD_VALUE;
5722 }
5723 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005724 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005725 true,
5726 NULL);
5727 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005728 status_t status =
5729 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5730 ALOGV("%s patch panel returned %d patchHandle %d",
5731 __func__, status, patchDesc->getAfHandle());
5732 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005733 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005734 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005735 // SW or HW Bridge
5736 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5737 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005738 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005739 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5740 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5741 outputDesc = sourceDesc->swOutput().promote();
5742 }
5743 if (outputDesc == nullptr) {
5744 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5745 // releaseOutput has already called closeOutput in case of direct output
5746 return NO_ERROR;
5747 }
François Gaffie7e39df22022-04-26 12:48:49 +02005748 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005749 // While using a HwBridge, force reconsidering device only if not reusing an existing
5750 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005751 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005752 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5753 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5754 // Reconsider device only for cases:
5755 // 1 / Active Output
5756 // 2 / Inactive Output previously hosting HwBridge
5757 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5758 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5759 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305760 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005761 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5762 outputDesc->devices(),
5763 force,
5764 0,
5765 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005766 } else {
5767 return BAD_VALUE;
5768 }
5769 } else {
5770 return BAD_VALUE;
5771 }
5772 return NO_ERROR;
5773}
5774
5775status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5776 struct audio_patch *patches,
5777 unsigned int *generation)
5778{
François Gaffie53615e22015-03-19 09:24:12 +01005779 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005780 return BAD_VALUE;
5781 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005782 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005783 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005784}
5785
Eric Laurente1715a42014-05-20 11:30:42 -07005786status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005787{
Eric Laurente1715a42014-05-20 11:30:42 -07005788 ALOGV("setAudioPortConfig()");
5789
5790 if (config == NULL) {
5791 return BAD_VALUE;
5792 }
5793 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5794 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005795 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5796 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005797 }
5798
Eric Laurenta121f902014-06-03 13:32:54 -07005799 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005800 if (config->type == AUDIO_PORT_TYPE_MIX) {
5801 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005802 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005803 if (outputDesc == NULL) {
5804 return BAD_VALUE;
5805 }
Eric Laurent84c70242014-06-23 08:46:27 -07005806 ALOG_ASSERT(!outputDesc->isDuplicated(),
5807 "setAudioPortConfig() called on duplicated output %d",
5808 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005809 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005810 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005811 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005812 if (inputDesc == NULL) {
5813 return BAD_VALUE;
5814 }
Eric Laurenta121f902014-06-03 13:32:54 -07005815 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005816 } else {
5817 return BAD_VALUE;
5818 }
5819 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5820 sp<DeviceDescriptor> deviceDesc;
5821 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5822 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5823 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5824 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5825 } else {
5826 return BAD_VALUE;
5827 }
5828 if (deviceDesc == NULL) {
5829 return BAD_VALUE;
5830 }
Eric Laurenta121f902014-06-03 13:32:54 -07005831 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005832 } else {
5833 return BAD_VALUE;
5834 }
5835
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005836 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005837 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5838 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005839 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005840 audioPortConfig->toAudioPortConfig(&newConfig, config);
5841 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005842 }
Eric Laurenta121f902014-06-03 13:32:54 -07005843 if (status != NO_ERROR) {
5844 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005845 }
Eric Laurente1715a42014-05-20 11:30:42 -07005846
5847 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005848}
5849
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005850void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5851{
Eric Laurentd60560a2015-04-10 11:31:20 -07005852 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005853 clearAudioPatches(uid);
5854 clearSessionRoutes(uid);
5855}
5856
Eric Laurent6a94d692014-05-20 11:18:06 -07005857void AudioPolicyManager::clearAudioPatches(uid_t uid)
5858{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005859 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005860 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005861 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005862 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005863 }
5864 }
5865}
5866
François Gaffiec005e562018-11-06 15:04:49 +01005867void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005868{
François Gaffiec005e562018-11-06 15:04:49 +01005869 // Take the first attributes following the product strategy as it is used to retrieve the routed
5870 // device. All attributes wihin a strategy follows the same "routing strategy"
5871 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5872 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005873 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005874 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005875 for (size_t j = 0; j < mOutputs.size(); j++) {
5876 if (mOutputs.keyAt(j) == ouptutToSkip) {
5877 continue;
5878 }
5879 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005880 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005881 continue;
5882 }
5883 // If the default device for this strategy is on another output mix,
5884 // invalidate all tracks in this strategy to force re connection.
5885 // Otherwise select new device on the output mix.
5886 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005887 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005888 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005889 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005890 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005891 // If the device is using preferred mixer attributes, the output need to reopen
5892 // with default configuration when the new selected devices are different from
5893 // current routing devices.
5894 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5895 continue;
5896 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305897 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005898 }
5899 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005900 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005901}
5902
5903void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5904{
5905 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005906 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005907 for (size_t i = 0; i < mOutputs.size(); i++) {
5908 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005909 for (const auto& client : outputDesc->getClientIterable()) {
5910 if (client->hasPreferredDevice() && client->uid() == uid) {
5911 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005912 auto clientStrategy = client->strategy();
5913 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5914 end(affectedStrategies)) {
5915 continue;
5916 }
5917 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005918 }
5919 }
5920 }
5921 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005922 for (const auto& strategy : affectedStrategies) {
5923 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005924 }
5925
5926 // remove input routes associated with this uid
5927 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005928 for (size_t i = 0; i < mInputs.size(); i++) {
5929 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005930 for (const auto& client : inputDesc->getClientIterable()) {
5931 if (client->hasPreferredDevice() && client->uid() == uid) {
5932 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5933 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005934 }
5935 }
5936 }
5937 // reroute inputs if necessary
5938 SortedVector<audio_io_handle_t> inputsToClose;
5939 for (size_t i = 0; i < mInputs.size(); i++) {
5940 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005941 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005942 inputsToClose.add(inputDesc->mIoHandle);
5943 }
5944 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005945 for (const auto& input : inputsToClose) {
5946 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005947 }
5948}
5949
Eric Laurentd60560a2015-04-10 11:31:20 -07005950void AudioPolicyManager::clearAudioSources(uid_t uid)
5951{
5952 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005953 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5954 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005955 stopAudioSource(mAudioSources.keyAt(i));
5956 }
5957 }
5958}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005959
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005960status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5961 audio_io_handle_t *ioHandle,
5962 audio_devices_t *device)
5963{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005964 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5965 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005966 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005967 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5968 if (deviceDesc == nullptr) {
5969 return INVALID_OPERATION;
5970 }
5971 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005972
François Gaffiedf372692015-03-19 10:43:27 +01005973 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005974}
5975
Eric Laurentd60560a2015-04-10 11:31:20 -07005976status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005977 const audio_attributes_t *attributes,
5978 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005979 uid_t uid) {
5980 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005981 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005982}
5983
5984status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5985 const audio_attributes_t *attributes,
5986 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005987 uid_t uid, bool internal, bool isCallRx,
5988 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005989{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005990 ALOGV("%s", __FUNCTION__);
5991 *portId = AUDIO_PORT_HANDLE_NONE;
5992
5993 if (source == NULL || attributes == NULL || portId == NULL) {
5994 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5995 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005996 return BAD_VALUE;
5997 }
5998
Eric Laurentd60560a2015-04-10 11:31:20 -07005999 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6000 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006001 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6002 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006003 return INVALID_OPERATION;
6004 }
6005
François Gaffie11d30102018-11-02 16:09:09 +01006006 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006007 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006008 String8(source->ext.device.address),
6009 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006010 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006011 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006012 return BAD_VALUE;
6013 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006014
jiabin4ef93452019-09-10 14:29:54 -07006015 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006016
François Gaffieaaac0fd2018-11-22 17:56:39 +01006017 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006018 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006019 mEngine->getStreamTypeForAttributes(*attributes),
6020 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006021 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006022
David Lif85c5e32024-07-01 13:14:10 +00006023 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006024 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006025 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006026 }
6027 return status;
6028}
6029
David Lif85c5e32024-07-01 13:14:10 +00006030status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6031 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006032{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006033 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006034
6035 // make sure we only have one patch per source.
6036 disconnectAudioSource(sourceDesc);
6037
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006038 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006039 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6040 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6041 sourceDesc->srcDevice()->type(),
6042 String8(sourceDesc->srcDevice()->address().c_str()),
6043 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006044 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006045 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006046 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006047 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006048 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6049 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6050 return INVALID_OPERATION;
6051 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006052 PatchBuilder patchBuilder;
6053 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6054 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006055
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006056 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006057 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006058}
6059
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006061{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006062 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6063 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006064 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006065 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006066 return BAD_VALUE;
6067 }
6068 status_t status = disconnectAudioSource(sourceDesc);
6069
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006070 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006071 return status;
6072}
6073
Andy Hung2ddee192015-12-18 17:34:44 -08006074status_t AudioPolicyManager::setMasterMono(bool mono)
6075{
6076 if (mMasterMono == mono) {
6077 return NO_ERROR;
6078 }
6079 mMasterMono = mono;
6080 // if enabling mono we close all offloaded devices, which will invalidate the
6081 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6082 // for recreating the new AudioTrack as non-offloaded PCM.
6083 //
6084 // If disabling mono, we leave all tracks as is: we don't know which clients
6085 // and tracks are able to be recreated as offloaded. The next "song" should
6086 // play back offloaded.
6087 if (mMasterMono) {
6088 Vector<audio_io_handle_t> offloaded;
6089 for (size_t i = 0; i < mOutputs.size(); ++i) {
6090 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6091 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6092 offloaded.push(desc->mIoHandle);
6093 }
6094 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006095 for (const auto& handle : offloaded) {
6096 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006097 }
6098 }
6099 // update master mono for all remaining outputs
6100 for (size_t i = 0; i < mOutputs.size(); ++i) {
6101 updateMono(mOutputs.keyAt(i));
6102 }
6103 return NO_ERROR;
6104}
6105
6106status_t AudioPolicyManager::getMasterMono(bool *mono)
6107{
6108 *mono = mMasterMono;
6109 return NO_ERROR;
6110}
6111
Eric Laurentac9cef52017-06-09 15:46:26 -07006112float AudioPolicyManager::getStreamVolumeDB(
6113 audio_stream_type_t stream, int index, audio_devices_t device)
6114{
Vlad Popa9d482762024-06-21 16:40:23 -07006115 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6116 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006117}
6118
jiabin81772902018-04-02 17:52:27 -07006119status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6120 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006121 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006122{
Kriti Dang6537def2021-03-02 13:46:59 +01006123 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6124 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006125 return BAD_VALUE;
6126 }
Kriti Dang6537def2021-03-02 13:46:59 +01006127 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6128 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006129
6130 size_t formatsWritten = 0;
6131 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006132
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006133 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006134 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6135 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006136 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006137 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006138 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006139 bool formatEnabled = true;
6140 switch (forceUse) {
6141 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006142 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006143 break;
6144 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6145 formatEnabled = false;
6146 break;
6147 default: // AUTO or ALWAYS => true
6148 break;
jiabin81772902018-04-02 17:52:27 -07006149 }
6150 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6151 }
jiabin81772902018-04-02 17:52:27 -07006152 }
6153 return NO_ERROR;
6154}
6155
Kriti Dang6537def2021-03-02 13:46:59 +01006156status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6157 audio_format_t *surroundFormats) {
6158 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6159 return BAD_VALUE;
6160 }
6161 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6162 __func__, *numSurroundFormats, surroundFormats);
6163
6164 size_t formatsWritten = 0;
6165 size_t formatsMax = *numSurroundFormats;
6166 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6167
6168 // Return formats from all device profiles that have already been resolved by
6169 // checkOutputsForDevice().
6170 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6171 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6172 audio_devices_t deviceType = device->type();
6173 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6174 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006175 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6176 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006177 continue;
6178 }
6179 // Formats reported by sink devices
6180 std::unordered_set<audio_format_t> formatset;
6181 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6182 formatset.insert(it->second.begin(), it->second.end());
6183 }
6184
6185 // Formats hard-coded in the in policy configuration file (if any).
6186 FormatVector encodedFormats = device->encodedFormats();
6187 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6188 // Filter the formats which are supported by the vendor hardware.
6189 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006190 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006191 formats.insert(*it);
6192 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006193 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006194 if (pair.second.count(*it) != 0) {
6195 formats.insert(pair.first);
6196 break;
6197 }
6198 }
6199 }
6200 }
6201 }
6202 *numSurroundFormats = formats.size();
6203 for (const auto& format: formats) {
6204 if (formatsWritten < formatsMax) {
6205 surroundFormats[formatsWritten++] = format;
6206 }
6207 }
6208 return NO_ERROR;
6209}
6210
jiabin81772902018-04-02 17:52:27 -07006211status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6212{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006213 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006214 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6215 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006216 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006217 return BAD_VALUE;
6218 }
6219
Mikhail Naganov100f0122018-11-29 11:22:16 -08006220 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6221 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006222 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006223 return INVALID_OPERATION;
6224 }
6225
Mikhail Naganov100f0122018-11-29 11:22:16 -08006226 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006227 return NO_ERROR;
6228 }
6229
Mikhail Naganov100f0122018-11-29 11:22:16 -08006230 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006231 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006232 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006233 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006234 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006235 }
6236 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006237 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006238 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006239 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006240 }
6241 }
6242
6243 sp<SwAudioOutputDescriptor> outputDesc;
6244 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006245 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6246 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006247 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6248 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006249 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006250 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006251 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006252 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6253 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006254 name.c_str(),
6255 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006256 if (status != NO_ERROR) {
6257 continue;
6258 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006259 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006260 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6261 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006262 name.c_str(),
6263 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006264 profileUpdated |= (status == NO_ERROR);
6265 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006266 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006267 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006268 AUDIO_DEVICE_IN_HDMI);
6269 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6270 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006271 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006272 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006273 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6274 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6275 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006276 name.c_str(),
6277 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006278 if (status != NO_ERROR) {
6279 continue;
6280 }
6281 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6282 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6283 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006284 name.c_str(),
6285 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006286 profileUpdated |= (status == NO_ERROR);
6287 }
6288
jiabin81772902018-04-02 17:52:27 -07006289 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006290 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006291 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006292 }
6293
6294 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6295}
6296
Eric Laurent5ada82e2019-08-29 17:53:54 -07006297void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006298{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006299 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006300 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006301 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006302 }
6303}
6304
jiabin6012f912018-11-02 17:06:30 -07006305bool AudioPolicyManager::isHapticPlaybackSupported()
6306{
6307 for (const auto& hwModule : mHwModules) {
6308 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6309 for (const auto &outProfile : outputProfiles) {
6310 struct audio_port audioPort;
6311 outProfile->toAudioPort(&audioPort);
6312 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6313 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6314 return true;
6315 }
6316 }
6317 }
6318 }
6319 return false;
6320}
6321
Carter Hsu325a8eb2022-01-19 19:56:51 +08006322bool AudioPolicyManager::isUltrasoundSupported()
6323{
6324 bool hasUltrasoundOutput = false;
6325 bool hasUltrasoundInput = false;
6326 for (const auto& hwModule : mHwModules) {
6327 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6328 if (!hasUltrasoundOutput) {
6329 for (const auto &outProfile : outputProfiles) {
6330 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6331 hasUltrasoundOutput = true;
6332 break;
6333 }
6334 }
6335 }
6336
6337 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6338 if (!hasUltrasoundInput) {
6339 for (const auto &inputProfile : inputProfiles) {
6340 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6341 hasUltrasoundInput = true;
6342 break;
6343 }
6344 }
6345 }
6346
6347 if (hasUltrasoundOutput && hasUltrasoundInput)
6348 return true;
6349 }
6350 return false;
6351}
6352
Atneya Nair698f5ef2022-12-15 16:15:09 -08006353bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6354{
6355 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6356 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6357 for (const auto& hwModule : mHwModules) {
6358 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6359 for (const auto &inputProfile : inputProfiles) {
6360 if ((inputProfile->getFlags() & mask) == mask) {
6361 return true;
6362 }
6363 }
6364 }
6365 return false;
6366}
6367
Eric Laurent8340e672019-11-06 11:01:08 -08006368bool AudioPolicyManager::isCallScreenModeSupported()
6369{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006370 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006371}
6372
6373
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006374status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006375{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006376 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006377 if (!sourceDesc->isConnected()) {
6378 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6379 return NO_ERROR;
6380 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006381 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6382 if (swOutput != 0) {
6383 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006384 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006385 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006386 }
jiabinbce0c1d2020-10-05 11:20:18 -07006387 if (releaseOutput(sourceDesc->portId())) {
6388 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6389 // no need to release audio patch here but just return NO_ERROR.
6390 return NO_ERROR;
6391 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006392 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006393 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006394 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006395 // close Hwoutput and remove from mHwOutputs
6396 } else {
6397 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6398 }
6399 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006400 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006401 sourceDesc->disconnect();
6402 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006403}
6404
François Gaffiec005e562018-11-06 15:04:49 +01006405sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6406 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006407{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006408 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006409 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006410 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006411 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006412 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6413 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006414 source = sourceDesc;
6415 break;
6416 }
6417 }
6418 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006419}
6420
Eric Laurentb4f42a92022-01-17 17:37:31 +01006421bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006422 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006423 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006424{
6425 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6426 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006427 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006428 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006429 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6430 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6431 return false;
6432 }
6433 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6434 return false;
6435 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006436 }
6437
Eric Laurentd332bc82023-08-04 11:45:23 +02006438 // The caller can have the audio config criteria ignored by either passing a null ptr or
6439 // the AUDIO_CONFIG_INITIALIZER value.
6440 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006441 // some positional channel masks and PCM format and for stereo if low latency performance
6442 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006443
6444 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006445 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006446 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6447 ? audio_channel_mask_contains_stereo(config->channel_mask)
6448 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006449 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006450 return false;
6451 }
6452 if (!audio_is_linear_pcm(config->format)) {
6453 return false;
6454 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006455 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6456 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6457 return false;
6458 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006459 }
6460
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006461 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006462 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006463 if (profile == nullptr) {
6464 return false;
6465 }
6466
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006467 return true;
6468}
6469
Shunkai Yao4c3af932024-04-26 04:12:21 +00006470// The Spatializer output is compatible with Haptic use cases if:
6471// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6472// with client if client haptic channel bits were set, or
6473// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6474// including the haptic bits or creating the HapticGenerator effect for same session.
6475bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6476 const audio_config_t* config, audio_session_t sessionId) const {
6477 const auto clientHapticChannel =
6478 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6479 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6480 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6481
6482 if (threadOutputHapticChannel) {
6483 // check format and sampleRate match if client haptic channel mask exist
6484 if (clientHapticChannel) {
6485 return mSpatializerOutput->getFormat() == config->format &&
6486 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6487 }
6488 return true;
6489 } else {
6490 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6491 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6492 // HapticGenerator effect for this session) are not supported.
6493 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006494 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006495 }
6496}
6497
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006498void AudioPolicyManager::checkVirtualizerClientRoutes() {
6499 std::set<audio_stream_type_t> streamsToInvalidate;
6500 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006501 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6502 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006503 audio_attributes_t attr = client->attributes();
6504 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6505 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6506 audio_config_base_t clientConfig = client->config();
6507 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006508 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006509 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006510 streamsToInvalidate.insert(client->stream());
6511 }
6512 }
6513 }
6514
jiabinc44b3462022-12-08 12:52:31 -08006515 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006516}
6517
Eric Laurente191d1b2022-04-15 11:59:25 +02006518
6519bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6520 const sp<SwAudioOutputDescriptor>& outputDesc) {
6521 if (outputDesc->isDuplicated()) {
6522 return false;
6523 }
6524 DeviceVector devices = outputDesc->supportedDevices();
6525 for (size_t i = 0; i < mOutputs.size(); i++) {
6526 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6527 if (desc == outputDesc || desc->isDuplicated()) {
6528 continue;
6529 }
6530 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6531 if (!sharedDevices.isEmpty()
6532 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6533 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6534 return false;
6535 }
6536 }
6537 return true;
6538}
6539
6540
Eric Laurentfa0f6742021-08-17 18:39:44 +02006541status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006542 const audio_attributes_t *attr,
6543 audio_io_handle_t *output) {
6544 *output = AUDIO_IO_HANDLE_NONE;
6545
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006546 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6547 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6548 audio_config_t *configPtr = nullptr;
6549 audio_config_t config;
6550 if (mixerConfig != nullptr) {
6551 config = audio_config_initializer(mixerConfig);
6552 configPtr = &config;
6553 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006554 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006555 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006556 return BAD_VALUE;
6557 }
6558
6559 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006560 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006561 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006562 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006563 return BAD_VALUE;
6564 }
6565
Eric Laurente191d1b2022-04-15 11:59:25 +02006566 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006567 for (size_t i = 0; i < mOutputs.size(); i++) {
6568 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006569 if (!desc->isDuplicated()
6570 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6571 spatializerOutputs.push_back(desc);
6572 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006573 }
6574 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006575 mSpatializerOutput.clear();
6576 bool outputsChanged = false;
6577 for (const auto& desc : spatializerOutputs) {
6578 if (desc->mProfile == profile
6579 && (configPtr == nullptr
6580 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6581 mSpatializerOutput = desc;
6582 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6583 } else {
6584 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6585 " and devices %s", __func__, desc->mIoHandle,
6586 configPtr != nullptr ? configPtr->channel_mask : 0,
6587 devices.toString().c_str());
6588 closeOutput(desc->mIoHandle);
6589 outputsChanged = true;
6590 }
Eric Laurent39095982021-08-24 18:29:27 +02006591 }
6592
Eric Laurente191d1b2022-04-15 11:59:25 +02006593 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006594 sp<SwAudioOutputDescriptor> desc =
6595 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006596 if (desc != nullptr) {
6597 mSpatializerOutput = desc;
6598 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006599 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006600 }
6601
6602 checkVirtualizerClientRoutes();
6603
Eric Laurente191d1b2022-04-15 11:59:25 +02006604 if (outputsChanged) {
6605 mPreviousOutputs = mOutputs;
6606 mpClientInterface->onAudioPortListUpdate();
6607 }
6608
6609 if (mSpatializerOutput == nullptr) {
6610 ALOGV("%s could not open spatializer output with requested config", __func__);
6611 return BAD_VALUE;
6612 }
Eric Laurent39095982021-08-24 18:29:27 +02006613 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006614 ALOGV("%s returning new spatializer output %d", __func__, *output);
6615 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006616}
6617
Eric Laurentfa0f6742021-08-17 18:39:44 +02006618status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6619 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006620 return INVALID_OPERATION;
6621 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006622 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006623 return BAD_VALUE;
6624 }
Eric Laurent39095982021-08-24 18:29:27 +02006625
Eric Laurente191d1b2022-04-15 11:59:25 +02006626 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6627 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6628 closeOutput(mSpatializerOutput->mIoHandle);
6629 //from now on mSpatializerOutput is null
6630 checkVirtualizerClientRoutes();
6631 }
Eric Laurent39095982021-08-24 18:29:27 +02006632
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006633 return NO_ERROR;
6634}
6635
Eric Laurente552edb2014-03-10 17:42:56 -07006636// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006637// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006638// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006639uint32_t AudioPolicyManager::nextAudioPortGeneration()
6640{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006641 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006642}
6643
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006644AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006645 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006646 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006647 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006648 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006649 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006650 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006651 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006652 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006653 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006654 mAudioPortGeneration(1),
6655 mBeaconMuteRefCount(0),
6656 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006657 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006658 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006659 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006660 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006661{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006662}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006663
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006664status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006665 if (mEngine == nullptr) {
6666 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006667 }
6668 mEngine->setObserver(this);
6669 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006670 if (status != NO_ERROR) {
6671 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6672 return status;
6673 }
François Gaffie2110e042015-03-24 08:41:51 +01006674
jiabin29230182023-04-04 21:02:36 +00006675 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6676 // at the end of this function.
6677 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006678 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6679 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6680
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006681 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006682 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006683 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006684
Eric Laurent3a4311c2014-03-17 12:00:47 -07006685 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006686 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6687 defaultOutputDevice == nullptr ||
6688 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6689 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6690 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006691 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006692 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006693 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006694
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006695 // Silence ALOGV statements
6696 property_set("log.tag." LOG_TAG, "D");
6697
Eric Laurente552edb2014-03-10 17:42:56 -07006698 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006699 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006700}
6701
Eric Laurente0720872014-03-11 09:30:41 -07006702AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006703{
Eric Laurente552edb2014-03-10 17:42:56 -07006704 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006705 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006706 }
6707 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006708 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006709 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006710 mAvailableOutputDevices.clear();
6711 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006712 mOutputs.clear();
6713 mInputs.clear();
6714 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006715 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006716 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006717}
6718
Eric Laurente0720872014-03-11 09:30:41 -07006719status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006720{
Eric Laurent87ffa392015-05-22 10:32:38 -07006721 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006722}
6723
Eric Laurente552edb2014-03-10 17:42:56 -07006724// ---
6725
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006726void AudioPolicyManager::onNewAudioModulesAvailable()
6727{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006728 DeviceVector newDevices;
6729 onNewAudioModulesAvailableInt(&newDevices);
6730 if (!newDevices.empty()) {
6731 nextAudioPortGeneration();
6732 mpClientInterface->onAudioPortListUpdate();
6733 }
6734}
6735
6736void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6737{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006738 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006739 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6740 continue;
6741 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006742 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006743 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6744 handle != AUDIO_MODULE_HANDLE_NONE) {
6745 hwModule->setHandle(handle);
6746 } else {
6747 ALOGW("could not load HW module %s", hwModule->getName());
6748 continue;
6749 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006750 }
6751 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006752 // open all output streams needed to access attached devices.
6753 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006754 // This also validates mAvailableOutputDevices list
6755 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6756 if (!outProfile->canOpenNewIo()) {
6757 ALOGE("Invalid Output profile max open count %u for profile %s",
6758 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6759 continue;
6760 }
6761 if (!outProfile->hasSupportedDevices()) {
6762 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6763 continue;
6764 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006765 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6766 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006767 mTtsOutputAvailable = true;
6768 }
6769
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006770 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006771 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006772 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006773 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6774 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006775 } else {
6776 // choose first device present in profile's SupportedDevices also part of
6777 // mAvailableOutputDevices.
6778 if (availProfileDevices.isEmpty()) {
6779 continue;
6780 }
6781 supportedDevice = availProfileDevices.itemAt(0);
6782 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006783 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006784 continue;
6785 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306786
6787 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6788 && availProfileDevices.areAllDevicesAttached()) {
6789 ALOGV("%s skip opening output for mmap profile %s", __func__,
6790 outProfile->getTagName().c_str());
6791 continue;
6792 }
6793
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006794 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6795 mpClientInterface);
6796 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006797 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006798 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006799 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6800 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006801 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006802 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006803 if (status != NO_ERROR) {
6804 ALOGW("Cannot open output stream for devices %s on hw module %s",
6805 supportedDevice->toString().c_str(), hwModule->getName());
6806 continue;
6807 }
6808 for (const auto &device : availProfileDevices) {
6809 // give a valid ID to an attached device once confirmed it is reachable
6810 if (!device->isAttached()) {
6811 device->attach(hwModule);
6812 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006813 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006814 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006815 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6816 }
6817 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006818 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006819 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6820 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006821 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006822 }
Eric Laurent39095982021-08-24 18:29:27 +02006823 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006824 outputDesc->close();
6825 } else {
6826 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306827 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006828 DeviceVector(supportedDevice),
6829 true,
6830 0,
6831 NULL);
6832 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006833 }
6834 // open input streams needed to access attached devices to validate
6835 // mAvailableInputDevices list
6836 for (const auto& inProfile : hwModule->getInputProfiles()) {
6837 if (!inProfile->canOpenNewIo()) {
6838 ALOGE("Invalid Input profile max open count %u for profile %s",
6839 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6840 continue;
6841 }
6842 if (!inProfile->hasSupportedDevices()) {
6843 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6844 continue;
6845 }
6846 // chose first device present in profile's SupportedDevices also part of
6847 // available input devices
6848 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006849 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006850 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006851 ALOGV("%s: Input device list is empty! for profile %s",
6852 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006853 continue;
6854 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306855
6856 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6857 && availProfileDevices.areAllDevicesAttached()) {
6858 ALOGV("%s skip opening input for mmap profile %s", __func__,
6859 inProfile->getTagName().c_str());
6860 continue;
6861 }
6862
Eric Laurentc71b11b2024-06-03 12:54:53 +00006863 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6864 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006865
6866 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6867 status_t status = inputDesc->open(nullptr,
6868 availProfileDevices.itemAt(0),
6869 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306870 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006871 &input);
6872 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306873 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6874 __func__, availProfileDevices.toString().c_str(),
6875 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006876 continue;
6877 }
6878 for (const auto &device : availProfileDevices) {
6879 // give a valid ID to an attached device once confirmed it is reachable
6880 if (!device->isAttached()) {
6881 device->attach(hwModule);
6882 device->importAudioPortAndPickAudioProfile(inProfile, true);
6883 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006884 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006885 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6886 }
6887 }
6888 inputDesc->close();
6889 }
6890 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006891
6892 // Check if spatializer outputs can be closed until used.
6893 // mOutputs vector never contains duplicated outputs at this point.
6894 std::vector<audio_io_handle_t> outputsClosed;
6895 for (size_t i = 0; i < mOutputs.size(); i++) {
6896 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6897 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6898 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6899 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006900 nextAudioPortGeneration();
6901 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6902 if (index >= 0) {
6903 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6904 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6905 patchDesc->getAfHandle(), 0);
6906 mAudioPatches.removeItemsAt(index);
6907 mpClientInterface->onAudioPatchListUpdate();
6908 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006909 desc->close();
6910 }
6911 }
6912 for (auto output : outputsClosed) {
6913 removeOutput(output);
6914 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006915}
6916
Eric Laurent98e38192018-02-15 18:31:53 -08006917void AudioPolicyManager::addOutput(audio_io_handle_t output,
6918 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006919{
Eric Laurent1c333e22014-05-20 10:48:17 -07006920 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006921 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006922 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006923 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006924 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006925}
6926
François Gaffie53615e22015-03-19 09:24:12 +01006927void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6928{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006929 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6930 ALOGV("%s: removing primary output", __func__);
6931 mPrimaryOutput = nullptr;
6932 }
François Gaffie53615e22015-03-19 09:24:12 +01006933 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006934 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006935}
6936
Eric Laurent98e38192018-02-15 18:31:53 -08006937void AudioPolicyManager::addInput(audio_io_handle_t input,
6938 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006939{
Eric Laurent1c333e22014-05-20 10:48:17 -07006940 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006941 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006942}
Eric Laurente552edb2014-03-10 17:42:56 -07006943
François Gaffie11d30102018-11-02 16:09:09 +01006944status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006945 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006946 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006947{
François Gaffie11d30102018-11-02 16:09:09 +01006948 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006949 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006950 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006951
François Gaffie11d30102018-11-02 16:09:09 +01006952 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006953 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006954 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006955 }
Eric Laurente552edb2014-03-10 17:42:56 -07006956
Eric Laurent3b73df72014-03-11 09:06:29 -07006957 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006958 // first call getAudioPort to get the supported attributes from the HAL
6959 struct audio_port_v7 port = {};
6960 device->toAudioPort(&port);
6961 status_t status = mpClientInterface->getAudioPort(&port);
6962 if (status == NO_ERROR) {
6963 device->importAudioPort(port);
6964 }
6965
6966 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006967 for (size_t i = 0; i < mOutputs.size(); i++) {
6968 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006969 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006970 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006971 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6972 mOutputs.keyAt(i), device->toString().c_str());
6973 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006974 }
6975 }
6976 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006977 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006978 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006979 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6980 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006981 if (profile->supportsDevice(device)) {
6982 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306983 ALOGV("%s(): adding profile %s from module %s",
6984 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006985 }
6986 }
6987 }
6988
Eric Laurent7b279bb2015-12-14 10:18:23 -08006989 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006990
Eric Laurente552edb2014-03-10 17:42:56 -07006991 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006992 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006993 return BAD_VALUE;
6994 }
6995
6996 // open outputs for matching profiles if needed. Direct outputs are also opened to
6997 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6998 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006999 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007000
7001 // nothing to do if one output is already opened for this profile
7002 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007003 for (j = 0; j < outputs.size(); j++) {
7004 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007005 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007006 // matching profile: save the sample rates, format and channel masks supported
7007 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007008 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007009 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007010 }
Eric Laurente552edb2014-03-10 17:42:56 -07007011 break;
7012 }
7013 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007014 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007015 continue;
7016 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307017 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7018 ALOGV("%s skip opening output for mmap profile %s",
7019 __func__, profile->getTagName().c_str());
7020 continue;
7021 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007022 if (!profile->canOpenNewIo()) {
7023 ALOGW("Max Output number %u already opened for this profile %s",
7024 profile->maxOpenCount, profile->getTagName().c_str());
7025 continue;
7026 }
7027
Eric Laurent83efe1c2017-07-09 16:51:08 -07007028 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007029 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007030 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7031 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007032 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007033 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007034 profiles.removeAt(profile_index);
7035 profile_index--;
7036 } else {
7037 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007038 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007039 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007040 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7041 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007042 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007043 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007044
François Gaffie11d30102018-11-02 16:09:09 +01007045 if (device_distinguishes_on_address(deviceType)) {
7046 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7047 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307048 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7049 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007050 }
Eric Laurente552edb2014-03-10 17:42:56 -07007051 ALOGV("checkOutputsForDevice(): adding output %d", output);
7052 }
7053 }
7054
7055 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007056 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007057 return BAD_VALUE;
7058 }
Eric Laurentd4692962014-05-05 18:13:44 -07007059 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007060 // check if one opened output is not needed any more after disconnecting one device
7061 for (size_t i = 0; i < mOutputs.size(); i++) {
7062 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007063 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007064 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007065 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007066 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007067 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007068 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007069 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7070 mOutputs.keyAt(i));
7071 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007072 }
Eric Laurente552edb2014-03-10 17:42:56 -07007073 }
7074 }
Eric Laurentd4692962014-05-05 18:13:44 -07007075 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007076 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007077 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7078 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007079 if (!profile->supportsDevice(device)) {
7080 continue;
7081 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307082 ALOGV("%s(): clearing direct output profile %s on module %s",
7083 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007084 profile->clearAudioProfiles();
7085 if (!profile->hasDynamicAudioProfile()) {
7086 continue;
7087 }
7088 // When a device is disconnected, if there is an IOProfile that contains dynamic
7089 // profiles and supports the disconnected device, call getAudioPort to repopulate
7090 // the capabilities of the devices that is supported by the IOProfile.
7091 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7092 if (supportedDevice == device ||
7093 !mAvailableOutputDevices.contains(supportedDevice)) {
7094 continue;
7095 }
7096 struct audio_port_v7 port;
7097 supportedDevice->toAudioPort(&port);
7098 status_t status = mpClientInterface->getAudioPort(&port);
7099 if (status == NO_ERROR) {
7100 supportedDevice->importAudioPort(port);
7101 }
Eric Laurente552edb2014-03-10 17:42:56 -07007102 }
7103 }
7104 }
7105 }
7106 return NO_ERROR;
7107}
7108
François Gaffie11d30102018-11-02 16:09:09 +01007109status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007110 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007111{
François Gaffie11d30102018-11-02 16:09:09 +01007112 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007113 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007114 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007115 }
7116
Eric Laurentd4692962014-05-05 18:13:44 -07007117 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007118 sp<AudioInputDescriptor> desc;
7119
jiabinbf5f4262023-04-12 21:48:34 +00007120 // first call getAudioPort to get the supported attributes from the HAL
7121 struct audio_port_v7 port = {};
7122 device->toAudioPort(&port);
7123 status_t status = mpClientInterface->getAudioPort(&port);
7124 if (status == NO_ERROR) {
7125 device->importAudioPort(port);
7126 }
7127
Eric Laurent0dd51852019-04-19 18:18:58 -07007128 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007129 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007130 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007131 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007132 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007133 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007134 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007135
François Gaffie11d30102018-11-02 16:09:09 +01007136 if (profile->supportsDevice(device)) {
7137 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307138 ALOGV("%s : adding profile %s from module %s", __func__,
7139 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007140 }
7141 }
7142 }
7143
Eric Laurent0dd51852019-04-19 18:18:58 -07007144 if (profiles.isEmpty()) {
7145 ALOGW("%s: No input profile available for device %s",
7146 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007147 return BAD_VALUE;
7148 }
7149
7150 // open inputs for matching profiles if needed. Direct inputs are also opened to
7151 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7152 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7153
Eric Laurent1c333e22014-05-20 10:48:17 -07007154 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007155
Eric Laurentd4692962014-05-05 18:13:44 -07007156 // nothing to do if one input is already opened for this profile
7157 size_t input_index;
7158 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7159 desc = mInputs.valueAt(input_index);
7160 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007161 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007162 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007163 }
Eric Laurentd4692962014-05-05 18:13:44 -07007164 break;
7165 }
7166 }
7167 if (input_index != mInputs.size()) {
7168 continue;
7169 }
7170
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307171 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7172 ALOGV("%s skip opening input for mmap profile %s",
7173 __func__, profile->getTagName().c_str());
7174 continue;
7175 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007176 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307177 ALOGW("%s Max Input number %u already opened for this profile %s",
7178 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007179 continue;
7180 }
7181
Eric Laurentc71b11b2024-06-03 12:54:53 +00007182 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007183 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307184 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307185 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7186 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007187
Eric Laurentcf2c0212014-07-25 16:20:43 -07007188 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007189 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007190 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007191 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007192 mpClientInterface->setParameters(input, String8(param));
7193 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007194 }
jiabin12537fc2023-10-12 17:56:08 +00007195 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007196 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307197 ALOGW("%s direct input missing param for profile %s", __func__,
7198 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007199 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007200 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007201 }
7202
Eric Laurent0dd51852019-04-19 18:18:58 -07007203 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007204 addInput(input, desc);
7205 }
7206 } // endif input != 0
7207
Eric Laurentcf2c0212014-07-25 16:20:43 -07007208 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307209 ALOGW("%s could not open input for device %s on profile %s", __func__,
7210 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007211 profiles.removeAt(profile_index);
7212 profile_index--;
7213 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007214 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007215 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007216 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307217 ALOGV("%s: adding input %d for profile %s", __func__,
7218 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007219
7220 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307221 ALOGV("%s: closing input %d for profile %s", __func__,
7222 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007223 closeInput(input);
7224 }
Eric Laurentd4692962014-05-05 18:13:44 -07007225 }
7226 } // end scan profiles
7227
7228 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007229 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007230 return BAD_VALUE;
7231 }
7232 } else {
7233 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007234 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007235 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007236 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007237 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007238 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007239 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007240 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307241 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7242 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007243 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007244 }
7245 }
7246 }
7247 } // end disconnect
7248
7249 return NO_ERROR;
7250}
7251
7252
Eric Laurente0720872014-03-11 09:30:41 -07007253void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007254{
7255 ALOGV("closeOutput(%d)", output);
7256
François Gaffie1c878552018-11-22 16:53:21 +01007257 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7258 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007259 ALOGW("closeOutput() unknown output %d", output);
7260 return;
7261 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007262 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007263 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007264
Eric Laurente552edb2014-03-10 17:42:56 -07007265 // look for duplicated outputs connected to the output being removed.
7266 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007267 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7268 if (dupOutput->isDuplicated() &&
7269 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7270 sp<SwAudioOutputDescriptor> remainingOutput =
7271 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007272 // As all active tracks on duplicated output will be deleted,
7273 // and as they were also referenced on the other output, the reference
7274 // count for their stream type must be adjusted accordingly on
7275 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007276 const bool wasActive = remainingOutput->isActive();
7277 // Note: no-op on the closing output where all clients has already been set inactive
7278 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007279 // stop() will be a no op if the output is still active but is needed in case all
7280 // active streams refcounts where cleared above
7281 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007282 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007283 }
Eric Laurente552edb2014-03-10 17:42:56 -07007284 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7285 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7286
7287 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007288 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007289 }
7290 }
7291
Eric Laurent05b90f82014-08-27 15:32:29 -07007292 nextAudioPortGeneration();
7293
François Gaffie1c878552018-11-22 16:53:21 +01007294 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007295 if (index >= 0) {
7296 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007297 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7298 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007299 mAudioPatches.removeItemsAt(index);
7300 mpClientInterface->onAudioPatchListUpdate();
7301 }
7302
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007303 if (closingOutputWasActive) {
7304 closingOutput->stop();
7305 }
François Gaffie1c878552018-11-22 16:53:21 +01007306 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007307 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007308 for (const auto device : closingOutput->devices()) {
7309 device->setPreferredConfig(nullptr);
7310 }
7311 }
Eric Laurente552edb2014-03-10 17:42:56 -07007312
François Gaffie53615e22015-03-19 09:24:12 +01007313 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007314 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007315 if (closingOutput == mSpatializerOutput) {
7316 mSpatializerOutput.clear();
7317 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007318
7319 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7320 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007321 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007322 bool directOutputOpen = false;
7323 for (size_t i = 0; i < mOutputs.size(); i++) {
7324 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7325 directOutputOpen = true;
7326 break;
7327 }
7328 }
7329 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007330 ALOGV("no direct outputs open, reset MSD patches");
7331 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7332 // how output devices for patching are resolved. Avoid by caching and reusing the
7333 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7334 // devices to patch to. This may be complicated by the fact that devices may become
7335 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007336 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007337 }
7338 }
jiabin220eea12024-05-17 17:55:20 +00007339
7340 if (closingOutput->mPreferredAttrInfo != nullptr) {
7341 closingOutput->mPreferredAttrInfo->resetActiveClient();
7342 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007343}
7344
7345void AudioPolicyManager::closeInput(audio_io_handle_t input)
7346{
7347 ALOGV("closeInput(%d)", input);
7348
7349 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7350 if (inputDesc == NULL) {
7351 ALOGW("closeInput() unknown input %d", input);
7352 return;
7353 }
7354
Eric Laurent6a94d692014-05-20 11:18:06 -07007355 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007356
François Gaffie11d30102018-11-02 16:09:09 +01007357 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007358 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007359 if (index >= 0) {
7360 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007361 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7362 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007363 mAudioPatches.removeItemsAt(index);
7364 mpClientInterface->onAudioPatchListUpdate();
7365 }
7366
François Gaffie6ebbce02023-07-19 13:27:53 +02007367 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007368 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007369 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007370
François Gaffie11d30102018-11-02 16:09:09 +01007371 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7372 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007373 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007374 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007375 }
Eric Laurente552edb2014-03-10 17:42:56 -07007376}
7377
François Gaffie11d30102018-11-02 16:09:09 +01007378SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7379 const DeviceVector &devices,
7380 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007381{
7382 SortedVector<audio_io_handle_t> outputs;
7383
François Gaffie11d30102018-11-02 16:09:09 +01007384 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007385 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007386 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007387 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007388 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007389 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007390 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007391 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007392 outputs.add(openOutputs.keyAt(i));
7393 }
7394 }
7395 return outputs;
7396}
7397
Mikhail Naganov37977152018-07-11 15:54:44 -07007398void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7399{
7400 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7401 // output is suspended before any tracks are moved to it
7402 checkA2dpSuspend();
7403 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007404 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007405 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007406 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007407 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007408 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7409 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7410 // configuration changes will ultimately be rerouted correctly. We can still avoid
7411 // unnecessary rerouting by caching and reusing the arguments to
7412 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7413 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007414 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007415 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007416 // an event that changed routing likely occurred, inform upper layers
7417 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007418}
7419
François Gaffiec005e562018-11-06 15:04:49 +01007420bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7421 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007422{
François Gaffiec005e562018-11-06 15:04:49 +01007423 return mEngine->getProductStrategyForAttributes(lAttr) ==
7424 mEngine->getProductStrategyForAttributes(rAttr);
7425}
7426
Francois Gaffieff1eb522020-05-06 18:37:04 +02007427void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7428{
7429 for (size_t i = 0; i < mAudioSources.size(); i++) {
7430 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7431 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007432 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007433 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007434 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007435 }
7436 }
7437}
7438
7439void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7440{
7441 for (size_t i = 0; i < mAudioSources.size(); i++) {
7442 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7443 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7444 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7445 disconnectAudioSource(sourceDesc);
7446 }
7447 }
7448}
7449
François Gaffiec005e562018-11-06 15:04:49 +01007450void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7451{
7452 auto psId = mEngine->getProductStrategyForAttributes(attr);
7453
7454 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7455 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007456
François Gaffie11d30102018-11-02 16:09:09 +01007457 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7458 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007459
Eric Laurentc209fe42020-06-05 18:11:23 -07007460 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007461 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007462 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007463 // take into account dynamic audio policies related changes: if a client is now associated
7464 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007465 // invalidate clients on outputs that do not support all the newly selected devices for the
7466 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007467 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007468 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007469 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007470 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007471 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007472
Eric Laurentc209fe42020-06-05 18:11:23 -07007473 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7474 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7475 continue;
7476 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007477 if (!desc->supportsAllDevices(newDevices)) {
7478 invalidatedOutputs.push_back(desc);
7479 break;
7480 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007481 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007482 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007483 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7484 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7485 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007486 if (status == OK) {
7487 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7488 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7489 maxLatency = desc->latency();
7490 }
7491 invalidatedOutputs.push_back(desc);
7492 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007493 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007494 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007495 }
7496 }
7497
Eric Laurent56ed8842022-11-15 16:04:41 +01007498 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007499 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7500 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007501 for (audio_io_handle_t srcOut : srcOutputs) {
7502 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007503 if (desc == nullptr) continue;
7504
7505 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007506 maxLatency = desc->latency();
7507 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007508
Eric Laurent56ed8842022-11-15 16:04:41 +01007509 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007510 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007511 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007512 // a client on a non direct outputs has necessarily a linear PCM format
7513 // so we can call selectOutput() safely
7514 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7515 client->flags(),
7516 client->config().format,
7517 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007518 client->config().sample_rate,
7519 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007520 if (newOutput != srcOut) {
7521 invalidate = true;
7522 break;
7523 }
7524 } else {
7525 sp<IOProfile> profile = getProfileForOutput(newDevices,
7526 client->config().sample_rate,
7527 client->config().format,
7528 client->config().channel_mask,
7529 client->flags(),
7530 true /* directOnly */);
7531 if (profile != desc->mProfile) {
7532 invalidate = true;
7533 break;
7534 }
7535 }
7536 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007537 // mute strategy while moving tracks from one output to another
7538 if (invalidate) {
7539 invalidatedOutputs.push_back(desc);
7540 if (desc->isStrategyActive(psId)) {
7541 setStrategyMute(psId, true, desc);
7542 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7543 newDevices.types());
7544 }
Eric Laurente552edb2014-03-10 17:42:56 -07007545 }
François Gaffiec005e562018-11-06 15:04:49 +01007546 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007547 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007548 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007549 }
Eric Laurente552edb2014-03-10 17:42:56 -07007550 }
7551
Eric Laurent56ed8842022-11-15 16:04:41 +01007552 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7553 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7554 std::to_string(srcOutputs[0]).c_str(),
7555 std::to_string(dstOutputs[0]).c_str());
7556
François Gaffiec005e562018-11-06 15:04:49 +01007557 // Move effects associated to this stream from previous output to new output
7558 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007559 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007560 }
François Gaffiec005e562018-11-06 15:04:49 +01007561 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007562 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007563 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007564 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007565 desc->setTracksInvalidatedStatusByStrategy(psId);
7566 }
Eric Laurente552edb2014-03-10 17:42:56 -07007567 }
7568 }
7569}
7570
Eric Laurente0720872014-03-11 09:30:41 -07007571void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007572{
François Gaffiec005e562018-11-06 15:04:49 +01007573 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7574 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7575 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007576 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007577 }
Eric Laurente552edb2014-03-10 17:42:56 -07007578}
7579
Kevin Rocard153f92d2018-12-18 18:33:28 -08007580void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007581 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007582 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007583 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007584 for (size_t i = 0; i < mOutputs.size(); i++) {
7585 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7586 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007587 sp<AudioPolicyMix> primaryMix;
7588 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007589 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007590 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7591 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7592 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007593 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7594 for (auto &secondaryMix : secondaryMixes) {
7595 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7596 if (outputDesc != nullptr &&
7597 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7598 secondaryDescs.push_back(outputDesc);
7599 }
7600 }
7601
jiabinc44b3462022-12-08 12:52:31 -08007602 if (status != OK &&
7603 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7604 // When it failed to query secondary output, only invalidate the client that is not
7605 // MMAP. The reason is that MMAP stream will not support secondary output.
7606 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007607 } else if (!std::equal(
7608 client->getSecondaryOutputs().begin(),
7609 client->getSecondaryOutputs().end(),
7610 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007611 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7612 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007613 // If the format is not PCM, the tracks should be invalidated to get correct
7614 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007615 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007616 } else {
7617 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7618 std::vector<audio_io_handle_t> secondaryOutputIds;
7619 for (const auto &secondaryDesc: secondaryDescs) {
7620 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7621 weakSecondaryDescs.push_back(secondaryDesc);
7622 }
7623 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7624 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007625 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007626 }
7627 }
7628 }
jiabin10a03f12021-05-07 23:46:28 +00007629 if (!trackSecondaryOutputs.empty()) {
7630 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7631 }
jiabinc44b3462022-12-08 12:52:31 -08007632 if (!clientsToInvalidate.empty()) {
7633 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7634 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007635 }
7636}
7637
Eric Laurent2517af32020-11-25 15:31:27 +01007638bool AudioPolicyManager::isScoRequestedForComm() const {
7639 AudioDeviceTypeAddrVector devices;
7640 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7641 for (const auto &device : devices) {
7642 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7643 return true;
7644 }
7645 }
7646 return false;
7647}
7648
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007649bool AudioPolicyManager::isHearingAidUsedForComm() const {
7650 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7651 true /*fromCache*/);
7652 for (const auto &device : devices) {
7653 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7654 return true;
7655 }
7656 }
7657 return false;
7658}
7659
7660
Eric Laurente0720872014-03-11 09:30:41 -07007661void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007662{
François Gaffie53615e22015-03-19 09:24:12 +01007663 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007664 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007665 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007666 return;
7667 }
7668
Eric Laurent3a4311c2014-03-17 12:00:47 -07007669 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007670 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7671 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007672 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007673
7674 // if suspended, restore A2DP output if:
7675 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007676 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007677 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007678 //
Eric Laurentf732e072016-08-03 19:30:28 -07007679 // if not suspended, suspend A2DP output if:
7680 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007681 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007682 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007683 //
7684 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007685 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007686 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007687 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007688 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007689
7690 mpClientInterface->restoreOutput(a2dpOutput);
7691 mA2dpSuspended = false;
7692 }
7693 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007694 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007695 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007696 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007697 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007698
7699 mpClientInterface->suspendOutput(a2dpOutput);
7700 mA2dpSuspended = true;
7701 }
7702 }
7703}
7704
François Gaffie11d30102018-11-02 16:09:09 +01007705DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7706 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007707{
François Gaffiedb1755b2023-09-01 11:50:35 +02007708 if (outputDesc == nullptr) {
7709 return DeviceVector{};
7710 }
François Gaffie11d30102018-11-02 16:09:09 +01007711
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007712 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007713 if (index >= 0) {
7714 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007715 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007716 ALOGV("%s device %s forced by patch %d", __func__,
7717 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7718 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007719 }
7720 }
7721
Dean Wheatley514b4312020-06-17 21:45:00 +10007722 // Do not retrieve engine device for outputs through MSD
7723 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7724 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7725 return outputDesc->devices();
7726 }
7727
Eric Laurent97ac8712018-07-27 18:59:02 -07007728 // Honor explicit routing requests only if no client using default routing is active on this
7729 // input: a specific app can not force routing for other apps by setting a preferred device.
7730 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007731 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007732 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007733 if (device != nullptr) {
7734 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007735 }
7736
François Gaffiea807ef92018-11-05 10:44:33 +01007737 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7738 // of setForceUse / Default Bus device here
7739 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7740 if (device != nullptr) {
7741 return DeviceVector(device);
7742 }
7743
François Gaffiedb1755b2023-09-01 11:50:35 +02007744 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007745 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7746 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307747 auto hasStreamActive = [&](auto stream) {
7748 return hasStream(streams, stream) && isStreamActive(stream, 0);
7749 };
Eric Laurent484e9272018-06-07 17:29:23 -07007750
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307751 auto doGetOutputDevicesForVoice = [&]() {
7752 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007753 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307754 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007755 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7756 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307757 };
7758
7759 // With low-latency playing on speaker, music on WFD, when the first low-latency
7760 // output is stopped, getNewOutputDevices checks for a product strategy
7761 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007762 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307763 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7764 // stream is associated to the output descriptor.
7765 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7766 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7767 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7768 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007769 // Retrieval of devices for voice DL is done on primary output profile, cannot
7770 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007771 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007772 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7773 break;
7774 }
Eric Laurente552edb2014-03-10 17:42:56 -07007775 }
François Gaffiec005e562018-11-06 15:04:49 +01007776 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007777 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007778}
7779
François Gaffie11d30102018-11-02 16:09:09 +01007780sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7781 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007782{
François Gaffie11d30102018-11-02 16:09:09 +01007783 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007784
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007785 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007786 if (index >= 0) {
7787 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007788 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007789 ALOGV("getNewInputDevice() device %s forced by patch %d",
7790 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7791 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007792 }
7793 }
7794
Eric Laurent97ac8712018-07-27 18:59:02 -07007795 // Honor explicit routing requests only if no client using default routing is active on this
7796 // input: a specific app can not force routing for other apps by setting a preferred device.
7797 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007798 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7799 if (device != nullptr) {
7800 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007801 }
7802
Eric Laurentdc95a252018-04-12 12:46:56 -07007803 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007804 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007805 audio_attributes_t attributes;
7806 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007807 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007808 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7809 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007810 attributes = topClient->attributes();
7811 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007812 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007813 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007814 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7815 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007816 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007817 }
7818
Francois Gaffie716e1432019-01-14 16:58:59 +01007819 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7820 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007821 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007822 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007823 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007824 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007825
Eric Laurente552edb2014-03-10 17:42:56 -07007826 return device;
7827}
7828
Eric Laurent794fde22016-03-11 09:50:45 -08007829bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7830 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007831 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007832}
7833
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007834status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007835 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007836 if (devices == nullptr) {
7837 return BAD_VALUE;
7838 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007839
Andy Hung6d23c0f2022-02-16 09:37:15 -08007840 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007841 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7842 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007843 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007844 for (const auto& device : curDevices) {
7845 devices->push_back(device->getDeviceTypeAddr());
7846 }
7847 return NO_ERROR;
7848}
7849
Eric Laurente0720872014-03-11 09:30:41 -07007850void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007851 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007852 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007853 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007854 updateDevicesAndOutputs();
7855 break;
7856 default:
7857 break;
7858 }
7859}
7860
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007861uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007862
7863 // skip beacon mute management if a dedicated TTS output is available
7864 if (mTtsOutputAvailable) {
7865 return 0;
7866 }
7867
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007868 switch(event) {
7869 case STARTING_OUTPUT:
7870 mBeaconMuteRefCount++;
7871 break;
7872 case STOPPING_OUTPUT:
7873 if (mBeaconMuteRefCount > 0) {
7874 mBeaconMuteRefCount--;
7875 }
7876 break;
7877 case STARTING_BEACON:
7878 mBeaconPlayingRefCount++;
7879 break;
7880 case STOPPING_BEACON:
7881 if (mBeaconPlayingRefCount > 0) {
7882 mBeaconPlayingRefCount--;
7883 }
7884 break;
7885 }
7886
7887 if (mBeaconMuteRefCount > 0) {
7888 // any playback causes beacon to be muted
7889 return setBeaconMute(true);
7890 } else {
7891 // no other playback: unmute when beacon starts playing, mute when it stops
7892 return setBeaconMute(mBeaconPlayingRefCount == 0);
7893 }
7894}
7895
7896uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7897 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7898 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7899 // keep track of muted state to avoid repeating mute/unmute operations
7900 if (mBeaconMuted != mute) {
7901 // mute/unmute AUDIO_STREAM_TTS on all outputs
7902 ALOGV("\t muting %d", mute);
7903 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007904 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7905 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7906 ALOGV("\t no tts volume source available");
7907 return 0;
7908 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007909 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007910 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007911 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7912 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007913 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007914 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007915 maxLatency = latency;
7916 }
7917 }
7918 mBeaconMuted = mute;
7919 return maxLatency;
7920 }
7921 return 0;
7922}
7923
Eric Laurente0720872014-03-11 09:30:41 -07007924void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007925{
François Gaffiec005e562018-11-06 15:04:49 +01007926 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007927 mPreviousOutputs = mOutputs;
7928}
7929
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007930uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007931 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007932 uint32_t delayMs)
7933{
7934 // mute/unmute strategies using an incompatible device combination
7935 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7936 // if unmuting, unmute only after the specified delay
7937 if (outputDesc->isDuplicated()) {
7938 return 0;
7939 }
7940
7941 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007942 DeviceVector devices = outputDesc->devices();
7943 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007944
François Gaffiec005e562018-11-06 15:04:49 +01007945 auto productStrategies = mEngine->getOrderedProductStrategies();
7946 for (const auto &productStrategy : productStrategies) {
7947 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7948 DeviceVector curDevices =
7949 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7950 curDevices = curDevices.filter(outputDesc->supportedDevices());
7951 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007952 bool doMute = false;
7953
François Gaffiec005e562018-11-06 15:04:49 +01007954 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007955 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007956 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7957 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007958 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007959 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007960 }
Eric Laurent99401132014-05-07 19:48:15 -07007961 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007962 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007963 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007964 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007965 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007966 continue;
7967 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307968 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007969 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7970 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7971 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007972 if (mute) {
7973 // FIXME: should not need to double latency if volume could be applied
7974 // immediately by the audioflinger mixer. We must account for the delay
7975 // between now and the next time the audioflinger thread for this output
7976 // will process a buffer (which corresponds to one buffer size,
7977 // usually 1/2 or 1/4 of the latency).
7978 if (muteWaitMs < desc->latency() * 2) {
7979 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007980 }
7981 }
7982 }
7983 }
7984 }
7985 }
7986
Eric Laurent99401132014-05-07 19:48:15 -07007987 // temporary mute output if device selection changes to avoid volume bursts due to
7988 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007989 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007990 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007991
Eric Laurentdc462862016-07-19 12:29:53 -07007992 if (muteWaitMs < tempMuteWaitMs) {
7993 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007994 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007995
7996 // If recommended duration is defined, replace temporary mute duration to avoid
7997 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7998 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7999 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8000 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8001 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8002
François Gaffieaaac0fd2018-11-22 17:56:39 +01008003 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8004 // make sure that we do not start the temporary mute period too early in case of
8005 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008006 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8007 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8008 delayMs + tempMuteDurationMs,
8009 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008010 }
8011 }
8012
Eric Laurente552edb2014-03-10 17:42:56 -07008013 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8014 if (muteWaitMs > delayMs) {
8015 muteWaitMs -= delayMs;
8016 usleep(muteWaitMs * 1000);
8017 return muteWaitMs;
8018 }
8019 return 0;
8020}
8021
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308022uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8023 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008024 const DeviceVector &devices,
8025 bool force,
8026 int delayMs,
8027 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008028 bool requiresMuteCheck, bool requiresVolumeCheck,
8029 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008030{
jiabin3ff8d7d2022-12-13 06:27:44 +00008031 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308032 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8033 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8034 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008035 uint32_t muteWaitMs;
8036
8037 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308038 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008039 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308040 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008041 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008042 return muteWaitMs;
8043 }
Eric Laurente552edb2014-03-10 17:42:56 -07008044
8045 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008046 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008047 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008048 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008049
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308050 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8051 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008052
8053 if (!filteredDevices.isEmpty()) {
8054 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008055 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008056
8057 // if the outputs are not materially active, there is no need to mute.
8058 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008059 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008060 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308061 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8062 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008063 muteWaitMs = 0;
8064 }
Eric Laurente552edb2014-03-10 17:42:56 -07008065
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008066 bool outputRouted = outputDesc->isRouted();
8067
Eric Laurent79ea9582020-06-11 18:49:24 -07008068 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8069 // output profile or if new device is not supported AND previous device(s) is(are) still
8070 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008071 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308072 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8073 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008074 // restore previous device after evaluating strategy mute state
8075 outputDesc->setDevices(prevDevices);
8076 return muteWaitMs;
8077 }
8078
Eric Laurente552edb2014-03-10 17:42:56 -07008079 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008080 // the requested device is AUDIO_DEVICE_NONE
8081 // OR the requested device is the same as current device
8082 // AND force is not specified
8083 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008084 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008085 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308086 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8087 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8088 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008089 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308090 ALOGV("%s %s setting same device on routed output, force apply volumes",
8091 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008092 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8093 }
Eric Laurente552edb2014-03-10 17:42:56 -07008094 return muteWaitMs;
8095 }
8096
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308097 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8098 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008099
Eric Laurente552edb2014-03-10 17:42:56 -07008100 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008101 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008102 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008103 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008104 PatchBuilder patchBuilder;
8105 patchBuilder.addSource(outputDesc);
8106 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8107 for (const auto &filteredDevice : filteredDevices) {
8108 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008109 }
8110
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008111 // Add half reported latency to delayMs when muteWaitMs is null in order
8112 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008113 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8114 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8115 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008116 }
Eric Laurente552edb2014-03-10 17:42:56 -07008117
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008118 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8119 if (!skipMuteDelay) {
8120 // update stream volumes according to new device
8121 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8122 }
Eric Laurente552edb2014-03-10 17:42:56 -07008123
8124 return muteWaitMs;
8125}
8126
Eric Laurentc75307b2015-03-17 15:29:32 -07008127status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008128 int delayMs,
8129 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008130{
Eric Laurent6a94d692014-05-20 11:18:06 -07008131 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008132 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8133 return INVALID_OPERATION;
8134 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008135 if (patchHandle) {
8136 index = mAudioPatches.indexOfKey(*patchHandle);
8137 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008138 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008139 }
8140 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008141 return INVALID_OPERATION;
8142 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008143 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008144 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008145 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008146 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008147 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008148 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008149 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008150 return status;
8151}
8152
8153status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008154 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008155 bool force,
8156 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008157{
8158 status_t status = NO_ERROR;
8159
Eric Laurent1f2f2232014-06-02 12:01:23 -07008160 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008161 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8162 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008163
François Gaffie11d30102018-11-02 16:09:09 +01008164 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008165 PatchBuilder patchBuilder;
8166 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008167 // AUDIO_SOURCE_HOTWORD is for internal use only:
8168 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008169 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8170 auto result = usecase;
8171 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8172 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8173 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008174 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008175 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008176 if (audio_is_remote_submix_device(device->type())) {
8177 // remote submix HAL does not support audio conversion, need source device
8178 // audio config to match the sink input descriptor audio config, otherwise AIDL
8179 // HAL patching will fail
8180 audio_port_config srcDevicePortConfig = {};
8181 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8182 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8183 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8184 srcDevicePortConfig.format = inputDesc->getFormat();
8185 patchBuilder.addSource(srcDevicePortConfig);
8186 } else {
8187 patchBuilder.addSource(device);
8188 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008189 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008190 }
8191 }
8192 return status;
8193}
8194
Eric Laurent6a94d692014-05-20 11:18:06 -07008195status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8196 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008197{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008198 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008199 ssize_t index;
8200 if (patchHandle) {
8201 index = mAudioPatches.indexOfKey(*patchHandle);
8202 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008203 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008204 }
8205 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008206 return INVALID_OPERATION;
8207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008208 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008209 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008210 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008211 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008212 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008213 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008214 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008215 return status;
8216}
8217
François Gaffie11d30102018-11-02 16:09:09 +01008218sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008219 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008220 audio_format_t& format,
8221 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008222 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008223{
8224 // Choose an input profile based on the requested capture parameters: select the first available
8225 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008226 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008227
Atneya Nair0f0a8032022-12-12 16:20:12 -08008228 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8229 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8230 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8231
8232 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008233
jiabin2fd710d2022-05-02 23:20:22 +00008234 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008235 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008236 uint32_t inexactSamplingRate = 0;
8237 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8238 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008239 uint32_t updatedSamplingRate = 0;
8240 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8241 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8242 for (const auto& hwModule : mHwModules) {
8243 for (const auto& profile : hwModule->getInputProfiles()) {
8244 // profile->log();
8245 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008246 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008247 DeviceVector(device),
8248 samplingRate,
8249 &updatedSamplingRate,
8250 format,
8251 &updatedFormat,
8252 channelMask,
8253 &updatedChannelMask,
8254 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008255 (audio_output_flags_t) flags);
8256 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008257 samplingRate = updatedSamplingRate;
8258 format = updatedFormat;
8259 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008260 return profile;
jiabin91beb492024-10-16 21:53:36 +00008261 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8262 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8263 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8264 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008265 inexactSamplingRate = updatedSamplingRate;
8266 inexactFormat = updatedFormat;
8267 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008268 }
8269 }
8270 }
8271
jiabin91beb492024-10-16 21:53:36 +00008272 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008273 samplingRate = inexactSamplingRate;
8274 format = inexactFormat;
8275 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008276 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008277 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8278 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8279 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8280 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8281 flags = AUDIO_INPUT_FLAG_NONE;
8282 } else { // fail
8283 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8284 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8285 samplingRate, format, channelMask, oriFlags);
8286 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008287 }
8288 }
jiabin2fd710d2022-05-02 23:20:22 +00008289
8290 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008291}
8292
Vlad Popa87e0e582024-05-20 18:49:20 -07008293float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8294 VolumeSource volumeSource,
8295 int index,
8296 const DeviceTypeSet &deviceTypes)
8297{
8298 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8299 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8300 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8301
8302 if (com_android_media_audio_abs_volume_index_fix()) {
8303 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8304 mAbsoluteVolumeDrivingStreams.end()) {
8305 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8306 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8307 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8308 ALOGD("%s: no group matching with %s", __FUNCTION__,
8309 toString(attributesToDriveAbs).c_str());
8310 return volumeDb;
8311 }
8312
8313 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8314 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8315 if (vsToDriveAbs == volumeSource) {
8316 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008317 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008318 } else {
8319 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8320 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8321 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8322 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8323 curvesAbs.getVolumeIndexMax());
8324 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8325 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8326 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8327 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8328 return newVolumeDb;
8329 }
8330 }
8331 return volumeDb;
8332 } else {
8333 return volumeDb;
8334 }
8335}
8336
François Gaffieaaac0fd2018-11-22 17:56:39 +01008337float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8338 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008339 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008340 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008341 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008342 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008343{
Vlad Popa9d482762024-06-21 16:40:23 -07008344 float volumeDb;
8345 if (adjustAttenuation) {
8346 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8347 } else {
8348 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8349 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008350 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8351 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8352
8353 if (!computeInternalInteraction) {
8354 return volumeDb;
8355 }
8356
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008357 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8358 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8359 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8360 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008361 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8362 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8363 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8364 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8365 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008366 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008367 mOutputs.isActive(ringVolumeSrc, 0)) {
8368 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008369 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008370 adjustAttenuation,
8371 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008372 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008373 }
8374
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008375 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008376 if ((volumeSource != callVolumeSrc && (isInCall() ||
8377 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008378 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008379 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8380 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008381 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8382 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8383 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008384 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008385 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008386 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008387 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008388 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008389 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008390 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008391 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8392 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8393 // programmatically muted.
8394 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8395 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8396 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008397 bool exemptFromCapping =
8398 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8399 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008400 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8401 volumeSource, volumeDb);
8402 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008403 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8404 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8405 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008406 }
8407 }
Eric Laurente552edb2014-03-10 17:42:56 -07008408 // if a headset is connected, apply the following rules to ring tones and notifications
8409 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008410 // - always attenuate notifications volume by 6dB
8411 // - attenuate ring tones volume by 6dB unless music is not playing and
8412 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008413 // - if music is playing, always limit the volume to current music volume,
8414 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008415 if (!Intersection(deviceTypes,
8416 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8417 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008418 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8419 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008420 ((volumeSource == alarmVolumeSrc ||
8421 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008422 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8423 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8424 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008425 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8426 curves.canBeMuted()) {
8427
Eric Laurente552edb2014-03-10 17:42:56 -07008428 // when the phone is ringing we must consider that music could have been paused just before
8429 // by the music application and behave as if music was active if the last music track was
8430 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008431 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8432 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008433 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008434 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008435 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8436 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008437 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008438 float musicVolDb = computeVolume(musicCurves,
8439 musicVolumeSrc,
8440 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008441 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008442 adjustAttenuation,
8443 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008444 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8445 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8446 if (volumeDb > minVolDb) {
8447 volumeDb = minVolDb;
8448 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008449 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008450 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8451 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008452 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8453 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8454 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8455 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008456 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008457 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008458 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8459 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008460 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8461 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008462 }
8463 }
jiabin9a3361e2019-10-01 09:38:30 -07008464 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008465 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008466 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008467 }
8468 }
8469
François Gaffie43c73442018-11-08 08:21:55 +01008470 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008471}
8472
Eric Laurent3839bc02018-07-10 18:33:34 -07008473int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008474 VolumeSource fromVolumeSource,
8475 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008476{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008477 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008478 return srcIndex;
8479 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008480 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8481 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008482 float minSrc = (float)srcCurves.getVolumeIndexMin();
8483 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8484 float minDst = (float)dstCurves.getVolumeIndexMin();
8485 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008486
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008487 // preserve mute request or correct range
8488 if (srcIndex < minSrc) {
8489 if (srcIndex == 0) {
8490 return 0;
8491 }
8492 srcIndex = minSrc;
8493 } else if (srcIndex > maxSrc) {
8494 srcIndex = maxSrc;
8495 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008496 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8497}
8498
François Gaffieaaac0fd2018-11-22 17:56:39 +01008499status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8500 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008501 int index,
8502 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008503 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008504 int delayMs,
8505 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008506{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008507 // APM is single threaded, and single instance.
8508 static std::set<IVolumeCurves*> invalidCurvesReported;
8509
François Gaffieaaac0fd2018-11-22 17:56:39 +01008510 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008511 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008512 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8513 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008514 return NO_ERROR;
8515 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008516
Eric Laurentae6e88c2024-01-10 14:42:57 +01008517 bool isVoiceVolSrc;
8518 bool isBtScoVolSrc;
8519 if (!isVolumeConsistentForCalls(
8520 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008521 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008522 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008523 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008524 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008525
jiabin9a3361e2019-10-01 09:38:30 -07008526 if (deviceTypes.empty()) {
8527 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008528 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008529 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008530 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008531 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008532
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008533 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008534 if (!invalidCurvesReported.count(&curves)) {
8535 invalidCurvesReported.insert(&curves);
8536 String8 dump;
8537 curves.dump(&dump);
8538 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8539 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008540 return BAD_VALUE;
8541 }
8542
jiabin9a3361e2019-10-01 09:38:30 -07008543 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008544 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008545 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008546 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008547 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8548 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008549 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8550 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008551 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008552 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008553
8554 bool muted;
8555 if (!com_android_media_audio_ring_my_car()) {
8556 muted = (index == 0) && (volumeDb != 0.0f);
8557 } else {
8558 muted = curves.isMuted();
8559 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008560 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8561 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008562
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008563 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008564 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8565 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8566 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008567 }
Eric Laurente552edb2014-03-10 17:42:56 -07008568 return NO_ERROR;
8569}
8570
Eric Laurentae6e88c2024-01-10 14:42:57 +01008571void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008572 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008573 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008574
8575 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8576 index = 0;
8577 }
8578
chenxin2095559032024-06-15 13:59:29 +08008579 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008580 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008581 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008582 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8583 } else {
8584 voiceVolume = index == 0 ? 0.0 : 1.0;
8585 }
8586 if (voiceVolume != mLastVoiceVolume) {
8587 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8588 mLastVoiceVolume = voiceVolume;
8589 }
8590}
8591
8592bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8593 const DeviceTypeSet& deviceTypes,
8594 bool& isVoiceVolSrc,
8595 bool& isBtScoVolSrc,
8596 const char* caller) {
8597 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008598 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8599
Eric Laurentae6e88c2024-01-10 14:42:57 +01008600 const bool isScoRequested = isScoRequestedForComm();
8601 const bool isHAUsed = isHearingAidUsedForComm();
8602
Vlad Popa695b76b2024-06-14 16:49:25 -07008603 if (com_android_media_audio_replace_stream_bt_sco()) {
8604 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8605 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8606 (isScoRequested || isHAUsed);
8607 return true;
8608 }
8609
8610 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008611 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8612
8613 if ((callVolSrc != btScoVolSrc) &&
8614 ((isVoiceVolSrc && isScoRequested) ||
8615 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8616 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8617 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8618 volumeSource, isScoRequested ? " " : " not ");
8619 return false;
8620 }
8621 return true;
8622}
8623
Eric Laurentc75307b2015-03-17 15:29:32 -07008624void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008625 const DeviceTypeSet& deviceTypes,
8626 int delayMs,
8627 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008628{
jiabincd510522020-01-22 09:40:55 -08008629 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008630 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8631 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008632 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008633 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008634 }
8635}
8636
François Gaffiec005e562018-11-06 15:04:49 +01008637void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8638 bool on,
8639 const sp<AudioOutputDescriptor>& outputDesc,
8640 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008641 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008642{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008643 std::vector<VolumeSource> sourcesToMute;
8644 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8645 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8646 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008647 VolumeSource source = toVolumeSource(attributes, false);
8648 if ((source != VOLUME_SOURCE_NONE) &&
8649 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8650 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008651 sourcesToMute.push_back(source);
8652 }
Eric Laurente552edb2014-03-10 17:42:56 -07008653 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008654 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008655 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008656 }
8657
Eric Laurente552edb2014-03-10 17:42:56 -07008658}
8659
Vlad Popa1e865e62024-08-15 19:11:42 -07008660void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8661 bool on,
8662 const sp<AudioOutputDescriptor>& outputDesc,
8663 int delayMs,
8664 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008665{
jiabin9a3361e2019-10-01 09:38:30 -07008666 if (deviceTypes.empty()) {
8667 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008668 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008669 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008670 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008671 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008672 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008673 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008674 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8675 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008676 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008677 }
8678 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008679 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8680 // ignored
8681 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008682 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008683 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008684 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008685 return;
8686 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008687 if (outputDesc->decMuteCount(volumeSource) == 0) {
8688 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008689 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008690 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008691 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008692 delayMs);
8693 }
8694 }
8695}
8696
François Gaffie53615e22015-03-19 09:24:12 +01008697bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8698{
François Gaffiec005e562018-11-06 15:04:49 +01008699 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008700 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8701 return true;
8702 }
8703
8704 // has known usage?
8705 switch (paa->usage) {
8706 case AUDIO_USAGE_UNKNOWN:
8707 case AUDIO_USAGE_MEDIA:
8708 case AUDIO_USAGE_VOICE_COMMUNICATION:
8709 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8710 case AUDIO_USAGE_ALARM:
8711 case AUDIO_USAGE_NOTIFICATION:
8712 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8713 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8714 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8715 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8716 case AUDIO_USAGE_NOTIFICATION_EVENT:
8717 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8718 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8719 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8720 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008721 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008722 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008723 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008724 case AUDIO_USAGE_EMERGENCY:
8725 case AUDIO_USAGE_SAFETY:
8726 case AUDIO_USAGE_VEHICLE_STATUS:
8727 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008728 break;
8729 default:
8730 return false;
8731 }
8732 return true;
8733}
8734
François Gaffie2110e042015-03-24 08:41:51 +01008735audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8736{
8737 return mEngine->getForceUse(usage);
8738}
8739
Eric Laurent96d1dda2022-03-14 17:14:19 +01008740bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008741 return isStateInCall(mEngine->getPhoneState());
8742}
8743
Eric Laurent96d1dda2022-03-14 17:14:19 +01008744bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008745 return is_state_in_call(state);
8746}
8747
Eric Laurentf9cccec2022-11-16 19:12:00 +01008748bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008749 audio_mode_t mode = mEngine->getPhoneState();
8750 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008751 || (mode == AUDIO_MODE_CALL_SCREEN)
8752 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008753}
8754
Eric Laurentf9cccec2022-11-16 19:12:00 +01008755bool AudioPolicyManager::isInCallOrScreening() const {
8756 audio_mode_t mode = mEngine->getPhoneState();
8757 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8758}
8759
Eric Laurentd60560a2015-04-10 11:31:20 -07008760void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8761{
8762 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008763 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008764 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008765 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008766 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008767 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008768 }
8769 }
8770
8771 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8772 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8773 bool release = false;
8774 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8775 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8776 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8777 source->ext.device.type == deviceDesc->type()) {
8778 release = true;
8779 }
8780 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008781 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008782 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8783 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8784 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008785 sink->ext.device.type == deviceDesc->type() &&
8786 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8787 || strncmp(sink->ext.device.address, address,
8788 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008789 release = true;
8790 }
8791 }
8792 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008793 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8794 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008795 }
8796 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008797
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008798 mInputs.clearSessionRoutesForDevice(deviceDesc);
8799
Francois Gaffie716e1432019-01-14 16:58:59 +01008800 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008801}
8802
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008803void AudioPolicyManager::modifySurroundFormats(
8804 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008805 std::unordered_set<audio_format_t> enforcedSurround(
8806 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008807 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008808 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008809 allSurround.insert(pair.first);
8810 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8811 }
Phil Burk09bc4612016-02-24 15:58:15 -08008812
8813 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8814 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008815 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008816 // This is the resulting set of formats depending on the surround mode:
8817 // 'all surround' = allSurround
8818 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8819 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8820 // 'manual surround' = mManualSurroundFormats
8821 // AUTO: formats v 'enforced surround'
8822 // ALWAYS: formats v 'all surround' v 'enforced surround'
8823 // NEVER: formats ^ 'non-surround'
8824 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008825
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008826 std::unordered_set<audio_format_t> formatSet;
8827 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8828 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008829 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008830 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008831 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008832 formatSet.insert(*formatIter);
8833 }
8834 }
8835 } else {
8836 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8837 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008838 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008839
jiabin81772902018-04-02 17:52:27 -07008840 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008841 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008842 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8843 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8844 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008845 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008846 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8847 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8848 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008849 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008850 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008851 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008852 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008853 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008854 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008855}
8856
jiabin06e4bab2019-07-29 10:13:34 -07008857void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8858 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008859 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8860 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8861
8862 // If NEVER, then remove support for channelMasks > stereo.
8863 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008864 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8865 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008866 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008867 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008868 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008869 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008870 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008871 }
8872 }
jiabin81772902018-04-02 17:52:27 -07008873 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8874 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8875 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008876 bool supports5dot1 = false;
8877 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008878 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008879 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8880 supports5dot1 = true;
8881 break;
8882 }
8883 }
8884 // If not then add 5.1 support.
8885 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008886 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008887 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008888 }
Phil Burk09bc4612016-02-24 15:58:15 -08008889 }
8890}
8891
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008892void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008893 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008894 const sp<IOProfile>& profile) {
8895 if (!profile->hasDynamicAudioProfile()) {
8896 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008897 }
François Gaffie112b0af2015-11-19 16:13:25 +01008898
jiabin12537fc2023-10-12 17:56:08 +00008899 audio_port_v7 devicePort;
8900 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008901
jiabin12537fc2023-10-12 17:56:08 +00008902 audio_port_v7 mixPort;
8903 profile->toAudioPort(&mixPort);
8904 mixPort.ext.mix.handle = ioHandle;
8905
8906 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8907 if (status != NO_ERROR) {
8908 ALOGE("%s failed to query the attributes of the mix port", __func__);
8909 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008910 }
jiabin12537fc2023-10-12 17:56:08 +00008911
8912 std::set<audio_format_t> supportedFormats;
8913 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8914 supportedFormats.insert(mixPort.audio_profiles[i].format);
8915 }
8916 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8917 mReportedFormatsMap[devDesc] = formats;
8918
8919 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008920 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8921 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008922 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8923 modifySurroundFormats(devDesc, &formats);
8924 size_t modifiedNumProfiles = 0;
8925 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8926 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8927 formats.end()) {
8928 // Skip the format that is not present after modifying surround formats.
8929 continue;
8930 }
8931 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8932 sizeof(struct audio_profile));
8933 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8934 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8935 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8936 modifySurroundChannelMasks(&channels);
8937 std::copy(channels.begin(), channels.end(),
8938 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8939 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8940 }
8941 mixPort.num_audio_profiles = modifiedNumProfiles;
8942 }
8943 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008944}
Eric Laurentd60560a2015-04-10 11:31:20 -07008945
Mikhail Naganovdc769682018-05-04 15:34:08 -07008946status_t AudioPolicyManager::installPatch(const char *caller,
8947 audio_patch_handle_t *patchHandle,
8948 AudioIODescriptorInterface *ioDescriptor,
8949 const struct audio_patch *patch,
8950 int delayMs)
8951{
8952 ssize_t index = mAudioPatches.indexOfKey(
8953 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8954 *patchHandle : ioDescriptor->getPatchHandle());
8955 sp<AudioPatch> patchDesc;
8956 status_t status = installPatch(
8957 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8958 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008959 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008960 }
8961 return status;
8962}
8963
8964status_t AudioPolicyManager::installPatch(const char *caller,
8965 ssize_t index,
8966 audio_patch_handle_t *patchHandle,
8967 const struct audio_patch *patch,
8968 int delayMs,
8969 uid_t uid,
8970 sp<AudioPatch> *patchDescPtr)
8971{
8972 sp<AudioPatch> patchDesc;
8973 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8974 if (index >= 0) {
8975 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008976 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008977 }
8978
8979 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8980 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8981 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8982 if (status == NO_ERROR) {
8983 if (index < 0) {
8984 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008985 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008986 } else {
8987 patchDesc->mPatch = *patch;
8988 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008989 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008990 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008991 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008992 }
8993 nextAudioPortGeneration();
8994 mpClientInterface->onAudioPatchListUpdate();
8995 }
8996 if (patchDescPtr) *patchDescPtr = patchDesc;
8997 return status;
8998}
8999
jiabinbce0c1d2020-10-05 11:20:18 -07009000bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9001{
9002 const TrackClientVector activeClients = output->getActiveClients();
9003 if (activeClients.empty()) {
9004 return true;
9005 }
9006 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9007 if (index < 0) {
9008 ALOGE("%s, no audio patch found while there are active clients on output %d",
9009 __func__, output->getId());
9010 return false;
9011 }
9012 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9013 DeviceVector routedDevices;
9014 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9015 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9016 patchDesc->mPatch.sinks[i].id);
9017 if (device == nullptr) {
9018 ALOGE("%s, no audio device found with id(%d)",
9019 __func__, patchDesc->mPatch.sinks[i].id);
9020 return false;
9021 }
9022 routedDevices.add(device);
9023 }
9024 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009025 if (client->isInvalid()) {
9026 // No need to take care about invalidated clients.
9027 continue;
9028 }
jiabinbce0c1d2020-10-05 11:20:18 -07009029 sp<DeviceDescriptor> preferredDevice =
9030 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9031 if (mEngine->getOutputDevicesForAttributes(
9032 client->attributes(), preferredDevice, false) == routedDevices) {
9033 return false;
9034 }
9035 }
9036 return true;
9037}
9038
9039sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009040 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009041 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9042 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009043{
9044 for (const auto& device : devices) {
9045 // TODO: This should be checking if the profile supports the device combo.
9046 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009047 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9048 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009049 return nullptr;
9050 }
9051 }
9052 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9053 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009054 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009055 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009056 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009057 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009058 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009059 return nullptr;
9060 }
jiabin14b50cc2023-12-13 19:01:52 +00009061 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9062 auto portConfig = desc->getConfig();
9063 for (const auto& device : devices) {
9064 device->setPreferredConfig(&portConfig);
9065 }
9066 }
jiabinbce0c1d2020-10-05 11:20:18 -07009067
9068 // Here is where the out_set_parameters() for card & device gets called
9069 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9070 const audio_devices_t deviceType = device->type();
9071 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009072 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009073 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9074 mpClientInterface->setParameters(output, String8(param));
9075 free(param);
9076 }
jiabin12537fc2023-10-12 17:56:08 +00009077 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009078 if (!profile->hasValidAudioProfile()) {
9079 ALOGW("%s() missing param", __func__);
9080 desc->close();
9081 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009082 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9083 // Reopen the output with the best audio profile picked by APM when the profile supports
9084 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009085 desc->close();
9086 output = AUDIO_IO_HANDLE_NONE;
9087 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9088 profile->pickAudioProfile(
9089 config.sample_rate, config.channel_mask, config.format);
9090 config.offload_info.sample_rate = config.sample_rate;
9091 config.offload_info.channel_mask = config.channel_mask;
9092 config.offload_info.format = config.format;
9093
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009094 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009095 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009096 if (status != NO_ERROR) {
9097 return nullptr;
9098 }
9099 }
9100
9101 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009102 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9103 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9104 hwModule->getHalVersionMajor() >= 3) {
9105 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9106 }
baek.kim -61c20122022-07-27 10:05:32 +00009107 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9108 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9109
jiabinbce0c1d2020-10-05 11:20:18 -07009110 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9111 sp<AudioPolicyMix> policyMix;
9112 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9113 policyMix->setOutput(desc);
9114 desc->mPolicyMix = policyMix;
9115 } else {
9116 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009117 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009118 }
9119
baek.kim -61c20122022-07-27 10:05:32 +00009120 } else if (hasPrimaryOutput() && speaker != nullptr
9121 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009122 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9123 // no duplicated output for:
9124 // - direct outputs
9125 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009126 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009127 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9128
9129 //TODO: configure audio effect output stage here
9130
9131 // open a duplicating output thread for the new output and the primary output
9132 sp<SwAudioOutputDescriptor> dupOutputDesc =
9133 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9134 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9135 if (status == NO_ERROR) {
9136 // add duplicated output descriptor
9137 addOutput(duplicatedOutput, dupOutputDesc);
9138 } else {
9139 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9140 mPrimaryOutput->mIoHandle, output);
9141 desc->close();
9142 removeOutput(output);
9143 nextAudioPortGeneration();
9144 return nullptr;
9145 }
9146 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009147 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9148 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9149 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009150 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009151 }
jiabinbce0c1d2020-10-05 11:20:18 -07009152 return desc;
9153}
9154
jiabinf1c73972022-04-14 16:28:52 -07009155status_t AudioPolicyManager::getDevicesForAttributes(
9156 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009157 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9158 // over any usage or content type also present in attr.
9159 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9160 attr.source != AUDIO_SOURCE_INVALID) {
9161 return getInputDevicesForAttributes(attr, devices);
9162 }
9163
jiabinf1c73972022-04-14 16:28:52 -07009164 // Devices are determined in the following precedence:
9165 //
9166 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9167 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9168 //
9169 // If no such dynamic policy then
9170 // 2) Devices containing an active client using setPreferredDevice
9171 // with same strategy as the attributes.
9172 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9173 //
9174 // If no corresponding active client with setPreferredDevice then
9175 // 3) Devices associated with the strategy determined by the attributes
9176 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9177 //
9178 // See related getOutputForAttrInt().
9179
9180 // check dynamic policies but only for primary descriptors (secondary not used for audible
9181 // audio routing, only used for duplication for playback capture)
9182 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009183 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009184 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009185 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9186 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9187 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009188 if (status != OK) {
9189 return status;
9190 }
9191
9192 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9193 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9194 // as they are unaffected by device/stream volume
9195 // (per SwAudioOutputDescriptor::isFixedVolume()).
9196 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9197 ) {
9198 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9199 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9200 devices.add(deviceDesc);
9201 } else {
9202 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9203 // which selects setPreferredDevice if active. This means forVolume call
9204 // will take an active setPreferredDevice, if such exists.
9205
9206 devices = mEngine->getOutputDevicesForAttributes(
9207 attr, nullptr /* preferredDevice */, false /* fromCache */);
9208 }
9209
9210 if (forVolume) {
9211 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9212 // for single volume control in AudioService (such relationship should exist if
9213 // SPEAKER_SAFE is present).
9214 //
9215 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9216 DeviceVector speakerSafeDevices =
9217 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9218 if (!speakerSafeDevices.isEmpty()) {
9219 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9220 devices.remove(speakerSafeDevices);
9221 }
9222 }
9223
9224 return NO_ERROR;
9225}
9226
wenyu zhang8558a332024-09-09 15:12:48 +00009227status_t AudioPolicyManager::getInputDevicesForAttributes(
9228 const audio_attributes_t &attr, DeviceVector &devices) {
9229 devices = DeviceVector(
9230 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9231 AUDIO_SESSION_NONE,
9232 nullptr /* mix */));
9233 return NO_ERROR;
9234}
9235
jiabinf1c73972022-04-14 16:28:52 -07009236status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9237 AudioProfileVector& audioProfiles,
9238 uint32_t flags,
9239 bool isInput) {
9240 for (const auto& hwModule : mHwModules) {
9241 // the MSD module checks for different conditions
9242 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9243 continue;
9244 }
9245 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9246 : hwModule->getOutputProfiles();
9247 for (const auto& profile : ioProfiles) {
9248 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009249 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009250 continue;
9251 }
9252 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9253 }
9254 }
9255
9256 if (!isInput) {
9257 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9258 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9259 if (msdModule != nullptr) {
9260 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9261 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9262 for (const auto &profile: msdModule->getOutputProfiles()) {
9263 if (!profile->asAudioPort()->isDirectOutput()) {
9264 continue;
9265 }
9266 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9267 }
9268 } else {
9269 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9270 }
9271 }
9272 }
9273
9274 return NO_ERROR;
9275}
9276
jiabin3ff8d7d2022-12-13 06:27:44 +00009277sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9278 const audio_config_t *config,
9279 audio_output_flags_t flags,
9280 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009281 closeOutput(outputDesc->mIoHandle);
9282 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9283 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9284 if (preferredOutput == nullptr) {
9285 ALOGE("%s failed to reopen output device=%d, caller=%s",
9286 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009287 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009288 return preferredOutput;
9289}
9290
9291void AudioPolicyManager::reopenOutputsWithDevices(
9292 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9293 for (const auto& [output, devices] : outputsToReopen) {
9294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9295 closeOutput(output);
9296 openOutputWithProfileAndDevice(desc->mProfile, devices);
9297 }
jiabina84c3d32022-12-02 18:59:55 +00009298}
9299
jiabinc44b3462022-12-08 12:52:31 -08009300PortHandleVector AudioPolicyManager::getClientsForStream(
9301 audio_stream_type_t streamType) const {
9302 PortHandleVector clients;
9303 for (size_t i = 0; i < mOutputs.size(); ++i) {
9304 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9305 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9306 }
9307 return clients;
9308}
9309
9310void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9311 PortHandleVector clients;
9312 for (auto stream : streams) {
9313 PortHandleVector clientsForStream = getClientsForStream(stream);
9314 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9315 }
9316 mpClientInterface->invalidateTracks(clients);
9317}
9318
jiabin220eea12024-05-17 17:55:20 +00009319void AudioPolicyManager::updateClientsInternalMute(
9320 const sp<android::SwAudioOutputDescriptor> &desc) {
9321 if (!desc->isBitPerfect() ||
9322 !com::android::media::audioserver::
9323 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9324 // This is only used for bit perfect output now.
9325 return;
9326 }
9327 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9328 bool bitPerfectClientInternalMute = false;
9329 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9330 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9331 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9332 bitPerfectClient = client;
9333 continue;
9334 }
9335 bool muted = false;
9336 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9337 // System sound is muted.
9338 muted = true;
9339 } else {
9340 bitPerfectClientInternalMute = true;
9341 }
9342 if (client->setInternalMute(muted)) {
9343 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9344 if (!result.ok()) {
9345 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9346 continue;
9347 }
9348 media::TrackInternalMuteInfo info;
9349 info.portId = result.value();
9350 info.muted = client->getInternalMute();
9351 clientsInternalMute.push_back(std::move(info));
9352 }
9353 }
9354 if (bitPerfectClient != nullptr &&
9355 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9356 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9357 if (result.ok()) {
9358 media::TrackInternalMuteInfo info;
9359 info.portId = result.value();
9360 info.muted = bitPerfectClient->getInternalMute();
9361 clientsInternalMute.push_back(std::move(info));
9362 } else {
9363 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9364 __func__, bitPerfectClient->portId());
9365 }
9366 }
9367 if (!clientsInternalMute.empty()) {
9368 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9369 status != NO_ERROR) {
9370 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9371 }
9372 }
9373}
9374
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009375} // namespace android