blob: 303f313dc81a3000fcbf02091f2dd824aa48c50f [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010020// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090021// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000042#include <android/media/audio/common/AudioMMapPolicy.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>
Atneya Nair25fbcf22024-11-19 19:53:23 -080048#include <error/expected_utils.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000058#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010059#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070060
Eric Laurent3b73df72014-03-11 09:06:29 -070061namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070062
Marvin Raminbdefaf02023-11-01 09:10:32 +010063
64namespace audio_flags = android::media::audiopolicy;
65
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010066using android::media::audio::common::AudioDevice;
67using android::media::audio::common::AudioDeviceAddress;
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000068using android::media::audio::common::AudioDeviceDescription;
69using android::media::audio::common::AudioMMapPolicy;
70using android::media::audio::common::AudioMMapPolicyInfo;
71using android::media::audio::common::AudioMMapPolicyType;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010072using android::media::audio::common::AudioPortDeviceExt;
73using android::media::audio::common::AudioPortExt;
Atneya Nair25fbcf22024-11-19 19:53:23 -080074using android::media::audio::common::AudioConfigBase;
75using binder::Status;
Eric Laurentb2fb4102024-06-21 12:25:26 +000076using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000077using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070078
Eric Laurentdc462862016-07-19 12:29:53 -070079//FIXME: workaround for truncated touch sounds
80// to be removed when the problem is handled by system UI
81#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070082
83// Largest difference in dB on earpiece in call between the voice volume and another
84// media / notification / system volume.
85constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
86
jiabin06e4bab2019-07-29 10:13:34 -070087template <typename T>
88bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 if (left.size() != right.size()) {
91 return false;
92 }
93 for (size_t index = 0; index < right.size(); index++) {
94 if (left[index] != right[index]) {
95 return false;
96 }
97 }
98 return true;
99}
100
101template <typename T>
102bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
103{
104 return !(left == right);
105}
106
Eric Laurente552edb2014-03-10 17:42:56 -0700107// ----------------------------------------------------------------------------
108// AudioPolicyInterface implementation
109// ----------------------------------------------------------------------------
110
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100111status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
112 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
113 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800114 nextAudioPortGeneration();
115 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800116}
117
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100118status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
119 audio_policy_dev_state_t state,
120 const char* device_address,
121 const char* device_name,
122 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800123 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100124 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
125 status == OK) {
126 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
127 } else {
128 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
129 return status;
130 }
131}
132
Ping Tsai2a5a5242024-08-16 13:39:10 +0800133status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000134 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200135{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000136 audio_port_v7 devicePort;
137 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800138 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
139 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
140 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
141
142 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200143}
144
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100145status_t AudioPolicyManager::setDeviceConnectionStateInt(
146 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
147 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100148 if (port.ext.getTag() != AudioPortExt::device) {
149 return BAD_VALUE;
150 }
151 audio_devices_t device_type;
152 std::string device_address;
153 if (status_t status = aidl2legacy_AudioDevice_audio_device(
154 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
155 status != OK) {
156 return status;
157 };
158 const char* device_name = port.name.c_str();
159 // connect/disconnect only 1 device at a time
160 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
161 return BAD_VALUE;
162
163 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
164 device_type, device_address.c_str(), device_name, encodedFormat,
165 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000166 if (device == nullptr) {
167 return INVALID_OPERATION;
168 }
169 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
170 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
171 }
172 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100173}
174
François Gaffie11d30102018-11-02 16:09:09 +0100175status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800176 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100177 const char* device_address,
178 const char* device_name,
179 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800180 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100181 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
182 status == OK) {
183 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
184 } else {
185 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
186 return status;
187 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188}
Paul McLeane743a472015-01-28 11:07:31 -0800189
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700190status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
191 audio_policy_dev_state_t state)
192{
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700194 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700195 SortedVector <audio_io_handle_t> outputs;
196
François Gaffie11d30102018-11-02 16:09:09 +0100197 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 // save a copy of the opened output descriptors before any output is opened or closed
200 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
201 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100202
203 bool wasLeUnicastActive = isLeUnicastActive();
204
Eric Laurente552edb2014-03-10 17:42:56 -0700205 switch (state)
206 {
207 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800208 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100210 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700211 return INVALID_OPERATION;
212 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800213 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700214 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700215
Eric Laurente552edb2014-03-10 17:42:56 -0700216 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200217 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700218 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700219 }
220
François Gaffie44481e72016-04-20 07:49:57 +0200221 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
222 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800223 if (broadcastDeviceConnectionState(
224 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
225 mAvailableOutputDevices.remove(device);
226 mHwModules.cleanUpForDevice(device);
227 ALOGE("%s() device %s format %x connection failed", __func__,
228 device->toString().c_str(), device->getEncodedFormat());
229 return INVALID_OPERATION;
230 }
François Gaffie44481e72016-04-20 07:49:57 +0200231
François Gaffie11d30102018-11-02 16:09:09 +0100232 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
233 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200234
jiabinc0048632023-04-27 22:04:31 +0000235 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700236
237 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700238 return INVALID_OPERATION;
239 }
François Gaffie2110e042015-03-24 08:41:51 +0100240
jiabin1c4794b2020-05-05 10:08:05 -0700241 // Populate encapsulation information when a output device is connected.
242 device->setEncapsulationInfoFromHal(mpClientInterface);
243
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700244 // outputs should never be empty here
245 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
246 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100247 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800248
Eric Laurent3ae5f312015-02-03 17:12:08 -0800249 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100253 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700254 return INVALID_OPERATION;
255 }
256
François Gaffie11d30102018-11-02 16:09:09 +0100257 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700258
jiabinc0048632023-04-27 22:04:31 +0000259 // Notify the HAL to prepare to disconnect device
260 broadcastDeviceConnectionState(
261 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100264 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700265
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100266 mOutputs.clearSessionRoutesForDevice(device);
267
François Gaffie11d30102018-11-02 16:09:09 +0100268 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100269
jiabinc0048632023-04-27 22:04:31 +0000270 // Send Disconnect to HALs
271 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
272
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800273 // Reset active device codec
274 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
275
Kriti Dangef6be8f2020-11-05 11:58:19 +0100276 // remove device from mReportedFormatsMap cache
277 mReportedFormatsMap.erase(device);
278
jiabina84c3d32022-12-02 18:59:55 +0000279 // remove preferred mixer configurations
280 mPreferredMixerAttrInfos.erase(device->getId());
281
Eric Laurente552edb2014-03-10 17:42:56 -0700282 } break;
283
284 default:
François Gaffie11d30102018-11-02 16:09:09 +0100285 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700286 return BAD_VALUE;
287 }
288
Eric Laurent736a1022019-03-27 18:28:46 -0700289 // Propagate device availability to Engine
290 setEngineDeviceConnectionState(device, state);
291
Eric Laurentae970022019-01-29 14:25:04 -0800292 // No need to evaluate playback routing when connecting a remote submix
293 // output device used by a dynamic policy of type recorder as no
294 // playback use case is affected.
295 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700296 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800297 for (audio_io_handle_t output : outputs) {
298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800299 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
300 if (policyMix != nullptr
301 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000302 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800303 doCheckForDeviceAndOutputChanges = false;
304 break;
305 }
306 }
307 }
308
309 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 // outputs must be closed after checkOutputForAllStrategies() is executed
311 if (!outputs.isEmpty()) {
312 for (audio_io_handle_t output : outputs) {
313 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100314 // close unused outputs after device disconnection or direct outputs that have
315 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200316 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200317 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
318 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200319 (desc->mDirectOpenCount == 0))
320 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
321 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200322 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700323 closeOutput(output);
324 }
Eric Laurente552edb2014-03-10 17:42:56 -0700325 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700326 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
327 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700329 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800330 };
331
332 if (doCheckForDeviceAndOutputChanges) {
333 checkForDeviceAndOutputChanges(checkCloseOutputs);
334 } else {
335 checkCloseOutputs();
336 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100337 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100338 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700339 const DeviceVector activeMediaDevices =
340 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000341 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700342 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700343 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530344 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
345 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100346 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700347 // do not force device change on duplicated output because if device is 0, it will
348 // also force a device 0 for the two outputs it is duplicated to which may override
349 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100350 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100351 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700352 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700353 // always force when disconnecting (a non-duplicated device)
354 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000355 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000356 // If the device is using preferred mixer attributes, the output need to reopen
357 // with default configuration when the new selected devices are different from
358 // current routing devices
359 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
360 continue;
361 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530362 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700363 }
jiabinbce0c1d2020-10-05 11:20:18 -0700364 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000365 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700366 desc->supportsDevicesForPlayback(activeMediaDevices)) {
367 // Reopen the output to query the dynamic profiles when there is not active
368 // clients or all active clients will be rerouted. Otherwise, set the flag
369 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
370 // can be reopened to query dynamic profiles when all clients are inactive.
371 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000372 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700373 } else {
374 desc->mPendingReopenToQueryProfiles = true;
375 }
376 }
377 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
378 // Clear the flag that previously set for re-querying profiles.
379 desc->mPendingReopenToQueryProfiles = false;
380 }
381 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000382 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700383
Eric Laurentd60560a2015-04-10 11:31:20 -0700384 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100385 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700386 }
387
Eric Laurent96d1dda2022-03-14 17:14:19 +0100388 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
389
Eric Laurent72aa32f2014-05-30 18:51:48 -0700390 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530391 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700392 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700393 } // end if is output device
394
Eric Laurente552edb2014-03-10 17:42:56 -0700395 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700396 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100397 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700398 switch (state)
399 {
400 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700402 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700404 return INVALID_OPERATION;
405 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700406
Jaideep Sharma33173202024-06-18 17:46:45 +0530407 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
408
Eric Laurent0dd51852019-04-19 18:18:58 -0700409 if (mAvailableInputDevices.add(device) < 0) {
410 return NO_MEMORY;
411 }
412
François Gaffie44481e72016-04-20 07:49:57 +0200413 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
414 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800415 if (broadcastDeviceConnectionState(
416 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
417 mAvailableInputDevices.remove(device);
418 mHwModules.cleanUpForDevice(device);
419 ALOGE("%s() device %s format %x connection failed", __func__,
420 device->toString().c_str(), device->getEncodedFormat());
421 return INVALID_OPERATION;
422 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700423 // Propagate device availability to Engine
424 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200425
Eric Laurent0dd51852019-04-19 18:18:58 -0700426 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700427 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
428
Eric Laurent0dd51852019-04-19 18:18:58 -0700429 mAvailableInputDevices.remove(device);
430
jiabinc0048632023-04-27 22:04:31 +0000431 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100432
433 mHwModules.cleanUpForDevice(device);
434
Eric Laurentd4692962014-05-05 18:13:44 -0700435 return INVALID_OPERATION;
436 }
437
Eric Laurentd4692962014-05-05 18:13:44 -0700438 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700439
440 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700441 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700442 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100443 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700444 return INVALID_OPERATION;
445 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700446
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700448
jiabinc0048632023-04-27 22:04:31 +0000449 // Notify the HAL to prepare to disconnect device
450 broadcastDeviceConnectionState(
451 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700452
François Gaffie11d30102018-11-02 16:09:09 +0100453 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700454
455 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100456
jiabinc0048632023-04-27 22:04:31 +0000457 // Set Disconnect to HALs
458 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
459
Kriti Dangef6be8f2020-11-05 11:58:19 +0100460 // remove device from mReportedFormatsMap cache
461 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700462
463 // Propagate device availability to Engine
464 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700465 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700466
467 default:
François Gaffie11d30102018-11-02 16:09:09 +0100468 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return BAD_VALUE;
470 }
471
Eric Laurent0dd51852019-04-19 18:18:58 -0700472 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700473 // As the input device list can impact the output device selection, update
474 // getDeviceForStrategy() cache
475 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700476
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100477 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200478 // Reconnect Audio Source
479 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
480 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
481 checkAudioSourceForAttributes(attributes);
482 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700483 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100484 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700485 }
486
Eric Laurentb52c1522014-05-20 11:27:36 -0700487 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530488 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700489 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700490 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700491
François Gaffie11d30102018-11-02 16:09:09 +0100492 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700493 return BAD_VALUE;
494}
495
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100496status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
497 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800498 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700499 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
500 devDescr->setName(device_name);
501 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100502}
503
Eric Laurent736a1022019-03-27 18:28:46 -0700504void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
505 audio_policy_dev_state_t state) {
506
507 // the Engine does not have to know about remote submix devices used by dynamic audio policies
508 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
509 return;
510 }
511 mEngine->setDeviceConnectionState(device, state);
512}
513
514
Eric Laurente0720872014-03-11 09:30:41 -0700515audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100516 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700517{
Eric Laurent634b7142016-04-20 13:48:02 -0700518 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
520 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700521 (strlen(device_address) != 0)/*matchAddress*/);
522
523 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100524 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700525 device, device_address);
526 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
527 }
François Gaffie53615e22015-03-19 09:24:12 +0100528
Eric Laurent3a4311c2014-03-17 12:00:47 -0700529 DeviceVector *deviceVector;
530
Eric Laurente552edb2014-03-10 17:42:56 -0700531 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700532 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700533 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700534 deviceVector = &mAvailableInputDevices;
535 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100536 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700537 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700538 }
Eric Laurent634b7142016-04-20 13:48:02 -0700539
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 return (deviceVector->getDevice(
541 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700542 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800543}
544
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800545status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
546 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800547 const char *device_name,
548 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800549{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800550 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
551 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800552
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800553 // connect/disconnect only 1 device at a time
554 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
555
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800556 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700557 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800559 // Nothing to do: device is not connected
560 return NO_ERROR;
561 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800562 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800563
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700564 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 // configure codecs.
566 // Handle two specific cases by sending a set parameter to
567 // configure A2DP codecs. No need to toggle device state.
568 // Case 1: A2DP active device switches from primary to primary
569 // module
570 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100571 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700572 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
574 if (availablePrimaryOutputDevices().contains(devDesc) &&
575 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100576 bool isA2dp = audio_is_a2dp_out_device(device);
577 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
578 : String8(AudioParameter::keyReconfigLeSupported);
579 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800580 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100581 int isReconfigSupported;
582 repliedParameters.getInt(supportKey, isReconfigSupported);
583 if (isReconfigSupported) {
584 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
585 : String8(AudioParameter::keyReconfigLe);
586 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800587 param.add(key, String8("true"));
588 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
589 devDesc->setEncodedFormat(encodedFormat);
590 return NO_ERROR;
591 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700592 }
593 }
cnx421bd2dcc42020-07-11 14:58:44 +0800594 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000595 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800596 for (size_t i = 0; i < mOutputs.size(); i++) {
597 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000598 // mute media strategies to avoid sending the music tail into
599 // the earpiece or headset.
600 if (desc->isStrategyActive(musicStrategy)) {
601 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
602 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
603 tempRecommendedMuteDuration : desc->latency() * 4;
604 if (muteWaitMs < tempMuteDurationMs) {
605 muteWaitMs = tempMuteDurationMs;
606 }
607 }
cnx421bd2dcc42020-07-11 14:58:44 +0800608 setStrategyMute(musicStrategy, true, desc);
609 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
610 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
611 nullptr, true /*fromCache*/).types());
612 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000613 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
614 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
615 // happens after the actual device switch.
616 if (muteWaitMs > 0) {
617 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
618 usleep(muteWaitMs * 1000);
619 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800620 // Toggle the device state: UNAVAILABLE -> AVAILABLE
621 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100622 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800623 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800624 device_address, device_name,
625 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800626 if (status != NO_ERROR) {
627 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
628 status);
629 return status;
630 }
631
632 status = setDeviceConnectionState(device,
633 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800634 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800635 if (status != NO_ERROR) {
636 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
637 status);
638 return status;
639 }
640
641 return NO_ERROR;
642}
643
Pattydd807582021-11-04 21:01:03 +0800644status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
645 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800646{
Pattydd807582021-11-04 21:01:03 +0800647 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800648 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800649 std::unordered_set<audio_format_t> formatSet;
650 sp<HwModule> primaryModule =
651 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700652 if (primaryModule == nullptr) {
653 ALOGE("%s() unable to get primary module", __func__);
654 return NO_INIT;
655 }
Pattydd807582021-11-04 21:01:03 +0800656
657 DeviceTypeSet audioDeviceSet;
658
659 switch(device) {
660 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
661 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
662 break;
663 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800664 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
665 break;
666 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
667 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800668 break;
669 default:
670 ALOGE("%s() device type 0x%08x not supported", __func__, device);
671 return BAD_VALUE;
672 }
673
jiabin9a3361e2019-10-01 09:38:30 -0700674 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800675 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800676 for (const auto& device : declaredDevices) {
677 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800678 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800679 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800680 return status;
681}
682
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100683DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
684{
685 DeviceVector rxSinkdevices{};
686 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
687 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
688 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
689 auto rxSinkDevice = rxSinkdevices.itemAt(0);
690 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
691 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
692 // retrieve Rx Source device descriptor
693 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
694 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
695
696 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
697 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
698 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
699 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
700 return DeviceVector(rxSinkDevice);
701 }
702 }
703 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
704 // the device returned is not necessarily reachable via this output
705 // (filter later by setOutputDevices())
706 return getNewOutputDevices(mPrimaryOutput, fromCache);
707}
708
709status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
710{
François Gaffiedb1755b2023-09-01 11:50:35 +0200711 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100712 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
713 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
714 }
715 return INVALID_OPERATION;
716}
717
718status_t AudioPolicyManager::updateCallRoutingInternal(
719 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700720{
721 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700723 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200724 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700725 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100726 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700727 }
François Gaffie11d30102018-11-02 16:09:09 +0100728
Francois Gaffie716e1432019-01-14 16:58:59 +0100729 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100730 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200731
Eric Laurentb2fb4102024-06-21 12:25:26 +0000732 if (!fix_call_audio_patch()) {
733 disconnectTelephonyAudioSource(mCallRxSourceClient);
734 disconnectTelephonyAudioSource(mCallTxSourceClient);
735 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200736
737 if (rxDevices.isEmpty()) {
738 ALOGW("%s() no selected output device", __func__);
739 return INVALID_OPERATION;
740 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000741 if (txSourceDevice == nullptr) {
742 ALOGE("%s() selected input device not available", __func__);
743 return INVALID_OPERATION;
744 }
François Gaffiec005e562018-11-06 15:04:49 +0100745
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100746 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100747 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700748
François Gaffie9eb18552018-11-05 10:33:26 +0100749 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700750 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100751 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700752 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100753 // retrieve Rx Source and Tx Sink device descriptors
754 sp<DeviceDescriptor> rxSourceDevice =
755 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
756 String8(),
757 AUDIO_FORMAT_DEFAULT);
758 sp<DeviceDescriptor> txSinkDevice =
759 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
760 String8(),
761 AUDIO_FORMAT_DEFAULT);
762
763 // RX and TX Telephony device are declared by Primary Audio HAL
764 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
765 (telephonyRxModule->getHalVersionMajor() >= 3)) {
766 if (rxSourceDevice == 0 || txSinkDevice == 0) {
767 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100768 ALOGE("%s() no telephony Tx and/or RX device", __func__);
769 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100770 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100771 // createAudioPatchInternal now supports both HW / SW bridging
772 createRxPatch = true;
773 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100774 } else {
775 // If the RX device is on the primary HW module, then use legacy routing method for
776 // voice calls via setOutputDevice() on primary output.
777 // Otherwise, create two audio patches for TX and RX path.
778 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
779 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700780 // If the TX device is also on the primary HW module, setOutputDevice() will take care
781 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100782 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
783 (txSinkDevice != 0);
784 }
785 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
786 // Otherwise, create two audio patches for TX and RX path.
787 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000788 if (fix_call_audio_patch()) {
789 disconnectTelephonyAudioSource(mCallRxSourceClient);
790 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200791 if (!hasPrimaryOutput()) {
792 ALOGW("%s() no primary output available", __func__);
793 return INVALID_OPERATION;
794 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530795 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700796 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000797 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800798 // If the TX device is on the primary HW module but RX device is
799 // on other HW module, SinkMetaData of telephony input should handle it
800 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700801 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700802 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100803 // terminate active capture if on the same HW module as the call TX source device
804 // FIXME: would be better to refine to only inputs whose profile connects to the
805 // call TX device but this information is not in the audio patch and logic here must be
806 // symmetric to the one in startInput()
807 for (const auto& activeDesc : mInputs.getActiveInputs()) {
808 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
809 closeActiveClients(activeDesc);
810 }
811 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000813 } else if (fix_call_audio_patch()) {
814 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800815 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100816 if (waitMs != nullptr) {
817 *waitMs = muteWaitMs;
818 }
819 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800820}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700821
Mikhail Naganov100f0122018-11-29 11:22:16 -0800822bool AudioPolicyManager::isDeviceOfModule(
823 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
824 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
825 if (module != 0) {
826 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
827 .indexOf(devDesc) != NAME_NOT_FOUND
828 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
829 .indexOf(devDesc) != NAME_NOT_FOUND;
830 }
831 return false;
832}
833
David Lif85c5e32024-07-01 13:14:10 +0000834void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000836 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
837
838 if (fix_call_audio_patch()) {
839 if (mCallRxSourceClient != nullptr) {
840 DeviceVector rxDevices =
841 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
842 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
843 "connectTelephonyRxAudioSource(): no device found for call RX source");
844 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
845 if (mCallRxSourceClient->isConnected()
846 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
847 return;
848 }
849 disconnectTelephonyAudioSource(mCallRxSourceClient);
850 }
851 } else {
852 disconnectTelephonyAudioSource(mCallRxSourceClient);
853 }
854
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200855 const struct audio_port_config source = {
856 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
857 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
858 };
Eric Laurent541a2002024-01-15 18:11:42 +0100859 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000860
Eric Laurentccbd7872024-06-20 12:34:15 +0000861 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000862 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100863 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
864 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000865 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
866 mCallRxSourceClient->srcDevice()->toString().c_str(),
867 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200868 ALOGE_IF(mCallRxSourceClient == nullptr,
869 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200870}
871
Francois Gaffie601801d2021-06-22 13:27:39 +0200872void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200873{
Francois Gaffie601801d2021-06-22 13:27:39 +0200874 if (clientDesc == nullptr) {
875 return;
876 }
877 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
878 "%s error stopping audio source", __func__);
879 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200880}
881
882void AudioPolicyManager::connectTelephonyTxAudioSource(
883 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
884 uint32_t delayMs)
885{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200886 if (srcDevice == nullptr || sinkDevice == nullptr) {
887 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
888 return;
889 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000890
891 if (fix_call_audio_patch()) {
892 if (mCallTxSourceClient != nullptr) {
893 if (mCallTxSourceClient->isConnected()
894 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
895 return;
896 }
897 disconnectTelephonyAudioSource(mCallTxSourceClient);
898 }
899 } else {
900 disconnectTelephonyAudioSource(mCallTxSourceClient);
901 }
902
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200903 PatchBuilder patchBuilder;
904 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000905
Francois Gaffie601801d2021-06-22 13:27:39 +0200906 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200907 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
908
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200909 struct audio_port_config source = {};
910 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100911 mCallTxSourceClient = new SourceClientDescriptor(
912 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000913 mCommunnicationStrategy, toVolumeSource(aa), true,
914 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100915 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
916
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200917 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
918 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200919 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
920 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200921 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000922 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
923 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200924 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200925 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200926 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200927}
928
Eric Laurente0720872014-03-11 09:30:41 -0700929void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700930{
931 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100932 // store previous phone state for management of sonification strategy below
933 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100934 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100935
936 if (mEngine->setPhoneState(state) != NO_ERROR) {
937 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 return;
939 }
François Gaffie2110e042015-03-24 08:41:51 +0100940 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700941 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700942 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700943 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800944 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700945 }
946
François Gaffie2110e042015-03-24 08:41:51 +0100947 /**
948 * Switching to or from incall state or switching between telephony and VoIP lead to force
949 * routing command.
950 */
Eric Laurent74b71512019-11-06 17:21:57 -0800951 bool force = ((isStateInCall(oldState) != isStateInCall(state))
952 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700953
954 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700955 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700956
Eric Laurente552edb2014-03-10 17:42:56 -0700957 int delayMs = 0;
958 if (isStateInCall(state)) {
959 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100960 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
961 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700963 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700964 // mute media and sonification strategies and delay device switch by the largest
965 // latency of any output where either strategy is active.
966 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100967 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
968 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
969 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700970 (delayMs < (int)desc->latency()*2)) {
971 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700972 }
François Gaffiec005e562018-11-06 15:04:49 +0100973 setStrategyMute(musicStrategy, true, desc);
974 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
975 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
976 nullptr, true /*fromCache*/).types());
977 setStrategyMute(sonificationStrategy, true, desc);
978 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
979 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
980 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700981 }
982 }
983
François Gaffiedb1755b2023-09-01 11:50:35 +0200984 if (state == AUDIO_MODE_IN_CALL) {
985 (void)updateCallRouting(false /*fromCache*/, delayMs);
986 } else {
987 if (oldState == AUDIO_MODE_IN_CALL) {
988 disconnectTelephonyAudioSource(mCallRxSourceClient);
989 disconnectTelephonyAudioSource(mCallTxSourceClient);
990 }
991 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100992 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
993 // force routing command to audio hardware when ending call
994 // even if no device change is needed
995 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
996 rxDevices = mPrimaryOutput->devices();
997 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530998 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700999 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07001000 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001
jiabin3ff8d7d2022-12-13 06:27:44 +00001002 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001003 // reevaluate routing on all outputs in case tracks have been started during the call
1004 for (size_t i = 0; i < mOutputs.size(); i++) {
1005 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01001006 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001007 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1008 && desc->mPreferredAttrInfo != nullptr) {
1009 // If the output is using preferred mixer attributes and the audio mode is not normal,
1010 // the output need to reopen with default configuration.
1011 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1012 continue;
1013 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001014 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1015 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301016 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001017 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001018 }
1019 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001020 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001021
Eric Laurent96d1dda2022-03-14 17:14:19 +01001022 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1023
Eric Laurente552edb2014-03-10 17:42:56 -07001024 if (isStateInCall(state)) {
1025 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001026 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001027 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001028 }
1029
1030 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001031 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1032 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001033}
1034
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001035audio_mode_t AudioPolicyManager::getPhoneState() {
1036 return mEngine->getPhoneState();
1037}
1038
Eric Laurente0720872014-03-11 09:30:41 -07001039void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001040 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001041{
François Gaffie2110e042015-03-24 08:41:51 +01001042 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001043 if (config == mEngine->getForceUse(usage)) {
1044 return;
1045 }
Eric Laurente552edb2014-03-10 17:42:56 -07001046
François Gaffie2110e042015-03-24 08:41:51 +01001047 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1048 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1049 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
François Gaffie2110e042015-03-24 08:41:51 +01001051 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1052 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1053 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001054
1055 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001056 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001057
Eric Laurent22fcda22019-05-17 16:28:47 -07001058 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1059 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001060 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001061 }
1062
Eric Laurentdc462862016-07-19 12:29:53 -07001063 //FIXME: workaround for truncated touch sounds
1064 // to be removed when the problem is handled by system UI
1065 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001066 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1067 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1068 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001069
1070 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001071 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001072}
1073
Eric Laurente0720872014-03-11 09:30:41 -07001074void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001075{
1076 ALOGV("setSystemProperty() property %s, value %s", property, value);
1077}
1078
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079// Find an MSD output profile compatible with the parameters passed.
1080// When "directOnly" is set, restrict search to profiles for direct outputs.
1081sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1082 const DeviceVector& devices,
1083 uint32_t samplingRate,
1084 audio_format_t format,
1085 audio_channel_mask_t channelMask,
1086 audio_output_flags_t flags,
1087 bool directOnly)
1088{
1089 flags = getRelevantFlags(flags, directOnly);
1090
1091 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1092 if (msdModule != nullptr) {
1093 // for the msd module check if there are patches to the output devices
1094 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1095 HwModuleCollection modules;
1096 modules.add(msdModule);
1097 return searchCompatibleProfileHwModules(
1098 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1099 flags, directOnly);
1100 }
1101 }
1102 return nullptr;
1103}
1104
Michael Chana94fbb22018-04-24 14:31:19 +10001105// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1106// search to profiles for direct outputs.
1107sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001108 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001109 uint32_t samplingRate,
1110 audio_format_t format,
1111 audio_channel_mask_t channelMask,
1112 audio_output_flags_t flags,
1113 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001114{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001115 flags = getRelevantFlags(flags, directOnly);
1116
1117 return searchCompatibleProfileHwModules(
1118 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1119}
1120
1121audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1122 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001123 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001124 // only retain flags that will drive the direct output profile selection
1125 // if explicitly requested
1126 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001127 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001128 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1129 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001130 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001131 return flags;
1132}
Eric Laurent861a6282015-05-18 15:40:16 -07001133
Dorin Drimusecc9f422022-03-09 17:57:40 +01001134sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1135 const HwModuleCollection& hwModules,
1136 const DeviceVector& devices,
1137 uint32_t samplingRate,
1138 audio_format_t format,
1139 audio_channel_mask_t channelMask,
1140 audio_output_flags_t flags,
1141 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001142 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001143 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001144 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001145 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001146 samplingRate, NULL /*updatedSamplingRate*/,
1147 format, NULL /*updatedFormat*/,
1148 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001149 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001150 continue;
1151 }
1152 // reject profiles not corresponding to a device currently available
1153 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1154 continue;
1155 }
1156 // reject profiles if connected device does not support codec
1157 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1158 continue;
1159 }
1160 if (!directOnly) {
1161 return curProfile;
1162 }
1163
1164 // when searching for direct outputs, if several profiles are compatible, give priority
1165 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001166 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001167 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001168 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001169 }
1170 profile = curProfile;
1171 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1172 break;
1173 }
Eric Laurente552edb2014-03-10 17:42:56 -07001174 }
1175 }
Eric Laurent861a6282015-05-18 15:40:16 -07001176 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001177}
1178
Eric Laurentfa0f6742021-08-17 18:39:44 +02001179sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001180 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001181{
1182 for (const auto& hwModule : mHwModules) {
1183 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001184 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001185 continue;
1186 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001187 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001188 // reject profiles not corresponding to a device currently available
1189 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1190 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1191 continue;
1192 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001193 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1194 != devices.size()) {
1195 continue;
1196 }
1197 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001198 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1199 return curProfile;
1200 }
1201 }
1202 return nullptr;
1203}
1204
Eric Laurentf4e63452017-11-06 19:31:46 +00001205audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001206{
François Gaffiec005e562018-11-06 15:04:49 +01001207 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001208
1209 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1210 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1211 // format, flags, etc. This may result in some discrepancy for functions that utilize
1212 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1213 // and AudioSystem::getOutputSamplingRate().
1214
François Gaffie11d30102018-11-02 16:09:09 +01001215 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001216 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001217 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001218 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1219 }
1220 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001221
François Gaffie11d30102018-11-02 16:09:09 +01001222 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1223 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001224 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001225}
1226
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1228 const audio_attributes_t *srcAttr,
1229 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001230{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001231 if (srcAttr != NULL) {
1232 if (!isValidAttributes(srcAttr)) {
1233 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1234 __func__,
1235 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1236 srcAttr->tags);
1237 return BAD_VALUE;
1238 }
1239 *dstAttr = *srcAttr;
1240 } else {
1241 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1242 ALOGE("%s: invalid stream type", __func__);
1243 return BAD_VALUE;
1244 }
François Gaffiec005e562018-11-06 15:04:49 +01001245 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001246 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001247
1248 // Only honor audibility enforced when required. The client will be
1249 // forced to reconnect if the forced usage changes.
1250 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001251 dstAttr->flags = static_cast<audio_flags_mask_t>(
1252 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001253 }
1254
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001255 return NO_ERROR;
1256}
1257
Kevin Rocard153f92d2018-12-18 18:33:28 -08001258status_t AudioPolicyManager::getOutputForAttrInt(
1259 audio_attributes_t *resultAttr,
1260 audio_io_handle_t *output,
1261 audio_session_t session,
1262 const audio_attributes_t *attr,
1263 audio_stream_type_t *stream,
1264 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001265 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001266 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001267 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001268 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001270 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001271 bool *isSpatialized,
1272 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001273{
François Gaffiec005e562018-11-06 15:04:49 +01001274 DeviceVector outputDevices;
Robert Wufb971192024-10-30 21:54:35 +00001275 audio_port_handle_t requestedPortId = getFirstDeviceId(*selectedDeviceIds);
1276 selectedDeviceIds->clear();
François Gaffie11d30102018-11-02 16:09:09 +01001277 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001278 const sp<DeviceDescriptor> requestedDevice =
1279 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1280
Eric Laurent8a1095a2019-11-08 14:44:16 -08001281 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001282 *isSpatialized = false;
1283
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001284 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1285 if (status != NO_ERROR) {
1286 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001287 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001288 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001289 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001290 }
François Gaffiec005e562018-11-06 15:04:49 +01001291 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001292
François Gaffiec005e562018-11-06 15:04:49 +01001293 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1294 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001295
Oscar Azucena873d10f2023-01-12 18:34:42 -08001296 bool usePrimaryOutputFromPolicyMixes = false;
1297
Kevin Rocard153f92d2018-12-18 18:33:28 -08001298 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1299 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1300 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001301 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001302 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1303 .channel_mask = config->channel_mask,
1304 .format = config->format,
1305 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001306 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001307 mAvailableOutputDevices, requestedDevice, primaryMix,
1308 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001309 if (status != OK) {
1310 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001311 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001312
Kevin Rocard153f92d2018-12-18 18:33:28 -08001313 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001314 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001315 && (!audio_is_linear_pcm(config->format) ||
1316 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001317 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001318 return BAD_VALUE;
1319 }
1320 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001321 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001322 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1323 primaryMix->mDeviceAddress,
1324 AUDIO_FORMAT_DEFAULT);
1325 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001326 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001327 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1328 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001329 // if a direct output can be opened to deliver the track's multi-channel content to the
1330 // output rather than being downmixed by the primary output, then use this direct
1331 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1332 // mix.
1333 bool tryDirectForChannelMask = policyDesc != nullptr
1334 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1335 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001336 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001337 audio_io_handle_t newOutput;
1338 status = openDirectOutput(
1339 *stream, session, config,
1340 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001341 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001342 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001343 policyDesc = mOutputs.valueFor(newOutput);
1344 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001345 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001346 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001347 policyDesc = nullptr;
1348 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001349 }
1350 if (policyDesc != nullptr) {
1351 policyDesc->mPolicyMix = primaryMix;
1352 *output = policyDesc->mIoHandle;
Robert Wufb971192024-10-30 21:54:35 +00001353 if (policyMixDevice != nullptr) {
1354 selectedDeviceIds->push_back(policyMixDevice->getId());
1355 }
jiabin24ff57a2023-11-27 21:06:51 +00001356 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1357 // Remove direct flag as it is not on a direct output.
1358 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1359 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001360
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001361 ALOGV("getOutputForAttr() returns output %d", *output);
1362 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1363 *outputType = API_OUT_MIX_PLAYBACK;
1364 } else {
1365 *outputType = API_OUTPUT_LEGACY;
1366 }
1367 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001368 } else {
1369 if (policyMixDevice != nullptr) {
1370 ALOGE("%s, try to use primary mix but no output found", __func__);
1371 return INVALID_OPERATION;
1372 }
1373 // Fallback to default engine selection as the selected primary mix device is not
1374 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001375 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001376 }
François Gaffiec005e562018-11-06 15:04:49 +01001377 // Virtual sources must always be dynamicaly or explicitly routed
1378 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1379 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1380 return BAD_VALUE;
1381 }
1382 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1383 // in order to let the choice of the order to future vendor engine
1384 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001385
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001386 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001387 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001388 }
1389
Nadav Barb2f18162018-07-18 13:01:53 +03001390 // Set incall music only if device was explicitly set, and fallback to the device which is
1391 // chosen by the engine if not.
1392 // FIXME: provide a more generic approach which is not device specific and move this back
1393 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001394 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001395 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001396 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001397 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001398 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001399 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001400 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001401 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001402 }
1403 }
1404
François Gaffiec005e562018-11-06 15:04:49 +01001405 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1406 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1407 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001408
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001409 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001410 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001411 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001412 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001413 ALOGV("%s() Using MSD devices %s instead of devices %s",
1414 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001415 } else {
1416 *output = AUDIO_IO_HANDLE_NONE;
1417 }
1418 }
1419 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001420 sp<PreferredMixerAttributesInfo> info = nullptr;
1421 if (outputDevices.size() == 1) {
1422 info = getPreferredMixerAttributesInfo(
1423 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001424 mEngine->getProductStrategyForAttributes(*resultAttr),
1425 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001426 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1427 // and it is currently active.
1428 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001429 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001430 info = nullptr;
1431 }
jiabin8a096672024-09-18 18:20:24 +00001432
1433 if (info != nullptr && info->isBitPerfect() &&
1434 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1435 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1436 // Reject direct request if a preferred mixer config in use is bit-perfect.
1437 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1438 __func__);
1439 return BAD_VALUE;
1440 }
1441
jiabin220eea12024-05-17 17:55:20 +00001442 if (com::android::media::audioserver::
1443 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1444 if (info != nullptr && info->getUid() == uid &&
1445 info->configMatches(*config) &&
1446 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1447 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1448 [this, &outputDevices](audio_usage_t usage) {
1449 return mOutputs.isUsageActiveOnDevice(
1450 usage, outputDevices[0]); }))) {
1451 // Bit-perfect request is not allowed when the phone mode is not normal or
1452 // there is any higher priority user case active.
1453 return INVALID_OPERATION;
1454 }
1455 }
jiabina84c3d32022-12-02 18:59:55 +00001456 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001457 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001458 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001459 // The client will be active if the client is currently preferred mixer owner and the
1460 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001461 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001462 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001463 && info->getUid() == uid
1464 && *output != AUDIO_IO_HANDLE_NONE
1465 // When bit-perfect output is selected for the preferred mixer attributes owner,
1466 // only need to consider the config matches.
1467 && mOutputs.valueFor(*output)->isConfigurationMatched(
1468 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001469
1470 if (*isBitPerfect) {
1471 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1472 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001473 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001474 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001475 AudioProfileVector profiles;
1476 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1477 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001478 const auto channels = profiles[0]->getChannels();
1479 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1480 config->channel_mask = *channels.begin();
1481 }
1482 const auto sampleRates = profiles[0]->getSampleRates();
1483 if (!sampleRates.empty() &&
1484 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1485 config->sample_rate = *sampleRates.begin();
1486 }
jiabinf1c73972022-04-14 16:28:52 -07001487 config->format = profiles[0]->getFormat();
1488 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001489 return INVALID_OPERATION;
1490 }
Paul McLeanaa981192015-03-21 09:55:15 -07001491
Michael Chan6fb34492020-12-08 15:44:49 +11001492 for (auto &outputDevice : outputDevices) {
Robert Wufb971192024-10-30 21:54:35 +00001493 if (std::find(selectedDeviceIds->begin(), selectedDeviceIds->end(),
1494 outputDevice->getId()) == selectedDeviceIds->end()) {
1495 selectedDeviceIds->push_back(outputDevice->getId());
1496 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
1497 std::swap(selectedDeviceIds->front(), selectedDeviceIds->back());
1498 }
Michael Chan6fb34492020-12-08 15:44:49 +11001499 }
1500 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001501
Eric Laurent8a1095a2019-11-08 14:44:16 -08001502 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1503 *outputType = API_OUTPUT_TELEPHONY_TX;
1504 } else {
1505 *outputType = API_OUTPUT_LEGACY;
1506 }
1507
Robert Wufb971192024-10-30 21:54:35 +00001508 ALOGV("%s returns output %d selectedDeviceIds %s", __func__, *output,
1509 toString(*selectedDeviceIds).c_str());
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001510
1511 return NO_ERROR;
1512}
1513
1514status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1515 audio_io_handle_t *output,
1516 audio_session_t session,
1517 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001518 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001519 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001520 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001521 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001522 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001523 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001524 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001525 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001526 bool *isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -07001527 float *volume,
1528 bool *muted)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001529{
1530 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1531 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1532 return INVALID_OPERATION;
1533 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001534 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001535 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001536 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001537 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001538 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Robert Wufb971192024-10-30 21:54:35 +00001539 DeviceIdVector requestedDeviceIds = *selectedDeviceIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001540
1541 // Prevent from storing invalid requested device id in clients
Robert Wufb971192024-10-30 21:54:35 +00001542 DeviceIdVector sanitizedRequestedPortIds;
1543 for (auto deviceId : *selectedDeviceIds) {
1544 if (mAvailableOutputDevices.getDeviceFromId(deviceId) != nullptr) {
1545 sanitizedRequestedPortIds.push_back(deviceId);
1546 }
1547 }
1548 *selectedDeviceIds = sanitizedRequestedPortIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001549
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001550 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Robert Wufb971192024-10-30 21:54:35 +00001551 config, flags, selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001552 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1553 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001554 if (status != NO_ERROR) {
1555 return status;
1556 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001557 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001558 if (secondaryOutputs != nullptr) {
1559 for (auto &secondaryMix : secondaryMixes) {
1560 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1561 if (outputDesc != nullptr &&
jiabin6838cda2024-11-22 21:54:30 +00001562 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE &&
1563 outputDesc->mIoHandle != *output) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001564 secondaryOutputs->push_back(outputDesc->mIoHandle);
1565 weakSecondaryOutputDescs.push_back(outputDesc);
1566 }
1567 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001568 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001569
Eric Laurent8fc147b2018-07-22 19:13:55 -07001570 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001571 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001572 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001573 };
jiabin4ef93452019-09-10 14:29:54 -07001574 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001575
Eric Laurentc209fe42020-06-05 18:11:23 -07001576 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Robert Wufb971192024-10-30 21:54:35 +00001577 // TODO(b/367816690): Add device id sets to TrackClientDescriptor
Eric Laurent8fc147b2018-07-22 19:13:55 -07001578 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001579 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Robert Wufb971192024-10-30 21:54:35 +00001580 getFirstDeviceId(sanitizedRequestedPortIds), *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001581 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001582 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001583 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001584 std::move(weakSecondaryOutputDescs),
1585 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001586 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001587
Andy Hung6b137d12024-08-27 22:35:17 +00001588 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001589 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001590
Robert Wufb971192024-10-30 21:54:35 +00001591 ALOGV("%s() returns output %d requestedPortIds %s selectedDeviceIds %s for port ID %d",
1592 __func__, *output, toString(requestedDeviceIds).c_str(),
1593 toString(*selectedDeviceIds).c_str(), *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001594
Eric Laurente83b55d2014-11-14 10:06:21 -08001595 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001596}
1597
Eric Laurentc529cf62020-04-17 18:19:10 -07001598status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1599 audio_session_t session,
1600 const audio_config_t *config,
1601 audio_output_flags_t flags,
1602 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001603 audio_io_handle_t *output,
1604 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001605
1606 *output = AUDIO_IO_HANDLE_NONE;
1607
1608 // skip direct output selection if the request can obviously be attached to a mixed output
1609 // and not explicitly requested
1610 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1611 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1612 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1613 return NAME_NOT_FOUND;
1614 }
1615
Mikhail Naganov806170e2024-09-05 17:26:50 -07001616 // Reject flag combinations that do not make sense. Note that the requested flags might not
1617 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1618 // combine the requested flags with its own flags, yielding an unsupported combination.
1619 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1620 return NAME_NOT_FOUND;
1621 }
1622
Eric Laurentc529cf62020-04-17 18:19:10 -07001623 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1624 // This prevents creating an offloaded track and tearing it down immediately after start
1625 // when audioflinger detects there is an active non offloadable effect.
1626 // FIXME: We should check the audio session here but we do not have it in this context.
1627 // This may prevent offloading in rare situations where effects are left active by apps
1628 // in the background.
1629 sp<IOProfile> profile;
1630 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1631 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1632 profile = getProfileForOutput(
1633 devices, config->sample_rate, config->format, config->channel_mask,
1634 flags, true /* directOnly */);
1635 }
1636
1637 if (profile == nullptr) {
1638 return NAME_NOT_FOUND;
1639 }
1640
1641 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1642 for (size_t i = 0; i < mOutputs.size(); i++) {
1643 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1644 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1645 // reuse direct output if currently open by the same client
1646 // and configured with same parameters
1647 if ((config->sample_rate == desc->getSamplingRate()) &&
1648 (config->format == desc->getFormat()) &&
1649 (config->channel_mask == desc->getChannelMask()) &&
1650 (session == desc->mDirectClientSession)) {
1651 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301652 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001653 mOutputs.keyAt(i), session);
1654 *output = mOutputs.keyAt(i);
1655 return NO_ERROR;
1656 }
1657 }
1658 }
1659
1660 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001661 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301662 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1663 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001664 return NAME_NOT_FOUND;
1665 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1666 // MMAP gracefully handles lack of an exclusive track resource by mixing
1667 // above the audio framework. For AAudio to know that the limit is reached,
1668 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301669 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1670 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001671 return NAME_NOT_FOUND;
1672 } else {
1673 // Close outputs on this profile, if available, to free resources for this request
1674 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1675 const auto desc = mOutputs.valueAt(i);
1676 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301677 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1678 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001679 closeOutput(desc->mIoHandle);
1680 }
1681 }
1682 }
1683 }
1684
1685 // Unable to close streams to find free resources for this request
1686 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301687 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1688 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001689 return NAME_NOT_FOUND;
1690 }
1691
Atneya Nairb16666a2023-12-11 20:18:33 -08001692 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001693
Michael Chan6fb34492020-12-08 15:44:49 +11001694 // An MSD patch may be using the only output stream that can service this request. Release
1695 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001696 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001697
Eric Laurentf1f22e72021-07-13 14:04:14 +02001698 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001699 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001700 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001701
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001702 // only accept an output with the requested parameters, unless the format can be IEC61937
1703 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1704 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1705 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1706 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001707 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001708 (!ignoreRequestedParametersCheck &&
1709 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1710 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1711 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001712 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1713 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1714 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1715 config->channel_mask, outputDesc->getChannelMask());
1716 if (*output != AUDIO_IO_HANDLE_NONE) {
1717 outputDesc->close();
1718 }
1719 // fall back to mixer output if possible when the direct output could not be open
1720 if (audio_is_linear_pcm(config->format) &&
1721 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1722 return NAME_NOT_FOUND;
1723 }
1724 *output = AUDIO_IO_HANDLE_NONE;
1725 return BAD_VALUE;
1726 }
1727 outputDesc->mDirectOpenCount = 1;
1728 outputDesc->mDirectClientSession = session;
1729
1730 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001731 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1732 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1733 hwModule->getHalVersionMajor() >= 3) {
1734 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1735 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001736 mPreviousOutputs = mOutputs;
1737 ALOGV("%s returns new direct output %d", __func__, *output);
1738 mpClientInterface->onAudioPortListUpdate();
1739 return NO_ERROR;
1740}
1741
François Gaffie11d30102018-11-02 16:09:09 +01001742audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1743 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001744 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001745 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001746 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001747 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001748 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001749 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001750 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001751{
Andy Hungc88b0642018-04-27 15:42:35 -07001752 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001753
jiabine375d412019-02-26 12:54:53 -08001754 // Discard haptic channel mask when forcing muting haptic channels.
1755 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001756 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1757 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001758
Eric Laurente552edb2014-03-10 17:42:56 -07001759 // open a direct output if required by specified parameters
1760 //force direct flag if offload flag is set: offloading implies a direct output stream
1761 // and all common behaviors are driven by checking only the direct flag
1762 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001763 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1764 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001765 }
Nadav Bar766fb022018-01-07 12:18:03 +02001766 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1767 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001768 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001769
1770 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1771
Eric Laurente83b55d2014-11-14 10:06:21 -08001772 // only allow deep buffering for music stream type
1773 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001774 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001775 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001776 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001777 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001778 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001779 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001780 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001781 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001782 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001783 audio_is_linear_pcm(config->format) &&
1784 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001785 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001786 AUDIO_OUTPUT_FLAG_DIRECT);
1787 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001788 }
Eric Laurente552edb2014-03-10 17:42:56 -07001789
Carter Hsua3abb402021-10-26 11:11:20 +08001790 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1791 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1792 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1793 }
1794
Eric Laurentf9230d52024-01-26 18:49:09 +01001795 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001796 // was specified and offload or direct playback is not explicitly requested, and there is no
1797 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001798 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001799 if (mSpatializerOutput != nullptr &&
1800 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1801 prefMixerConfigInfo == nullptr &&
1802 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1803 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001804 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001805 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001806 }
1807
Eric Laurentc529cf62020-04-17 18:19:10 -07001808 audio_config_t directConfig = *config;
1809 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001810
1811 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1812 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001813 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001814 return output;
1815 }
1816
Eric Laurent14cbfca2016-03-17 09:42:16 -07001817 // A request for HW A/V sync cannot fallback to a mixed output because time
1818 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001819 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001820 return AUDIO_IO_HANDLE_NONE;
1821 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001822 // A request for Tuner cannot fallback to a mixed output
1823 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1824 return AUDIO_IO_HANDLE_NONE;
1825 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001826
Eric Laurente552edb2014-03-10 17:42:56 -07001827 // ignoring channel mask due to downmix capability in mixer
1828
1829 // open a non direct output
1830
1831 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001832 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001833 // get which output is suitable for the specified stream. The actual
1834 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001835 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001836 if (prefMixerConfigInfo != nullptr) {
1837 for (audio_io_handle_t outputHandle : outputs) {
1838 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1839 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1840 output = outputHandle;
1841 break;
1842 }
1843 }
1844 if (output == AUDIO_IO_HANDLE_NONE) {
1845 // No output open with the preferred profile. Open a new one.
1846 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1847 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1848 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1849 config.format = prefMixerConfigInfo->getConfigBase().format;
1850 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1851 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1852 &config, prefMixerConfigInfo->getFlags());
1853 if (preferredOutput == nullptr) {
1854 ALOGE("%s failed to open output with preferred mixer config", __func__);
1855 } else {
1856 output = preferredOutput->mIoHandle;
1857 }
1858 }
1859 } else {
1860 // at this stage we should ignore the DIRECT flag as no direct output could be
1861 // found earlier
1862 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001863 if (com::android::media::audioserver::
1864 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1865 // If the preferred mixer attributes is null, do not select the bit-perfect output
1866 // unless the bit-perfect output is the only output.
1867 // The bit-perfect output can exist while the passed in preferred mixer attributes
1868 // info is null when it is a high priority client. The high priority clients are
1869 // ringtone or alarm, which is not a bit-perfect use case.
1870 size_t i = 0;
1871 while (i < outputs.size() && outputs.size() > 1) {
1872 auto desc = mOutputs.valueFor(outputs[i]);
1873 // The output descriptor must not be null here.
1874 if (desc->isBitPerfect()) {
1875 outputs.removeItemsAt(i);
1876 } else {
1877 i += 1;
1878 }
1879 }
1880 }
jiabina84c3d32022-12-02 18:59:55 +00001881 output = selectOutput(
1882 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1883 }
Eric Laurente552edb2014-03-10 17:42:56 -07001884 }
François Gaffie11d30102018-11-02 16:09:09 +01001885 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001886 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001887 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001888
Eric Laurente552edb2014-03-10 17:42:56 -07001889 return output;
1890}
1891
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001892sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001893 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1894 mAvailableInputDevices);
1895 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1896}
1897
1898DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1899 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1900 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901}
1902
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001905 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1906 if (msdModule != 0) {
1907 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1908 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1909 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1910 const struct audio_port_config *source = &patch->mPatch.sources[j];
1911 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1912 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001913 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001914 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001915 }
1916 }
1917 }
1918 return msdPatches;
1919}
1920
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001921bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1922 ssize_t index = mAudioPatches.indexOfKey(handle);
1923 if (index < 0) {
1924 return false;
1925 }
1926 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1927 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1928 if (msdModule == nullptr) {
1929 return false;
1930 }
1931 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1932 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1933 return true;
1934 }
1935 index = getMsdOutputPatches().indexOfKey(handle);
1936 if (index < 0) {
1937 return false;
1938 }
1939 return true;
1940}
1941
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001942status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1943 const InputProfileCollection &inputProfiles,
1944 const OutputProfileCollection &outputProfiles,
1945 const sp<DeviceDescriptor> &sourceDevice,
1946 const sp<DeviceDescriptor> &sinkDevice,
1947 AudioProfileVector& sourceProfiles,
1948 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001949 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001950 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 return NO_INIT;
1952 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001953 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001954 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001955 return NO_INIT;
1956 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001957 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001958 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1959 inProfile->supportsDevice(sourceDevice)) {
1960 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001961 }
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001964 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001965 outProfile->supportsDevice(sinkDevice)) {
1966 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001967 }
1968 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969 return NO_ERROR;
1970}
1971
1972status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1973 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1974 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1975{
Dean Wheatley16809da2022-12-09 14:55:46 +11001976 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1977 static const std::vector<audio_format_t> formatsOrder = {{
1978 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001979 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1980 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001981 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1982 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1983 // preferred).
1984 std::vector<audio_channel_mask_t> masks = {{
1985 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1986 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1987 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1988 // insert index masks (higher counts most preferred) as preferred over position masks
1989 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1990 masks.insert(
1991 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1992 }
1993 return masks;
1994 }();
1995
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001996 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001997 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1998 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001999 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002000 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
2001 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07002002 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002003 }
2004 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
2005 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
2006 sinkConfig->format = bestSinkConfig.format;
2007 // For encoded streams force direct flag to prevent downstream mixing.
2008 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2009 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002010 if (audio_is_iec61937_compatible(sinkConfig->format)) {
2011 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002012 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002013 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2014 // raw and IEC61937 framed streams.
2015 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2016 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2017 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002018 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2019 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002020 sourceConfig->channel_mask =
2021 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2022 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2023 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002024 sourceConfig->format = bestSinkConfig.format;
2025 // Copy input stream directly without any processing (e.g. resampling).
2026 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2027 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2028 if (hwAvSync) {
2029 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2030 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2031 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2032 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2033 }
2034 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2035 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2036 sinkConfig->config_mask |= config_mask;
2037 sourceConfig->config_mask |= config_mask;
2038 return NO_ERROR;
2039}
2040
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002041PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2042 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002043{
2044 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002045 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2046 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2047 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2048 if (deviceModule == nullptr) {
2049 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2050 return patchBuilder;
2051 }
2052 const InputProfileCollection inputProfiles = msdIsSource ?
2053 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2054 const OutputProfileCollection outputProfiles = msdIsSource ?
2055 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2056
2057 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2058 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2059 device : getMsdAudioOutDevices().itemAt(0);
2060 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2061
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002062 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2063 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002064 AudioProfileVector sourceProfiles;
2065 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002066 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2067 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002068 for (auto hwAvSync : { true, false }) {
2069 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2070 sourceProfiles, sinkProfiles) != NO_ERROR) {
2071 continue;
2072 }
2073 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2074 &sinkConfig) == NO_ERROR) {
2075 // Found a matching config. Re-create PatchBuilder with this config.
2076 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2077 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002078 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002079 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002080 " supporting PCM format conversion.", __func__);
2081 return patchBuilder;
2082}
2083
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002084status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002085 DeviceVector devices;
2086 if (outputDevices != nullptr && outputDevices->size() > 0) {
2087 devices.add(*outputDevices);
2088 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002089 // Use media strategy for unspecified output device. This should only
2090 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2091 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002092 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002093 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002094 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002095 }
Michael Chan6fb34492020-12-08 15:44:49 +11002096 std::vector<PatchBuilder> patchesToCreate;
2097 for (auto i = 0u; i < devices.size(); ++i) {
2098 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002099 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002100 }
2101 // Retain only the MSD patches associated with outputDevices request.
2102 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002103 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002104 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2105 auto retainedPatch = false;
2106 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2107 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2108 patchesToRemove.removeItemsAt(i);
2109 retainedPatch = true;
2110 break;
2111 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002112 }
Michael Chan6fb34492020-12-08 15:44:49 +11002113 if (retainedPatch) {
2114 it = patchesToCreate.erase(it);
2115 continue;
2116 }
2117 ++it;
2118 }
2119 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2120 return NO_ERROR;
2121 }
2122 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2123 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002124 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002125 }
Michael Chan6fb34492020-12-08 15:44:49 +11002126 status_t status = NO_ERROR;
2127 for (const auto &p : patchesToCreate) {
2128 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2129 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2130 char message[256];
2131 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2132 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2133 currStatus == NO_ERROR ? "Success" : "Error",
2134 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2135 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2136 if (currStatus == NO_ERROR) {
2137 ALOGD("%s", message);
2138 } else {
2139 ALOGE("%s", message);
2140 if (status == NO_ERROR) {
2141 status = currStatus;
2142 }
2143 }
2144 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002145 return status;
2146}
2147
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002148void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2149 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002150 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 && devices.getDevice(sink->ext.device.type,
2155 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2156 releaseAudioPatch(patch->getHandle(), mUidCached);
2157 break;
2158 }
2159 }
2160 }
2161}
2162
Dorin Drimus94d94412022-02-02 09:05:02 +01002163bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002164 DeviceVector devicesToCheck =
2165 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002166 AudioPatchCollection msdPatches = getMsdOutputPatches();
2167 for (size_t i = 0; i < msdPatches.size(); i++) {
2168 const auto& patch = msdPatches[i];
2169 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2170 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2171 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2172 const auto& foundDevice = devicesToCheck.getDevice(
2173 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2174 if (foundDevice != nullptr) {
2175 devicesToCheck.remove(foundDevice);
2176 if (devicesToCheck.isEmpty()) {
2177 return true;
2178 }
2179 }
2180 }
2181 }
2182 }
2183 return false;
2184}
2185
Eric Laurente0720872014-03-11 09:30:41 -07002186audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002187 audio_output_flags_t flags,
2188 audio_format_t format,
2189 audio_channel_mask_t channelMask,
2190 uint32_t samplingRate,
2191 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002192{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002193 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2194 "%s called with format %#x", __func__, format);
2195
jiabinebb6af42020-06-09 17:31:17 -07002196 // Return the output that haptic-generating attached to when 1) session id is specified,
2197 // 2) haptic-generating effect exists for given session id and 3) the output that
2198 // haptic-generating effect attached to is in given outputs.
2199 if (sessionId != AUDIO_SESSION_NONE) {
2200 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2201 sessionId, FX_IID_HAPTICGENERATOR);
2202 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2203 return hapticGeneratingOutput;
2204 }
2205 }
2206
Eric Laurent16c66dd2019-05-01 17:54:10 -07002207 // Flags disqualifying an output: the match must happen before calling selectOutput()
2208 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2209 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2210
2211 // Flags expressing a functional request: must be honored in priority over
2212 // other criteria
2213 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2214 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002215 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2216 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002217 // Flags expressing a performance request: have lower priority than serving
2218 // requested sampling rate or channel mask
2219 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2220 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2221 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2222
2223 const audio_output_flags_t functionalFlags =
2224 (audio_output_flags_t)(flags & kFunctionalFlags);
2225 const audio_output_flags_t performanceFlags =
2226 (audio_output_flags_t)(flags & kPerformanceFlags);
2227
2228 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2229
Eric Laurente552edb2014-03-10 17:42:56 -07002230 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002231 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002232 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002233 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002235 // with tiebreak preferring the minimum number of extra functional flags
2236 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002237 // 3: the output supporting the exact channel mask
2238 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002239 // 5: the output with the highest sampling rate if the requested sample rate is
2240 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002241 // 6: the output with the highest number of requested performance flags
2242 // 7: the output with the bit depth the closest to the requested one
2243 // 8: the primary output
2244 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Eric Laurent16c66dd2019-05-01 17:54:10 -07002246 // matching criteria values in priority order for best matching output so far
2247 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002248
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002249 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002250 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2251 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2252 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002253
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002254 for (audio_io_handle_t output : outputs) {
2255 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256 // matching criteria values in priority order for current output
2257 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002258
Eric Laurent16c66dd2019-05-01 17:54:10 -07002259 if (outputDesc->isDuplicated()) {
2260 continue;
2261 }
2262 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2263 continue;
2264 }
Eric Laurent8838a382014-09-08 16:44:28 -07002265
Eric Laurent16c66dd2019-05-01 17:54:10 -07002266 // If haptic channel is specified, use the haptic output if present.
2267 // When using haptic output, same audio format and sample rate are required.
2268 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002269 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002270 // skip if haptic channel specified but output does not support it, or output support haptic
2271 // but there is no haptic channel requested AND no orphan haptic effect exist
2272 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2273 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002274 continue;
2275 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002276 // In the case of audio-coupled-haptic playback, there is no format conversion and
2277 // resampling in the framework, same format/channel/sampleRate for client and the output
2278 // thread is required. In the case of HapticGenerator effect, do not require format
2279 // matching.
2280 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2281 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002282 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002283 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002284 }
2285
2286 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002287 const int matchingFunctionalFlags =
2288 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2289 const int totalFunctionalFlags =
2290 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2291 // Prefer matching functional flags, but subtract unnecessary functional flags.
2292 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002293
2294 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002295 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2296 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002297 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2298 channelCount <= outputChannelCount) {
2299 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002300 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2301 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002302 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002303 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002304 currentMatchCriteria[3] = outputChannelCount;
2305 }
2306
2307 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002308 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002309 int diff; // avoid unsigned integer overflow.
2310 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2311
2312 // prefer the closest output sampling rate greater than or equal to target
2313 // if none exists, prefer the closest output sampling rate less than target.
2314 //
2315 // criteria is offset to make non-negative.
2316 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002317 }
2318
2319 // performance flags match
2320 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2321
2322 // format match
2323 if (format != AUDIO_FORMAT_INVALID) {
2324 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002325 PolicyAudioPort::kFormatDistanceMax -
2326 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002327 }
2328
2329 // primary output match
2330 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2331
2332 // compare match criteria by priority then value
2333 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2334 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2335 bestMatchCriteria = currentMatchCriteria;
2336 bestOutput = output;
2337
2338 std::stringstream result;
2339 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2340 std::ostream_iterator<int>(result, " "));
2341 ALOGV("%s new bestOutput %d criteria %s",
2342 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002343 }
2344 }
2345
Eric Laurent16c66dd2019-05-01 17:54:10 -07002346 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002347}
2348
Eric Laurent8fc147b2018-07-22 19:13:55 -07002349status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002350{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002351 ALOGV("%s portId %d", __FUNCTION__, portId);
2352
2353 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2354 if (outputDesc == 0) {
2355 ALOGW("startOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002356 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002357 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002358 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002359
Eric Laurent8fc147b2018-07-22 19:13:55 -07002360 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002361 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002362
jiabin220eea12024-05-17 17:55:20 +00002363 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2364 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2365 && outputDesc->isBitPerfect()) {
2366 // Usually, APM selects bit-perfect output for high priority use cases only when
2367 // bit-perfect output is the only output that can be routed to the selected device.
2368 // However, here is no need to play high priority use cases such as ringtone and alarm
2369 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2370 // can attach to new output.
2371 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2372 __func__, client->stream());
2373 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2374 return DEAD_OBJECT;
2375 }
2376
Eric Laurent733ce942017-12-07 12:18:25 -08002377 status_t status = outputDesc->start();
2378 if (status != NO_ERROR) {
2379 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002380 }
2381
Eric Laurent97ac8712018-07-27 18:59:02 -07002382 uint32_t delayMs;
2383 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002384
2385 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002386 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002387 if (status == DEAD_OBJECT) {
2388 sp<SwAudioOutputDescriptor> desc =
2389 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2390 if (desc == nullptr) {
2391 // This is not common, it may indicate something wrong with the HAL.
2392 ALOGE("%s unable to open output with default config", __func__);
2393 return status;
2394 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002395 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002396 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002397 }
jiabina84c3d32022-12-02 18:59:55 +00002398
2399 // If the client is the first one active on preferred mixer parameters, reopen the output
2400 // if the current mixer parameters doesn't match the preferred one.
2401 if (outputDesc->devices().size() == 1) {
2402 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2403 outputDesc->devices()[0]->getId(), client->strategy());
2404 if (info != nullptr && info->getUid() == client->uid()) {
2405 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2406 info->getConfigBase(), info->getFlags())) {
2407 stopSource(outputDesc, client);
2408 outputDesc->stop();
2409 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2410 config.channel_mask = info->getConfigBase().channel_mask;
2411 config.sample_rate = info->getConfigBase().sample_rate;
2412 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002413 sp<SwAudioOutputDescriptor> desc =
2414 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2415 if (desc == nullptr) {
2416 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002417 }
jiabin220eea12024-05-17 17:55:20 +00002418 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002419 // Intentionally return error to let the client side resending request for
2420 // creating and starting.
2421 return DEAD_OBJECT;
2422 }
2423 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002424 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002425 // If it is first bit-perfect client, reroute all clients that will be routed to
2426 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2427 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002428 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002429 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002430 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2431 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002432 continue;
2433 }
jiabine6b87492024-09-18 23:36:14 +00002434 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2435 outputsToResetDevice.push_back(mOutputs[i]);
2436 }
jiabine3d1f552023-06-14 17:42:17 +00002437 for (const auto& c : mOutputs[i]->getClientIterable()) {
2438 clientsToInvalidate.push_back(c->portId());
2439 }
2440 }
2441 if (!clientsToInvalidate.empty()) {
2442 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2443 __func__);
2444 mpClientInterface->invalidateTracks(clientsToInvalidate);
2445 }
jiabine6b87492024-09-18 23:36:14 +00002446 for (const auto& output : outputsToResetDevice) {
2447 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2448 }
jiabine3d1f552023-06-14 17:42:17 +00002449 }
jiabina84c3d32022-12-02 18:59:55 +00002450 }
2451 }
2452
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002453 if (client->hasPreferredDevice()) {
2454 // playback activity with preferred device impacts routing occurred, inform upper layers
2455 mpClientInterface->onRoutingUpdated();
2456 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002457 if (delayMs != 0) {
2458 usleep(delayMs * 1000);
2459 }
2460
jiabin220eea12024-05-17 17:55:20 +00002461 if (status == NO_ERROR &&
2462 outputDesc->mPreferredAttrInfo != nullptr &&
2463 outputDesc->isBitPerfect() &&
2464 com::android::media::audioserver::
2465 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2466 // A new client is started on bit-perfect output, update all clients internal mute.
2467 updateClientsInternalMute(outputDesc);
2468 }
2469
Eric Laurentc75307b2015-03-17 15:29:32 -07002470 return status;
2471}
2472
Eric Laurent96d1dda2022-03-14 17:14:19 +01002473bool AudioPolicyManager::isLeUnicastActive() const {
2474 if (isInCall()) {
2475 return true;
2476 }
2477 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2478}
2479
2480bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2481 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2482 return false;
2483 }
2484 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2485 ALOGV("%s active %d", __func__, active);
2486 return active;
2487}
2488
Eric Laurent97ac8712018-07-27 18:59:02 -07002489status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2490 const sp<TrackClientDescriptor>& client,
2491 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002492{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002493 // cannot start playback of STREAM_TTS if any other output is being used
2494 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002495
2496 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002497 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002498 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002499 auto clientStrategy = client->strategy();
2500 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002501 if (stream == AUDIO_STREAM_TTS) {
2502 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002503 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002504 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002505 return INVALID_OPERATION;
2506 } else {
2507 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2508 }
2509 } else {
2510 // some playback other than beacon starts
2511 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2512 }
2513
Eric Laurent77305a62016-07-25 16:39:22 -07002514 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002515 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002516 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002517
François Gaffie11d30102018-11-02 16:09:09 +01002518 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002519 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002520 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002521 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002522 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002523 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002524 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002525 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002526 } else {
2527 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002528 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002529 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2530 AUDIO_FORMAT_DEFAULT);
2531 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2532 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 }
2534
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002535 // requiresMuteCheck is false when we can bypass mute strategy.
2536 // It covers a common case when there is no materially active audio
2537 // and muting would result in unnecessary delay and dropped audio.
2538 const uint32_t outputLatencyMs = outputDesc->latency();
2539 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002540 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002541
Eric Laurente552edb2014-03-10 17:42:56 -07002542 // increment usage count for this stream on the requested output:
2543 // NOTE that the usage count is the same for duplicated output and hardware output which is
2544 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002545 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002546
2547 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002548 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002549 // Preferred device may be exclusive, use only if no other active clients on this output
2550 devices = DeviceVector(
2551 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2552 } else {
2553 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2554 }
François Gaffie11d30102018-11-02 16:09:09 +01002555 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002556 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 }
2558 }
Eric Laurente552edb2014-03-10 17:42:56 -07002559
François Gaffiec005e562018-11-06 15:04:49 +01002560 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002561 selectOutputForMusicEffects();
2562 }
2563
François Gaffie1c878552018-11-22 16:53:21 +01002564 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002565 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002566 if (devices.isEmpty()) {
2567 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002568 }
François Gaffiec005e562018-11-06 15:04:49 +01002569 bool shouldWait =
2570 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2571 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2572 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002573 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002574 const bool needToCloseBitPerfectOutput =
2575 (com::android::media::audioserver::
2576 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2577 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2578 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002579 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002580 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002581 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002582 // An output has a shared device if
2583 // - managed by the same hw module
2584 // - supports the currently selected device
2585 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002586 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002587
Eric Laurent77305a62016-07-25 16:39:22 -07002588 // force a device change if any other output is:
2589 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002590 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002591 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002592 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002593 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002594 // change the device currently selected by the other output.
2595 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002596 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002597 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002598 force = true;
2599 }
2600 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002601 // a notification so that audio focus effect can propagate, or that a mute/unmute
2602 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002603 const uint32_t latencyMs = desc->latency();
2604 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2605
2606 if (shouldWait && isActive && (waitMs < latencyMs)) {
2607 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002608 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002609
2610 // Require mute check if another output is on a shared device
2611 // and currently active to have proper drain and avoid pops.
2612 // Note restoring AudioTracks onto this output needs to invoke
2613 // a volume ramp if there is no mute.
2614 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002615
2616 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2617 outputsToReopen.push_back(desc);
2618 }
Eric Laurente552edb2014-03-10 17:42:56 -07002619 }
2620 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002621
jiabin220eea12024-05-17 17:55:20 +00002622 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002623 // If the output is open with preferred mixer attributes, but the routed device is
2624 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2625 // changed.
2626 return DEAD_OBJECT;
2627 }
jiabin220eea12024-05-17 17:55:20 +00002628 for (auto& outputToReopen : outputsToReopen) {
2629 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2630 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002631 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302632 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2633 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002634
Eric Laurente552edb2014-03-10 17:42:56 -07002635 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002636 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002637 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002638 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002639 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002640 outputDesc->useHwGain() /*force*/)) {
2641 // request AudioService to reinitialize the volume curves asynchronously
2642 ALOGE("checkAndSetVolume failed, requesting volume range init");
2643 mpClientInterface->onVolumeRangeInitRequest();
2644 };
Eric Laurente552edb2014-03-10 17:42:56 -07002645
2646 // update the outputs if starting an output with a stream that can affect notification
2647 // routing
2648 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002649
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002650 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002651 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002652 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002653 }
Eric Laurentdc462862016-07-19 12:29:53 -07002654
2655 if (waitMs > muteWaitMs) {
2656 *delayMs = waitMs - muteWaitMs;
2657 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002658
2659 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2660 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2661 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2662 // change occurs after the MixerThread starts and causes a stream volume
2663 // glitch.
2664 //
2665 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002666 }
Eric Laurentdc462862016-07-19 12:29:53 -07002667
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002668 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002669 mEngine->getForceUse(
2670 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002671 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002672 }
2673
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 // Automatically enable the remote submix input when output is started on a re routing mix
2675 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002676 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2677 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002678 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2679 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2680 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002681 "remote-submix",
2682 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002683 }
2684
Eric Laurent96d1dda2022-03-14 17:14:19 +01002685 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2686
Eric Laurente552edb2014-03-10 17:42:56 -07002687 return NO_ERROR;
2688}
2689
Eric Laurent96d1dda2022-03-14 17:14:19 +01002690void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2691 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2692 bool isUnicastActive = isLeUnicastActive();
2693
2694 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002695 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002696 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2697 for (size_t i = 0; i < mOutputs.size(); i++) {
2698 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2699 if (desc != ignoredOutput && desc->isActive()
2700 && ((isUnicastActive &&
2701 !desc->devices().
2702 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2703 || (wasUnicastActive &&
2704 !desc->devices().getDevicesFromTypes(
2705 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2706 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2707 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002708 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002709 // If the device is using preferred mixer attributes, the output need to reopen
2710 // with default configuration when the new selected devices are different from
2711 // current routing devices.
2712 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2713 continue;
2714 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302715 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002716 // re-apply device specific volume if not done by setOutputDevice()
2717 if (!force) {
2718 applyStreamVolumes(desc, newDevices.types(), delayMs);
2719 }
2720 }
2721 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002722 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002723 }
2724}
2725
Eric Laurent8fc147b2018-07-22 19:13:55 -07002726status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002727{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002728 ALOGV("%s portId %d", __FUNCTION__, portId);
2729
2730 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2731 if (outputDesc == 0) {
2732 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002733 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002734 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002735 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002736
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002737 if (client->hasPreferredDevice(true)) {
2738 // playback activity with preferred device impacts routing occurred, inform upper layers
2739 mpClientInterface->onRoutingUpdated();
2740 }
2741
Eric Laurent97ac8712018-07-27 18:59:02 -07002742 ALOGV("stopOutput() output %d, stream %d, session %d",
2743 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002744
Eric Laurent97ac8712018-07-27 18:59:02 -07002745 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002746
Eric Laurent733ce942017-12-07 12:18:25 -08002747 if (status == NO_ERROR ) {
2748 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002749 } else {
2750 return status;
2751 }
2752
2753 if (outputDesc->devices().size() == 1) {
2754 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2755 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002756 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002757 if (info != nullptr && info->getUid() == client->uid()) {
2758 info->decreaseActiveClient();
2759 if (info->getActiveClientCount() == 0) {
2760 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002761 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002762 }
2763 }
jiabin220eea12024-05-17 17:55:20 +00002764 if (com::android::media::audioserver::
2765 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2766 !outputReopened && outputDesc->isBitPerfect()) {
2767 // Only need to update the clients' internal mute when the output is bit-perfect and it
2768 // is not reopened.
2769 updateClientsInternalMute(outputDesc);
2770 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002771 }
2772 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002773}
2774
Eric Laurent97ac8712018-07-27 18:59:02 -07002775status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2776 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002777{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002778 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002779 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002780 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002781 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002782
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002783 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2784
François Gaffie1c878552018-11-22 16:53:21 +01002785 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2786 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002787 // Automatically disable the remote submix input when output is stopped on a
2788 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002789 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002790 if (isSingleDeviceType(
2791 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002792 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002793 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002794 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2795 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002796 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002797 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002798 }
2799 }
2800 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002801 if (client->hasPreferredDevice(true) &&
2802 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002803 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002804 forceDeviceUpdate = true;
2805 }
2806
Eric Laurente552edb2014-03-10 17:42:56 -07002807 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002808 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002809
Eric Laurente552edb2014-03-10 17:42:56 -07002810 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002811 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002812 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002813 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002814
2815 // If the routing does not change, if an output is routed on a device using HwGain
2816 // (aka setAudioPortConfig) and there are still active clients following different
2817 // volume group(s), force reapply volume
2818 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2819 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2820
Eric Laurente552edb2014-03-10 17:42:56 -07002821 // delay the device switch by twice the latency because stopOutput() is executed when
2822 // the track stop() command is received and at that time the audio track buffer can
2823 // still contain data that needs to be drained. The latency only covers the audio HAL
2824 // and kernel buffers. Also the latency does not always include additional delay in the
2825 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302826 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002827 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002828
2829 // force restoring the device selection on other active outputs if it differs from the
2830 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002831 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002832 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002833 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002834 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002835 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002836 desc->isActive() &&
2837 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002838 (newDevices != desc->devices())) {
2839 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2840 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002841
jiabin220eea12024-05-17 17:55:20 +00002842 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002843 // If the device is using preferred mixer attributes, the output need to
2844 // reopen with default configuration when the new selected devices are
2845 // different from current routing devices.
2846 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2847 continue;
2848 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302849 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002850
Eric Laurent57de36c2016-09-28 16:59:11 -07002851 // re-apply device specific volume if not done by setOutputDevice()
2852 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002853 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002854 }
Eric Laurente552edb2014-03-10 17:42:56 -07002855 }
2856 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002857 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002858 // update the outputs if stopping one with a stream that can affect notification routing
2859 handleNotificationRoutingForStream(stream);
2860 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002861
2862 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2863 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002864 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002865 }
2866
François Gaffiec005e562018-11-06 15:04:49 +01002867 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002868 selectOutputForMusicEffects();
2869 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002870
2871 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2872
Eric Laurente552edb2014-03-10 17:42:56 -07002873 return NO_ERROR;
2874 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002875 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002876 return INVALID_OPERATION;
2877 }
2878}
2879
jiabinbce0c1d2020-10-05 11:20:18 -07002880bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002881{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002882 ALOGV("%s portId %d", __FUNCTION__, portId);
2883
2884 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2885 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002886 // If an output descriptor is closed due to a device routing change,
2887 // then there are race conditions with releaseOutput from tracks
2888 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2889 // destroyed shortly thereafter.
2890 //
2891 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002893 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002894 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895
2896 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002897
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302898 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2899 if (outputDesc->isClientActive(client)) {
2900 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2901 stopOutput(portId);
2902 }
2903
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2905 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002906 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002908 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002909 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002910 if (--outputDesc->mDirectOpenCount == 0) {
2911 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002912 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002913 }
2914 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302915
Andy Hung39efb7a2018-09-26 15:39:28 -07002916 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002917 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2918 // The output is pending reopened to query dynamic profiles and
2919 // there is no active clients
2920 closeOutput(outputDesc->mIoHandle);
2921 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2922 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2923 if (newOutputDesc == nullptr) {
2924 ALOGE("%s failed to open output", __func__);
2925 }
2926 return true;
2927 }
2928 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002929}
2930
Atneya Nair25fbcf22024-11-19 19:53:23 -08002931base::expected<media::GetInputForAttrResponse, std::variant<binder::Status, AudioConfigBase>>
2932AudioPolicyManager::getInputForAttr(audio_attributes_t attributes,
2933 audio_io_handle_t requestedInput,
2934 audio_port_handle_t requestedDeviceId,
2935 audio_config_base_t config,
2936 audio_input_flags_t flags,
2937 audio_unique_id_t riid,
2938 audio_session_t session,
Atneya Nairfda90e82024-11-19 19:55:25 -08002939 const AttributionSourceState& attributionSource)
Eric Laurente552edb2014-03-10 17:42:56 -07002940{
François Gaffiec005e562018-11-06 15:04:49 +01002941 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002942 "flags %#x attributes=%s requested device ID %d",
Atneya Nair25fbcf22024-11-19 19:53:23 -08002943 __func__, attributes.source, config.sample_rate, config.format, config.channel_mask,
2944 session, flags, toString(attributes).c_str(), requestedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002945
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002946 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002947 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002948 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002949 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002950 sp<RecordClientDescriptor> clientDesc;
Atneya Nair25fbcf22024-11-19 19:53:23 -08002951 uid_t uid = static_cast<uid_t>(attributionSource.uid);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002952 bool isSoundTrigger;
Atneya Nair25fbcf22024-11-19 19:53:23 -08002953 int vdi = 0 /* default device id */;
2954 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955
Atneya Nair25fbcf22024-11-19 19:53:23 -08002956 if (attributes.source == AUDIO_SOURCE_DEFAULT) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002957 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002958 }
2959
Atneya Nairfda90e82024-11-19 19:55:25 -08002960 using PermissionReqs = AudioPolicyClientInterface::PermissionReqs;
2961 using MixType = AudioPolicyClientInterface::MixType;
2962 PermissionReqs permReq {
2963 .source = legacy2aidl_audio_source_t_AudioSource(attributes.source).value(),
2964 .mixType = MixType::NONE, // can be modified
2965 .virtualDeviceId = 0, // can be modified
2966 .isHotword = (flags & (AUDIO_INPUT_FLAG_HW_HOTWORD | AUDIO_INPUT_FLAG_HOTWORD_TAP |
2967 AUDIO_INPUT_FLAG_HW_LOOKBACK)) != 0,
2968 .isCallRedir = (attributes.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0,
2969 };
2970
Paul McLean466dc8e2015-04-17 13:15:36 -06002971 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002972 sp<DeviceDescriptor> explicitRoutingDevice =
Atneya Nair25fbcf22024-11-19 19:53:23 -08002973 mAvailableInputDevices.getDeviceFromId(requestedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002974
Eric Laurentad2e7b92017-09-14 20:06:42 -07002975 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2976 // possible
2977 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
Atneya Nair25fbcf22024-11-19 19:53:23 -08002978 requestedInput != AUDIO_IO_HANDLE_NONE) {
2979 input = requestedInput;
2980 ssize_t index = mInputs.indexOfKey(requestedInput);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002981 if (index < 0) {
Atneya Nair25fbcf22024-11-19 19:53:23 -08002982 return base::unexpected{Status::fromExceptionCode(
2983 EX_ILLEGAL_ARGUMENT,
2984 String8::format("%s unknown MMAP input %d", __func__, requestedInput))};
Eric Laurentad2e7b92017-09-14 20:06:42 -07002985 }
2986 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002987 RecordClientVector clients = inputDesc->getClientsForSession(session);
2988 if (clients.size() == 0) {
Atneya Nair25fbcf22024-11-19 19:53:23 -08002989 return base::unexpected{Status::fromExceptionCode(
2990 EX_ILLEGAL_ARGUMENT, String8::format("%s unknown session %d on input %d",
2991 __func__, session, requestedInput))};
Eric Laurentad2e7b92017-09-14 20:06:42 -07002992 }
2993 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2994 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002995 // corresponds to a new client and is only permitted from the same UID.
2996 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997 if (clients.size() > 1) {
2998 for (const auto& client : clients) {
2999 // The client map is ordered by key values (portId) and portIds are allocated
3000 // incrementaly. So the first client in this list is the one opened by audio flinger
3001 // when the mmap stream is created and should be ignored as it does not correspond
3002 // to an actual client
3003 if (client == *clients.cbegin()) {
3004 continue;
3005 }
3006 if (uid != client->uid() && !client->isSilenced()) {
Atneya Nair25fbcf22024-11-19 19:53:23 -08003007 return base::unexpected{Status::fromExceptionCode(
3008 EX_ILLEGAL_STATE,
3009 String8::format("%s bad uid %d for client %d uid %d", __func__, uid,
3010 client->portId(), client->uid()))};
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 }
Eric Laurent331679c2018-04-16 17:03:16 -07003012 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003013 }
François Gaffie11d30102018-11-02 16:09:09 +01003014 device = inputDesc->getDevice();
Atneya Nair25fbcf22024-11-19 19:53:23 -08003015 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, requestedInput, session);
Eric Laurent275e8e92014-11-30 15:14:47 -08003016 } else {
Atneya Nair25fbcf22024-11-19 19:53:23 -08003017 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
3018 extractAddressFromAudioAttributes(attributes).has_value()) {
3019 status_t status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
3020 if (status != NO_ERROR) {
3021 ALOGW("%s could not find input mix for attr %s",
3022 __func__, toString(attributes).c_str());
3023 return base::unexpected {aidl_utils::binderStatusFromStatusT(status)};
3024 }
3025 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3026 String8(attributes.tags + strlen("addr=")),
3027 AUDIO_FORMAT_DEFAULT);
3028 if (device == nullptr) {
3029 return base::unexpected{Status::fromExceptionCode(
3030 EX_ILLEGAL_ARGUMENT,
3031 String8::format(
3032 "%s could not find in Remote Submix device for source %d, tags %s",
3033 __func__, attributes.source, attributes.tags))};
3034 }
3035
3036 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003037 permReq.mixType = MixType::PUBLIC_CAPTURE_PLAYBACK;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003038 } else {
Atneya Nairfda90e82024-11-19 19:55:25 -08003039 permReq.mixType = MixType::EXT_POLICY_REROUTE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003040 }
3041 // TODO is this correct?
Atneya Nairfda90e82024-11-19 19:55:25 -08003042 permReq.virtualDeviceId = policyMix->mVirtualDeviceId;
Eric Laurent97ac8712018-07-27 18:59:02 -07003043 } else {
Atneya Nair25fbcf22024-11-19 19:53:23 -08003044 if (explicitRoutingDevice != nullptr) {
3045 device = explicitRoutingDevice;
3046 } else {
3047 // Prevent from storing invalid requested device id in clients
3048 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
3049 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
3050 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3051 __FUNCTION__, device->type());
Marvin Ramine5a122d2023-12-07 13:57:59 +01003052 }
Atneya Nair25fbcf22024-11-19 19:53:23 -08003053 if (device == nullptr) {
3054 return base::unexpected{Status::fromExceptionCode(
3055 EX_ILLEGAL_ARGUMENT,
3056 String8::format("%s could not find device for source %d", __func__,
3057 attributes.source))};
3058 }
3059 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003060 permReq.mixType = MixType::CAPTURE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003061 } else if (policyMix) {
3062 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3063 // there is an external policy, but this input is attached to a mix of recorders,
3064 // meaning it receives audio injected into the framework, so the recorder doesn't
3065 // know about it and is therefore considered "legacy"
Atneya Nairfda90e82024-11-19 19:55:25 -08003066 permReq.mixType = MixType::NONE;
3067 permReq.virtualDeviceId = policyMix->mVirtualDeviceId;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003068 } else if (audio_is_remote_submix_device(device->type())) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003069 permReq.mixType = MixType::CAPTURE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003070 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003071 permReq.mixType = MixType::TELEPHONY_RX_CAPTURE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003072 } else {
Atneya Nairfda90e82024-11-19 19:55:25 -08003073 permReq.mixType = MixType::NONE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003074 }
Eric Laurentc722f302014-12-10 11:21:49 -08003075 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003076
Atneya Nairfda90e82024-11-19 19:55:25 -08003077 auto permRes = mpClientInterface->checkPermissionForInput(attributionSource, permReq);
3078 if (!permRes.has_value()) return base::unexpected {permRes.error()};
3079 if (!permRes.value()) {
3080 return base::unexpected{Status::fromExceptionCode(
3081 EX_SECURITY, String8::format("%s: %s missing perms for source %d mix %d vdi %d"
3082 "hotword? %d callredir? %d", __func__, attributionSource.toString().c_str(),
3083 static_cast<int>(permReq.source),
3084 static_cast<int>(permReq.mixType),
3085 permReq.virtualDeviceId,
3086 permReq.isHotword,
3087 permReq.isCallRedir))};
3088 }
Atneya Nair25fbcf22024-11-19 19:53:23 -08003089
3090 input = getInputForDevice(device, session, attributes, config, flags, policyMix);
3091 if (input == AUDIO_IO_HANDLE_NONE) {
3092 AudioProfileVector profiles;
3093 status_t ret = getProfilesForDevices(
3094 DeviceVector(device), profiles, flags, true /*isInput*/);
3095 if (ret == NO_ERROR && !profiles.empty()) {
3096 const auto channels = profiles[0]->getChannels();
3097 if (!channels.empty() && (channels.find(config.channel_mask) == channels.end())) {
3098 config.channel_mask = *channels.begin();
3099 }
3100 const auto sampleRates = profiles[0]->getSampleRates();
3101 if (!sampleRates.empty() &&
3102 (sampleRates.find(config.sample_rate) == sampleRates.end())) {
3103 config.sample_rate = *sampleRates.begin();
3104 }
3105 config.format = profiles[0]->getFormat();
3106 }
3107 const auto suggestedConfig = VALUE_OR_FATAL(
3108 legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/));
3109 return base::unexpected {suggestedConfig};
3110 }
Eric Laurent599c7582015-12-07 18:05:55 -08003111 }
3112
Atneya Nair25fbcf22024-11-19 19:53:23 -08003113 auto selectedDeviceId = mAvailableInputDevices.contains(device) ?
François Gaffiec005e562018-11-06 15:04:49 +01003114 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003115
Francois Gaffie716e1432019-01-14 16:58:59 +01003116 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003117 mSoundTriggerSessions.indexOfKey(session) >= 0;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118
Atneya Nair25fbcf22024-11-19 19:53:23 -08003119 const auto allocatedPortId = PolicyAudioPort::getNextUniqueId();
3120
3121 clientDesc = new RecordClientDescriptor(allocatedPortId, riid, uid, session, attributes, config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003122 requestedDeviceId, attributes.source, flags,
3123 isSoundTrigger);
Atneya Nair25fbcf22024-11-19 19:53:23 -08003124 inputDesc = mInputs.valueFor(input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003125 // Move (if found) effect for the client session to its input
Atneya Nair25fbcf22024-11-19 19:53:23 -08003126 mEffects.moveEffectsForIo(session, input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003127 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003128
Atneya Nairfda90e82024-11-19 19:55:25 -08003129 ALOGV("getInputForAttr() returns input %d selectedDeviceId %d vdi %d for port ID %d",
3130 input, selectedDeviceId, permReq.virtualDeviceId, allocatedPortId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003131
Atneya Nair25fbcf22024-11-19 19:53:23 -08003132 auto ret = media::GetInputForAttrResponse {};
3133 ret.input = input;
3134 ret.selectedDeviceId = selectedDeviceId;
3135 ret.portId = allocatedPortId;
Atneya Nairfda90e82024-11-19 19:55:25 -08003136 ret.virtualDeviceId = permReq.virtualDeviceId;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003137 ret.config = legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/).value();
3138 return ret;
Eric Laurent599c7582015-12-07 18:05:55 -08003139}
3140
Atneya Nair25fbcf22024-11-19 19:53:23 -08003141audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent599c7582015-12-07 18:05:55 -08003142 audio_session_t session,
Atneya Nair25fbcf22024-11-19 19:53:23 -08003143 const audio_attributes_t& attributes,
3144 const audio_config_base_t& config,
Eric Laurent599c7582015-12-07 18:05:55 -08003145 audio_input_flags_t flags,
Atneya Nair25fbcf22024-11-19 19:53:23 -08003146 const sp<AudioPolicyMix>& policyMix) {
Eric Laurent599c7582015-12-07 18:05:55 -08003147 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003148 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003149 bool isSoundTrigger = false;
3150
François Gaffiec005e562018-11-06 15:04:49 +01003151 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003152 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3153 if (index >= 0) {
3154 input = mSoundTriggerSessions.valueFor(session);
3155 isSoundTrigger = true;
3156 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3157 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3158 } else {
3159 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003160 }
François Gaffiec005e562018-11-06 15:04:49 +01003161 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Atneya Nair25fbcf22024-11-19 19:53:23 -08003162 audio_is_linear_pcm(config.format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003163 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003164 }
3165
Carter Hsua3abb402021-10-26 11:11:20 +08003166 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3167 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3168 }
3169
Eric Laurentfe231122017-11-17 17:48:06 -08003170 // sampling rate and flags may be updated by getInputProfile
Atneya Nair25fbcf22024-11-19 19:53:23 -08003171 uint32_t profileSamplingRate = (config.sample_rate == 0) ?
3172 SAMPLE_RATE_HZ_DEFAULT : config.sample_rate;
3173 audio_format_t profileFormat = config.format;
3174 audio_channel_mask_t profileChannelMask = config.channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003175 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003176 // find a compatible input profile (not necessarily identical in parameters)
3177 sp<IOProfile> profile = getInputProfile(
3178 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3179 if (profile == nullptr) {
3180 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003181 }
jiabin2fd710d2022-05-02 23:20:22 +00003182
Glenn Kasten05ddca52016-02-11 08:17:12 -08003183 // Pick input sampling rate if not specified by client
Atneya Nair25fbcf22024-11-19 19:53:23 -08003184 uint32_t samplingRate = config.sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003185 if (samplingRate == 0) {
3186 samplingRate = profileSamplingRate;
3187 }
Eric Laurente552edb2014-03-10 17:42:56 -07003188
Eric Laurent322b4d22015-04-03 15:57:54 -07003189 if (profile->getModuleHandle() == 0) {
3190 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003191 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003192 }
3193
Eric Laurentec376dc2021-04-08 20:41:22 +02003194 // Reuse an already opened input if a client with the same session ID already exists
3195 // on that input
3196 for (size_t i = 0; i < mInputs.size(); i++) {
3197 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3198 if (desc->mProfile != profile) {
3199 continue;
3200 }
3201 RecordClientVector clients = desc->clientsList();
3202 for (const auto &client : clients) {
3203 if (session == client->session()) {
3204 return desc->mIoHandle;
3205 }
3206 }
3207 }
3208
Eric Laurentc71b11b2024-06-03 12:54:53 +00003209 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003210 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003211 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3212 // First pick best candidate for preemption (there may not be any):
3213 // - Preempt and input if:
3214 // - It has only strictly lower priority use cases than the new client
3215 // - It has equal priority use cases than the new client, was not
3216 // opened thanks to preemption or has been active since opened.
3217 // - Order the preemption candidates by inactive first and priority second
3218 sp<AudioInputDescriptor> closeCandidate;
3219 int leastCloseRank = INT_MAX;
3220 static const int sCloseActive = 0x100;
3221
3222 for (size_t i = 0; i < mInputs.size(); i++) {
3223 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3224 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003225 continue;
3226 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003227 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3228 if (topPrioClient == nullptr) {
3229 continue;
3230 }
3231 int topPrio = source_priority(topPrioClient->source());
3232 if (topPrio < source_priority(attributes.source)
3233 || (topPrio == source_priority(attributes.source)
3234 && !desc->isPreemptor())) {
3235 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3236 if (closeRank < leastCloseRank) {
3237 leastCloseRank = closeRank;
3238 closeCandidate = desc;
3239 }
3240 }
3241 }
3242
3243 if (closeCandidate != nullptr) {
3244 closeInput(closeCandidate->mIoHandle);
3245 // Mark the new input as being issued from a preemption
3246 // so that is will not be preempted later
3247 isPreemptor = true;
3248 } else {
3249 // Then pick the best reusable input (There is always one)
3250 // The order of preference is:
3251 // 1) active inputs with same use case as the new client
3252 // 2) inactive inputs with same use case
3253 // 3) active inputs with different use cases
3254 // 4) inactive inputs with different use cases
3255 sp<AudioInputDescriptor> reuseCandidate;
3256 int leastReuseRank = INT_MAX;
3257 static const int sReuseDifferentUseCase = 0x100;
3258
3259 for (size_t i = 0; i < mInputs.size(); i++) {
3260 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3261 if (desc->mProfile != profile) {
3262 continue;
3263 }
3264 int reuseRank = sReuseDifferentUseCase;
3265 for (const auto& client: desc->getClientIterable()) {
3266 if (client->source() == attributes.source) {
3267 reuseRank = 0;
3268 break;
3269 }
3270 }
3271 reuseRank += desc->isActive() ? 0 : 1;
3272 if (reuseRank < leastReuseRank) {
3273 leastReuseRank = reuseRank;
3274 reuseCandidate = desc;
3275 }
3276 }
3277 return reuseCandidate->mIoHandle;
3278 }
3279 } else { // fix_input_sharing_logic()
3280 for (size_t i = 0; i < mInputs.size(); ) {
3281 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3282 if (desc->mProfile != profile) {
3283 i++;
3284 continue;
3285 }
3286 // if sound trigger, reuse input if used by other sound trigger on same session
3287 // else
3288 // reuse input if active client app is not in IDLE state
3289 //
3290 RecordClientVector clients = desc->clientsList();
3291 bool doClose = false;
3292 for (const auto& client : clients) {
3293 if (isSoundTrigger != client->isSoundTrigger()) {
3294 continue;
3295 }
3296 if (client->isSoundTrigger()) {
3297 if (session == client->session()) {
3298 return desc->mIoHandle;
3299 }
3300 continue;
3301 }
3302 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003303 return desc->mIoHandle;
3304 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003305 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003306 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003307 if (doClose) {
3308 closeInput(desc->mIoHandle);
3309 } else {
3310 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003311 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003312 }
3313 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003314 }
3315
Eric Laurentc71b11b2024-06-03 12:54:53 +00003316 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3317 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003318
Eric Laurentfe231122017-11-17 17:48:06 -08003319 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3320 lConfig.sample_rate = profileSamplingRate;
3321 lConfig.channel_mask = profileChannelMask;
3322 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003323
François Gaffie11d30102018-11-02 16:09:09 +01003324 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003325
3326 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003327 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003328 (profileSamplingRate != lConfig.sample_rate) ||
3329 !audio_formats_match(profileFormat, lConfig.format) ||
3330 (profileChannelMask != lConfig.channel_mask)) {
3331 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003332 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003333 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003334 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003335 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003336 }
Eric Laurent599c7582015-12-07 18:05:55 -08003337 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003338 }
3339
Eric Laurentc722f302014-12-10 11:21:49 -08003340 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003341
Eric Laurent599c7582015-12-07 18:05:55 -08003342 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003343 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003344
Eric Laurent599c7582015-12-07 18:05:55 -08003345 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003346}
3347
Eric Laurent4eb58f12018-12-07 16:41:02 -08003348status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003349{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003350 ALOGV("%s portId %d", __FUNCTION__, portId);
3351
3352 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3353 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003354 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003355 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003356 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003357 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003358 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003359 if (client->active()) {
3360 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3361 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003362 }
3363
Eric Laurent8f42ea12018-08-08 09:08:25 -07003364 audio_session_t session = client->session();
3365
Eric Laurent4eb58f12018-12-07 16:41:02 -08003366 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003367
Eric Laurent4eb58f12018-12-07 16:41:02 -08003368 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003369
Eric Laurent4eb58f12018-12-07 16:41:02 -08003370 status_t status = inputDesc->start();
3371 if (status != NO_ERROR) {
3372 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003373 }
Eric Laurente552edb2014-03-10 17:42:56 -07003374
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003375 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003376 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003377 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003378
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379 // indicate active capture to sound trigger service if starting capture from a mic on
3380 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003381 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003382 if (device != nullptr) {
3383 status = setInputDevice(input, device, true /* force */);
3384 } else {
3385 ALOGW("%s no new input device can be found for descriptor %d",
3386 __FUNCTION__, inputDesc->getId());
3387 status = BAD_VALUE;
3388 }
Eric Laurente552edb2014-03-10 17:42:56 -07003389
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003390 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003391 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003392 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003393 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003394 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3395 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003396 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003397 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003398
François Gaffie11d30102018-11-02 16:09:09 +01003399 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3400 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003401 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003402 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003403 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003404
Eric Laurent8f42ea12018-08-08 09:08:25 -07003405 // automatically enable the remote submix output when input is started if not
3406 // used by a policy mix of type MIX_TYPE_RECORDERS
3407 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003408 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003409 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003410 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003411 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003412 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3413 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003414 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003415 if (address != "") {
3416 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3417 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003418 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003419 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003420 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003421 } else if (status != NO_ERROR) {
3422 // Restore client activity state.
3423 inputDesc->setClientActive(client, false);
3424 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003425 }
3426
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003427 ALOGV("%s input %d source = %d status = %d exit",
3428 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003429
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003430 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003431}
3432
Eric Laurent8fc147b2018-07-22 19:13:55 -07003433status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003434{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003435 ALOGV("%s portId %d", __FUNCTION__, portId);
3436
3437 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3438 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003439 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00003440 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07003441 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003442 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003443 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003444 if (!client->active()) {
3445 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003446 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003447 }
Carter Hsue6139d52021-07-08 10:30:20 +08003448 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003450
Eric Laurent8f42ea12018-08-08 09:08:25 -07003451 inputDesc->stop();
3452 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003453 auto current_source = inputDesc->source();
3454 setInputDevice(input, getNewInputDevice(inputDesc),
3455 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003456 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003457 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003458 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003459 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003460 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3461 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003462 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003463 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003464
3465 // automatically disable the remote submix output when input is stopped if not
3466 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003467 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003468 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003469 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003470 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003471 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3472 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003473 }
3474 if (address != "") {
3475 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3476 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003477 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003478 }
3479 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003480 resetInputDevice(input);
3481
3482 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3483 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003484 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3485 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003486 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003487 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003488 }
3489 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003490 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003491 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003492}
3493
Eric Laurent8fc147b2018-07-22 19:13:55 -07003494void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003495{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003496 ALOGV("%s portId %d", __FUNCTION__, portId);
3497
3498 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3499 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003500 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003501 return;
3502 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003503 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003504 audio_io_handle_t input = inputDesc->mIoHandle;
3505
Eric Laurent8f42ea12018-08-08 09:08:25 -07003506 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003507
Andy Hung39efb7a2018-09-26 15:39:28 -07003508 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003509
3510 // If no more clients are present in this session, park effects to an orphan chain
3511 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3512 if (clientsOnSession.size() == 0) {
3513 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3514 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003515 if (inputDesc->getClientCount() > 0) {
3516 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003517 return;
3518 }
3519
Eric Laurent05b90f82014-08-27 15:32:29 -07003520 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003521 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003522 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003523}
3524
Eric Laurent8f42ea12018-08-08 09:08:25 -07003525void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003526{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003527 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003528
3529 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003530 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003531 }
3532}
3533
Eric Laurent8f42ea12018-08-08 09:08:25 -07003534void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3535{
3536 stopInput(portId);
3537 releaseInput(portId);
3538}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003539
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003540bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3541 if (input->clientsList().size() == 0
3542 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3543 return true;
3544 }
3545 for (const auto& client : input->clientsList()) {
3546 sp<DeviceDescriptor> device =
3547 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3548 client->session());
3549 if (!input->supportedDevices().contains(device)) {
3550 return true;
3551 }
3552 }
3553 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3554 return false;
3555}
3556
Eric Laurent0dd51852019-04-19 18:18:58 -07003557void AudioPolicyManager::checkCloseInputs() {
3558 // After connecting or disconnecting an input device, close input if:
3559 // - it has no client (was just opened to check profile) OR
3560 // - none of its supported devices are connected anymore OR
3561 // - one of its clients cannot be routed to one of its supported
3562 // devices anymore. Otherwise update device selection
3563 std::vector<audio_io_handle_t> inputsToClose;
3564 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003565 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003566 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003567 }
3568 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003569 for (const audio_io_handle_t handle : inputsToClose) {
3570 ALOGV("%s closing input %d", __func__, handle);
3571 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003572 }
Eric Laurentd4692962014-05-05 18:13:44 -07003573}
3574
Vlad Popa87e0e582024-05-20 18:49:20 -07003575status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3576 const char *address __unused,
3577 bool enabled,
3578 audio_stream_type_t streamToDriveAbs)
3579{
Vlad Popa08502d82024-10-22 20:17:47 -07003580 ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3581 streamToDriveAbs);
3582
Vlad Popa6319b2d2024-11-15 18:32:13 -08003583 bool changed = false;
Neha Jain7af15132024-11-16 00:47:18 +00003584 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
Vlad Popa6319b2d2024-11-15 18:32:13 -08003585 if (enabled) {
3586 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3587 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3588 toString(streamToDriveAbs).c_str());
3589 return BAD_VALUE;
3590 }
3591
Vlad Popa3d8d8942024-11-19 21:04:31 -08003592 const auto attrIt = mAbsoluteVolumeDrivingStreams.find(deviceType);
3593 if (attrIt == mAbsoluteVolumeDrivingStreams.end() ||
3594 (attrIt->second.usage != attributesToDriveAbs.usage ||
3595 attrIt->second.content_type != attributesToDriveAbs.content_type ||
3596 attrIt->second.flags != attributesToDriveAbs.flags)) {
Vlad Popa6319b2d2024-11-15 18:32:13 -08003597 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3598 changed = true;
3599 }
3600 } else {
Vlad Popa3d8d8942024-11-19 21:04:31 -08003601 if (mAbsoluteVolumeDrivingStreams.erase(deviceType) != 0) {
Vlad Popa6319b2d2024-11-15 18:32:13 -08003602 changed = true;
3603 }
Vlad Popafb0af7c2024-10-29 16:38:37 -07003604 }
3605
Vlad Popa3d8d8942024-11-19 21:04:31 -08003606 const DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3607 attributesToDriveAbs, nullptr /* preferredDevice */, true /* fromCache */);
3608 changed &= devices.types().contains(deviceType);
3609 // if something changed on the output device for the changed attributes, apply the stream
3610 // volumes regarding the new absolute mode to all the outputs without any delay
Vlad Popa6319b2d2024-11-15 18:32:13 -08003611 if (changed) {
3612 for (size_t i = 0; i < mOutputs.size(); i++) {
3613 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa3d8d8942024-11-19 21:04:31 -08003614 ALOGI("%s: apply stream volumes for portId %d and device type %d", __func__,
3615 desc->getId(), deviceType);
Vlad Popa6319b2d2024-11-15 18:32:13 -08003616 applyStreamVolumes(desc, {deviceType});
3617 }
3618 }
3619
Vlad Popa87e0e582024-05-20 18:49:20 -07003620 return NO_ERROR;
3621}
3622
François Gaffie251c7f02018-11-07 10:41:08 +01003623void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003624{
3625 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003626 if (indexMin < 0 || indexMax < 0) {
3627 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3628 return;
3629 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003630 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003631
3632 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003633 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3634 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003635 continue;
3636 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003637 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003638 }
Eric Laurente552edb2014-03-10 17:42:56 -07003639}
3640
Eric Laurente0720872014-03-11 09:30:41 -07003641status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003642 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003643 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003644 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003645{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003646 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003647 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3648 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3649 return NO_ERROR;
3650 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303651 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3652 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003653 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003654}
3655
Eric Laurente0720872014-03-11 09:30:41 -07003656status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003657 int *index,
3658 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003659{
François Gaffiec005e562018-11-06 15:04:49 +01003660 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3661 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003662 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003663 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003664 deviceTypes = mEngine->getOutputDevicesForStream(
3665 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003666 }
jiabin9a3361e2019-10-01 09:38:30 -07003667 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003668}
3669
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003670status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003671 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003672 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003673 audio_devices_t device)
3674{
3675 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003676 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3677 if (group == VOLUME_GROUP_NONE) {
3678 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003679 return BAD_VALUE;
3680 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003681 ALOGV("%s: group %d matching with %s index %d",
3682 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003683 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3684 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3685 __FUNCTION__, toString(attributes).c_str());
3686 return NO_ERROR;
3687 }
François Gaffiecfe17322018-11-07 13:41:29 +01003688 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003689 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003690 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003691 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3692 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3693 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3694 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003695 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3696
Vlad Popa1e865e62024-08-15 19:11:42 -07003697
3698 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003699 if (status != NO_ERROR) {
3700 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3701 return status;
3702 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003703
jiabin9a3361e2019-10-01 09:38:30 -07003704 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003705 auto curCurvAttrs = curves.getAttributes();
3706 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3707 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003708 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003709 } else if (!curves.getStreamTypes().empty()) {
3710 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003711 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003712 } else {
3713 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3714 return BAD_VALUE;
3715 }
jiabin9a3361e2019-10-01 09:38:30 -07003716 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3717 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003718
François Gaffiecfe17322018-11-07 13:41:29 +01003719 // update volume on all outputs and streams matching the following:
3720 // - The requested stream (or a stream matching for volume control) is active on the output
3721 // - The device (or devices) selected by the engine for this stream includes
3722 // the requested device
3723 // - For non default requested device, currently selected device on the output is either the
3724 // requested device or one of the devices selected by the engine for this stream
3725 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3726 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003727 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003728 for (size_t i = 0; i < mOutputs.size(); i++) {
3729 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003730 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003731
jiabin9a3361e2019-10-01 09:38:30 -07003732 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3733 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003734 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003735
3736 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003737 continue;
3738 }
3739 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3740 curDevices.find(device) == curDevices.end()) {
3741 continue;
3742 }
3743 bool applyVolume = false;
3744 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3745 curSrcDevices.insert(device);
3746 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003747 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3748 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003749 } else {
3750 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3751 }
3752 if (!applyVolume) {
3753 continue; // next output
3754 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003755 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3756 // If a higher priority strategy is active, and the output is routed to a device with a
3757 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003758 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003759 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003760 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003761 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003762 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003763 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3764 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3765 false /*preferredDevice*/);
3766 if (activeClients.empty()) {
3767 continue;
3768 }
3769 bool isPreempted = false;
3770 bool isHigherPriority = productStrategy < strategy;
3771 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003772 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003773 ALOGV("%s: Strategy=%d (\nrequester:\n"
3774 " group %d, volumeGroup=%d attributes=%s)\n"
3775 " higher priority source active:\n"
3776 " volumeGroup=%d attributes=%s) \n"
3777 " on output %zu, bailing out", __func__, productStrategy,
3778 group, group, toString(attributes).c_str(),
3779 client->volumeSource(), toString(client->attributes()).c_str(), i);
3780 applyVolume = false;
3781 isPreempted = true;
3782 break;
3783 }
3784 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003785 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003786 applyVolume = true;
3787 }
3788 }
3789 if (isPreempted || applyVolume) {
3790 break;
3791 }
3792 }
3793 if (!applyVolume) {
3794 continue; // next output
3795 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003796 }
François Gaffieed91f582020-01-31 10:35:37 +01003797 //FIXME: workaround for truncated touch sounds
3798 // delayed volume change for system stream to be removed when the problem is
3799 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003800 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003801 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003802 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3803 if (volStatus != NO_ERROR) {
3804 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003805 }
3806 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003807
Ping Tsaic2575c62024-11-21 15:08:33 +00003808 // update voice volume if the an active call route exists and target device is same as current
3809 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()) {
3810 audio_devices_t rxSinkDevice = mCallRxSourceClient->sinkDevice()->type();
3811 audio_devices_t curVoiceDevice = Volume::getDeviceForVolume({rxSinkDevice});
3812 if (curVoiceDevice == device
3813 && curSrcDevices.find(curVoiceDevice) != curSrcDevices.end()) {
3814 bool isVoiceVolSrc;
3815 bool isBtScoVolSrc;
3816 if (isVolumeConsistentForCalls(vs, {rxSinkDevice},
3817 isVoiceVolSrc, isBtScoVolSrc, __func__)
3818 && (isVoiceVolSrc || isBtScoVolSrc)) {
3819 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
3820 !audio_is_ble_out_device(rxSinkDevice);
3821 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
3822 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003823 }
3824 }
3825
François Gaffiecfe17322018-11-07 13:41:29 +01003826 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3827 return status;
3828}
3829
François Gaffieaaac0fd2018-11-22 17:56:39 +01003830status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003831 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003832 audio_devices_t device,
3833 IVolumeCurves &volumeCurves)
3834{
3835 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3836 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003837 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3838 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003839 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303840 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3841 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003842 return BAD_VALUE;
3843 }
3844 if (!audio_is_output_device(device)) {
3845 return BAD_VALUE;
3846 }
3847
3848 // Force max volume if stream cannot be muted
3849 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3850
Vlad Popa1e865e62024-08-15 19:11:42 -07003851 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003852 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003853 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003854 return NO_ERROR;
3855}
3856
3857status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3858 int &index,
3859 audio_devices_t device)
3860{
3861 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3862 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003863 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003864 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003865 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003866 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003867 }
jiabin9a3361e2019-10-01 09:38:30 -07003868 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003869}
3870
3871status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3872 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003873 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003874{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003875 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003876 return BAD_VALUE;
3877 }
jiabin9a3361e2019-10-01 09:38:30 -07003878 index = curves.getVolumeIndex(deviceTypes);
3879 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003880 return NO_ERROR;
3881}
3882
3883status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3884 int &index)
3885{
3886 index = getVolumeCurves(attr).getVolumeIndexMin();
3887 return NO_ERROR;
3888}
3889
3890status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3891 int &index)
3892{
3893 index = getVolumeCurves(attr).getVolumeIndexMax();
3894 return NO_ERROR;
3895}
3896
Eric Laurent36829f92017-04-07 19:04:42 -07003897audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003898{
3899 // select one output among several suitable for global effects.
3900 // The priority is as follows:
3901 // 1: An offloaded output. If the effect ends up not being offloadable,
3902 // AudioFlinger will invalidate the track and the offloaded output
3903 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003904 // 2: Spatializer output if the stereo spatializer feature enabled
3905 // 3: A deep buffer output
3906 // 4: The primary output
3907 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003908
François Gaffiec005e562018-11-06 15:04:49 +01003909 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3910 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003911 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003912
Eric Laurent36829f92017-04-07 19:04:42 -07003913 if (outputs.size() == 0) {
3914 return AUDIO_IO_HANDLE_NONE;
3915 }
Eric Laurente552edb2014-03-10 17:42:56 -07003916
Eric Laurent36829f92017-04-07 19:04:42 -07003917 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3918 bool activeOnly = true;
3919
3920 while (output == AUDIO_IO_HANDLE_NONE) {
3921 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003922 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003923 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3924 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3925
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003926 for (audio_io_handle_t outputLoop : outputs) {
3927 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003928 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003929 continue;
3930 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003931 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003932 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003933 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003934 outputOffloaded = outputLoop;
3935 }
3936 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3937 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3938 outputSpatializer = outputLoop;
3939 }
Eric Laurent36829f92017-04-07 19:04:42 -07003940 }
3941 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003942 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003943 }
3944 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003945 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003946 }
3947 }
3948 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3949 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003950 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3951 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003952 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3953 output = outputDeepBuffer;
3954 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3955 output = outputPrimary;
3956 } else {
3957 output = outputs[0];
3958 }
3959 activeOnly = false;
3960 }
3961
3962 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003963 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3964 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003965 mMusicEffectOutput = output;
3966 }
3967
3968 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003969 return output;
3970}
3971
Eric Laurent36829f92017-04-07 19:04:42 -07003972audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3973{
3974 return selectOutputForMusicEffects();
3975}
3976
Eric Laurente0720872014-03-11 09:30:41 -07003977status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003978 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003979 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003980 int session,
3981 int id)
3982{
Shunkai Yao29d10572024-03-19 04:31:47 +00003983 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003984 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003985 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003986 index = mInputs.indexOfKey(io);
3987 if (index < 0) {
3988 ALOGW("registerEffect() unknown io %d", io);
3989 return INVALID_OPERATION;
3990 }
Eric Laurente552edb2014-03-10 17:42:56 -07003991 }
3992 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003993 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3994 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3995 || strategy == PRODUCT_STRATEGY_NONE));
3996 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003997}
3998
Eric Laurentc241b0d2018-11-28 09:08:49 -08003999status_t AudioPolicyManager::unregisterEffect(int id)
4000{
4001 if (mEffects.getEffect(id) == nullptr) {
4002 return INVALID_OPERATION;
4003 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08004004 if (mEffects.isEffectEnabled(id)) {
4005 ALOGW("%s effect %d enabled", __FUNCTION__, id);
4006 setEffectEnabled(id, false);
4007 }
4008 return mEffects.unregisterEffect(id);
4009}
4010
4011status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
4012{
4013 sp<EffectDescriptor> effect = mEffects.getEffect(id);
4014 if (effect == nullptr) {
4015 return INVALID_OPERATION;
4016 }
4017
4018 status_t status = mEffects.setEffectEnabled(id, enabled);
4019 if (status == NO_ERROR) {
4020 mInputs.trackEffectEnabled(effect, enabled);
4021 }
4022 return status;
4023}
4024
Eric Laurent6c796322019-04-09 14:13:17 -07004025
4026status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
4027{
4028 mEffects.moveEffects(ids, io);
4029 return NO_ERROR;
4030}
4031
Eric Laurentc75307b2015-03-17 15:29:32 -07004032bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
4033{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004034 auto vs = toVolumeSource(stream, false);
4035 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004036}
4037
4038bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4039{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004040 auto vs = toVolumeSource(stream, false);
4041 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004042}
4043
Eric Laurente0720872014-03-11 09:30:41 -07004044bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004045{
4046 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004047 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004048 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004049 return true;
4050 }
4051 }
4052 return false;
4053}
4054
Eric Laurent275e8e92014-11-30 15:14:47 -08004055// Register a list of custom mixes with their attributes and format.
4056// When a mix is registered, corresponding input and output profiles are
4057// added to the remote submix hw module. The profile contains only the
4058// parameters (sampling rate, format...) specified by the mix.
4059// The corresponding input remote submix device is also connected.
4060//
4061// When a remote submix device is connected, the address is checked to select the
4062// appropriate profile and the corresponding input or output stream is opened.
4063//
4064// When capture starts, getInputForAttr() will:
4065// - 1 look for a mix matching the address passed in attribtutes tags if any
4066// - 2 if none found, getDeviceForInputSource() will:
4067// - 2.1 look for a mix matching the attributes source
4068// - 2.2 if none found, default to device selection by policy rules
4069// At this time, the corresponding output remote submix device is also connected
4070// and active playback use cases can be transferred to this mix if needed when reconnecting
4071// after AudioTracks are invalidated
4072//
4073// When playback starts, getOutputForAttr() will:
4074// - 1 look for a mix matching the address passed in attribtutes tags if any
4075// - 2 if none found, look for a mix matching the attributes usage
4076// - 3 if none found, default to device and output selection by policy rules.
4077
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004078status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004079{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004080 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4081 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004082 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004083 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004084 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004085 // examine each mix's route type
4086 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004087 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004088 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4089 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4090 ALOGE("Unsupported Policy Mix %zu of %zu: "
4091 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4092 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004093 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004094 break;
4095 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004096 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4097 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004098 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004099 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4100 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004101 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004102 rSubmixModule = mHwModules.getModuleFromName(
4103 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4104 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004105 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004106 i);
4107 res = INVALID_OPERATION;
4108 break;
4109 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004110 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004111
Eric Laurent97ac8712018-07-27 18:59:02 -07004112 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004113 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004114 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004115 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004116 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4117 } else {
4118 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4119 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004120 }
François Gaffie036e1e92015-03-19 10:16:24 +01004121
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004122 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004123 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004124 res = INVALID_OPERATION;
4125 break;
4126 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004127 audio_config_t outputConfig = mix.mFormat;
4128 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004129 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4130 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004131 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4132 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004133 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004134 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4135 audio_is_linear_pcm(outputConfig.format)
4136 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004137 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004138 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4139 audio_is_linear_pcm(inputConfig.format)
4140 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004141
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004142 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004143 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004144 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004145 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004146 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004147 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004148 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004149 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4150 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004151 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004152 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004153 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004154
4155 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4156 mix.mDeviceType, mix.mDeviceAddress,
4157 String8(), AUDIO_FORMAT_DEFAULT);
4158 if (device == nullptr) {
4159 res = INVALID_OPERATION;
4160 break;
4161 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004162
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004163 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004164 // First try to find an already opened output supporting the device
4165 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004166 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004167
Eric Laurentc529cf62020-04-17 18:19:10 -07004168 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004169 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004170 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004171 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004172 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004173 } else {
4174 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004175 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004176 }
4177 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004178 // If no output found, try to find a direct output profile supporting the device
4179 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4180 sp<HwModule> module = mHwModules[i];
4181 for (size_t j = 0;
4182 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4183 j++) {
4184 sp<IOProfile> profile = module->getOutputProfiles()[j];
4185 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4186 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4187 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004188 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004189 res = INVALID_OPERATION;
4190 } else {
4191 foundOutput = true;
4192 }
4193 }
4194 }
4195 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004196 if (res != NO_ERROR) {
4197 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004198 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004199 res = INVALID_OPERATION;
4200 break;
4201 } else if (!foundOutput) {
4202 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004203 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004204 res = INVALID_OPERATION;
4205 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004206 } else {
4207 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004208 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004209 }
Eric Laurentc722f302014-12-10 11:21:49 -08004210 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004211 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004212 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004213 if (audio_flags::audio_mix_ownership()) {
4214 // Only unregister mixes that were actually registered to not accidentally unregister
4215 // mixes that already existed previously.
4216 unregisterPolicyMixes(registeredMixes);
4217 registeredMixes.clear();
4218 } else {
4219 unregisterPolicyMixes(mixes);
4220 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004221 } else if (checkOutputs) {
4222 checkForDeviceAndOutputChanges();
4223 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004224 }
4225 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004226}
4227
4228status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4229{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004230 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004231 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004232 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004233 sp<HwModule> rSubmixModule;
4234 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004235 for (const auto& mix : mixes) {
4236 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004237
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004238 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004239 rSubmixModule = mHwModules.getModuleFromName(
4240 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4241 if (rSubmixModule == 0) {
4242 res = INVALID_OPERATION;
4243 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004244 }
4245 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004246
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004247 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004248
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004249 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004250 res = INVALID_OPERATION;
4251 continue;
4252 }
4253
Marvin Ramin0783e202024-03-05 12:45:50 +01004254 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004255 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004256 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4257 status_t currentRes =
4258 setDeviceConnectionStateInt(device,
4259 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4260 address.c_str(),
4261 "remote-submix",
4262 AUDIO_FORMAT_DEFAULT);
4263 if (!audio_flags::audio_mix_ownership()) {
4264 res = currentRes;
4265 }
4266 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004267 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004268 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004269 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004270 }
4271 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004272 }
jiabin5740f082019-08-19 15:08:30 -07004273 rSubmixModule->removeOutputProfile(address.c_str());
4274 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004275
Kevin Rocard153f92d2018-12-18 18:33:28 -08004276 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004277 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004278 res = INVALID_OPERATION;
4279 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004280 } else {
4281 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004282 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004283 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004284 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004285
4286 if (res == NO_ERROR && checkOutputs) {
4287 checkForDeviceAndOutputChanges();
4288 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004289 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004290 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004291}
4292
Marvin Raminbdefaf02023-11-01 09:10:32 +01004293status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4294 if (!audio_flags::audio_mix_test_api()) {
4295 return INVALID_OPERATION;
4296 }
4297
4298 _aidl_return.clear();
4299 _aidl_return.reserve(mPolicyMixes.size());
4300 for (const auto &policyMix: mPolicyMixes) {
4301 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4302 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4303 policyMix->mCbFlags);
4304 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004305 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004306 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004307 }
4308
Vlad Popaa5d73f32024-03-08 16:05:38 -08004309 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004310 return OK;
4311}
4312
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004313status_t AudioPolicyManager::updatePolicyMix(
4314 const AudioMix& mix,
4315 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4316 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4317 if (res == NO_ERROR) {
4318 checkForDeviceAndOutputChanges();
4319 updateCallAndOutputRouting();
4320 }
4321 return res;
4322}
4323
Mikhail Naganov100f0122018-11-29 11:22:16 -08004324void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4325{
4326 size_t i = 0;
4327 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4328 for (const auto& fmt : mManualSurroundFormats) {
4329 if (i++ != 0) dst->append(", ");
4330 std::string sfmt;
4331 FormatConverter::toString(fmt, sfmt);
4332 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4333 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4334 }
4335}
4336
Eric Laurentc529cf62020-04-17 18:19:10 -07004337// Returns true if all devices types match the predicate and are supported by one HW module
4338bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004339 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004340 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004341 const char *context,
4342 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004343 for (size_t i = 0; i < devices.size(); i++) {
4344 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004345 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004346 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004347 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004348 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004349 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004350 return false;
4351 }
4352 }
4353 return true;
4354}
4355
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004356void AudioPolicyManager::changeOutputDevicesMuteState(
4357 const AudioDeviceTypeAddrVector& devices) {
4358 ALOGVV("%s() num devices %zu", __func__, devices.size());
4359
4360 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4361 getSoftwareOutputsForDevices(devices);
4362
4363 for (size_t i = 0; i < outputs.size(); i++) {
4364 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4365 DeviceVector prevDevices = outputDesc->devices();
4366 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4367 }
4368}
4369
4370std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4371 const AudioDeviceTypeAddrVector& devices) const
4372{
4373 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4374 DeviceVector deviceDescriptors;
4375 for (size_t j = 0; j < devices.size(); j++) {
4376 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4377 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4378 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4379 ALOGE("%s: device type %#x address %s not supported or not an output device",
4380 __func__, devices[j].mType, devices[j].getAddress());
4381 continue;
4382 }
4383 deviceDescriptors.add(desc);
4384 }
4385 for (size_t i = 0; i < mOutputs.size(); i++) {
4386 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4387 continue;
4388 }
4389 outputs.push_back(mOutputs.valueAt(i));
4390 }
4391 return outputs;
4392}
4393
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004394status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004395 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004396 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004397 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4398 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004399 }
4400 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004401 if (res != NO_ERROR) {
4402 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4403 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004404 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004405
4406 checkForDeviceAndOutputChanges();
4407 updateCallAndOutputRouting();
4408
4409 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004410}
4411
4412status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4413 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004414 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4415 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004416 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004417 __FUNCTION__, uid);
4418 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004419 }
4420
Eric Laurentc529cf62020-04-17 18:19:10 -07004421 checkForDeviceAndOutputChanges();
4422 updateCallAndOutputRouting();
4423
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004424 return res;
4425}
4426
Eric Laurent2517af32020-11-25 15:31:27 +01004427
jiabin0a488932020-08-07 17:32:40 -07004428status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4429 device_role_t role,
4430 const AudioDeviceTypeAddrVector &devices) {
4431 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4432 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004433
Eric Laurentc529cf62020-04-17 18:19:10 -07004434 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004435 return BAD_VALUE;
4436 }
jiabin0a488932020-08-07 17:32:40 -07004437 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004438 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004439 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4440 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004441 return status;
4442 }
4443
4444 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004445
4446 bool forceVolumeReeval = false;
4447 // FIXME: workaround for truncated touch sounds
4448 // to be removed when the problem is handled by system UI
4449 uint32_t delayMs = 0;
4450 if (strategy == mCommunnicationStrategy) {
4451 forceVolumeReeval = true;
4452 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4453 updateInputRouting();
4454 }
4455 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004456
4457 return NO_ERROR;
4458}
4459
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004460void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4461 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004462{
4463 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004464 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004465 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004466 // Only apply special touch sound delay once
4467 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004468 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004469 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004470 for (size_t i = 0; i < mOutputs.size(); i++) {
4471 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4472 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004473 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4474 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004475 // As done in setDeviceConnectionState, we could also fix default device issue by
4476 // preventing the force re-routing in case of default dev that distinguishes on address.
4477 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004478 bool newDevicesNotEmpty = !newDevices.isEmpty();
4479 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4480 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004481 // If the device is using preferred mixer attributes, the output need to reopen
4482 // with default configuration when the new selected devices are different from
4483 // current routing devices.
4484 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4485 continue;
4486 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304487
jiabin2361ed82024-09-20 17:36:31 +00004488 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4489 newDevicesNotEmpty /*force*/, delayMs,
4490 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4491 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004492 // Only apply special touch sound delay once
4493 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004494 }
4495 if (forceVolumeReeval && !newDevices.isEmpty()) {
4496 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4497 }
4498 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004499 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004500 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004501}
4502
Eric Laurent2517af32020-11-25 15:31:27 +01004503void AudioPolicyManager::updateInputRouting() {
4504 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304505 // Skip for hotword recording as the input device switch
4506 // is handled within sound trigger HAL
4507 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4508 continue;
4509 }
Eric Laurent2517af32020-11-25 15:31:27 +01004510 auto newDevice = getNewInputDevice(activeDesc);
4511 // Force new input selection if the new device can not be reached via current input
4512 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4513 setInputDevice(activeDesc->mIoHandle, newDevice);
4514 } else {
4515 closeInput(activeDesc->mIoHandle);
4516 }
4517 }
4518}
4519
Paul Wang5d7cdb52022-11-22 09:45:06 +00004520status_t
4521AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4522 device_role_t role,
4523 const AudioDeviceTypeAddrVector &devices) {
4524 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4525 dumpAudioDeviceTypeAddrVector(devices).c_str());
4526
Eric Laurent78fedbf2023-03-09 14:40:44 +01004527 if (!areAllDevicesSupported(
4528 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004529 return BAD_VALUE;
4530 }
4531 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4532 if (status != NO_ERROR) {
4533 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4534 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4535 return status;
4536 }
4537
4538 checkForDeviceAndOutputChanges();
4539
4540 bool forceVolumeReeval = false;
4541 // TODO(b/263479999): workaround for truncated touch sounds
4542 // to be removed when the problem is handled by system UI
4543 uint32_t delayMs = 0;
4544 if (strategy == mCommunnicationStrategy) {
4545 forceVolumeReeval = true;
4546 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4547 updateInputRouting();
4548 }
4549 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4550
4551 return NO_ERROR;
4552}
4553
4554status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4555 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004556{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004557 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004558
Paul Wang5d7cdb52022-11-22 09:45:06 +00004559 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004560 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004561 ALOGW_IF(status != NAME_NOT_FOUND,
4562 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004563 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004564 return status;
4565 }
4566
4567 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004568
4569 bool forceVolumeReeval = false;
4570 // FIXME: workaround for truncated touch sounds
4571 // to be removed when the problem is handled by system UI
4572 uint32_t delayMs = 0;
4573 if (strategy == mCommunnicationStrategy) {
4574 forceVolumeReeval = true;
4575 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4576 updateInputRouting();
4577 }
4578 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004579
4580 return NO_ERROR;
4581}
4582
jiabin0a488932020-08-07 17:32:40 -07004583status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4584 device_role_t role,
4585 AudioDeviceTypeAddrVector &devices) {
4586 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004587}
4588
Jiabin Huang3b98d322020-09-03 17:54:16 +00004589status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4590 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4591 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4592 dumpAudioDeviceTypeAddrVector(devices).c_str());
4593
Mikhail Naganov55773032020-10-01 15:08:13 -07004594 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004595 return BAD_VALUE;
4596 }
4597 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4598 ALOGW_IF(status != NO_ERROR,
4599 "Engine could not set preferred devices %s for audio source %d role %d",
4600 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4601
Wenyu Zhang47655d22024-10-01 12:24:53 +00004602 if (status == NO_ERROR) {
4603 updateInputRouting();
4604 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004605 return status;
4606}
4607
4608status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4609 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4610 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4611 dumpAudioDeviceTypeAddrVector(devices).c_str());
4612
Mikhail Naganov55773032020-10-01 15:08:13 -07004613 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004614 return BAD_VALUE;
4615 }
4616 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4617 ALOGW_IF(status != NO_ERROR,
4618 "Engine could not add preferred devices %s for audio source %d role %d",
4619 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4620
Eric Laurent2517af32020-11-25 15:31:27 +01004621 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004622 return status;
4623}
4624
4625status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4626 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4627{
4628 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4629 dumpAudioDeviceTypeAddrVector(devices).c_str());
4630
Eric Laurent78fedbf2023-03-09 14:40:44 +01004631 if (!areAllDevicesSupported(
4632 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004633 return BAD_VALUE;
4634 }
4635
4636 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4637 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004638 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004639 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004640 if (status == NO_ERROR) {
4641 updateInputRouting();
4642 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004643 return status;
4644}
4645
4646status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4647 device_role_t role) {
4648 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4649
4650 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004651 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004652 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004653 if (status == NO_ERROR) {
4654 updateInputRouting();
4655 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004656 return status;
4657}
4658
4659status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4660 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4661 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4662}
4663
Oscar Azucena90e77632019-11-27 17:12:28 -08004664status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004665 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004666 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004667 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4668 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004669 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004670 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4671 if (status != NO_ERROR) {
4672 ALOGE("%s() could not set device affinity for userId %d",
4673 __FUNCTION__, userId);
4674 return status;
4675 }
4676
4677 // reevaluate outputs for all devices
4678 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004679 changeOutputDevicesMuteState(devices);
4680 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4681 true /* skipDelays */);
4682 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004683
4684 return NO_ERROR;
4685}
4686
4687status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004688 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004689 AudioDeviceTypeAddrVector devices;
4690 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004691 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4692 if (status != NO_ERROR) {
4693 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4694 __FUNCTION__, userId);
4695 return status;
4696 }
4697
4698 // reevaluate outputs for all devices
4699 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004700 changeOutputDevicesMuteState(devices);
4701 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4702 true /* skipDelays */);
4703 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004704
4705 return NO_ERROR;
4706}
4707
Andy Hungc29d82b2018-10-05 12:23:17 -07004708void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004709{
Andy Hungc29d82b2018-10-05 12:23:17 -07004710 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004711 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004712 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004713 std::string stateLiteral;
4714 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004715 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004716 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4717 "communications", "media", "record", "dock", "system",
4718 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4719 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4720 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004721 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4722 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4723 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4724 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4725 dst->append(" (MANUAL: ");
4726 dumpManualSurroundFormats(dst);
4727 dst->append(")");
4728 }
4729 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004730 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004731 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4732 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004733 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004734 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004735
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004736 dst->append("\n");
4737 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4738 dst->append("\n");
4739 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004740 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004741 mOutputs.dump(dst);
4742 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004743 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004744 mAudioPatches.dump(dst);
4745 mPolicyMixes.dump(dst);
4746 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004747
Kevin Rocardb99cc752019-03-21 20:52:24 -07004748 dst->appendFormat(" AllowedCapturePolicies:\n");
4749 for (auto& policy : mAllowedCapturePolicies) {
4750 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4751 }
4752
jiabina84c3d32022-12-02 18:59:55 +00004753 dst->appendFormat(" Preferred mixer audio configuration:\n");
4754 for (const auto it : mPreferredMixerAttrInfos) {
4755 dst->appendFormat(" - device port id: %d\n", it.first);
4756 for (const auto preferredMixerInfoIt : it.second) {
4757 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4758 preferredMixerInfoIt.second->dump(dst);
4759 }
4760 }
4761
François Gaffiec005e562018-11-06 15:04:49 +01004762 dst->appendFormat("\nPolicy Engine dump:\n");
4763 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004764
4765 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4766 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4767 dst->appendFormat(" - device type: %s, driving stream %d\n",
4768 dumpDeviceTypes({it.first}).c_str(),
4769 mEngine->getVolumeGroupForAttributes(it.second));
4770 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004771
4772 // dump mmap policy by device
4773 dst->appendFormat("\nMmap policy:\n");
4774 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4775 std::stringstream ss;
4776 ss << '{';
4777 for (const auto& [deviceType, policy] : policyByDevice) {
4778 ss << deviceType.toString() << ":" << toString(policy) << " ";
4779 }
4780 ss << '}';
4781 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4782 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004783}
4784
4785status_t AudioPolicyManager::dump(int fd)
4786{
4787 String8 result;
4788 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004789 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004790 return NO_ERROR;
4791}
4792
Kevin Rocardb99cc752019-03-21 20:52:24 -07004793status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4794{
4795 mAllowedCapturePolicies[uid] = capturePolicy;
4796 return NO_ERROR;
4797}
4798
Eric Laurente552edb2014-03-10 17:42:56 -07004799// This function checks for the parameters which can be offloaded.
4800// This can be enhanced depending on the capability of the DSP and policy
4801// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004802audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004803{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004804 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004805 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004806 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004807 offloadInfo.format,
4808 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4809 offloadInfo.has_video);
4810
jiabin2b9d5a12021-12-10 01:06:29 +00004811 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004812 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004813 }
4814
4815 // See if there is a profile to support this.
4816 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004817 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004818 offloadInfo.sample_rate,
4819 offloadInfo.format,
4820 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004821 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4822 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004823 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4824 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4825 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004826 if (profile == nullptr) {
4827 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4828 }
4829 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4830 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4831 }
4832 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004833}
4834
Michael Chana94fbb22018-04-24 14:31:19 +10004835bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4836 const audio_attributes_t& attributes) {
4837 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004838 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004839 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4840 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004841 config.sample_rate,
4842 config.format,
4843 config.channel_mask,
4844 output_flags,
4845 true /* directOnly */);
4846 ALOGV("%s() profile %sfound with name: %s, "
4847 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4848 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004849 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004850 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004851
4852 // also try the MSD module if compatible profile not found
4853 if (profile == nullptr) {
4854 profile = getMsdProfileForOutput(outputDevices,
4855 config.sample_rate,
4856 config.format,
4857 config.channel_mask,
4858 output_flags,
4859 true /* directOnly */);
4860 ALOGV("%s() MSD profile %sfound with name: %s, "
4861 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4862 __FUNCTION__, profile != 0 ? "" : "NOT ",
4863 (profile != 0 ? profile->getTagName().c_str() : "null"),
4864 config.sample_rate, config.format, config.channel_mask, output_flags);
4865 }
4866 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004867}
4868
jiabin2b9d5a12021-12-10 01:06:29 +00004869bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4870 bool durationIgnored) {
4871 if (mMasterMono) {
4872 return false; // no offloading if mono is set.
4873 }
4874
4875 // Check if offload has been disabled
4876 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4877 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4878 return false;
4879 }
4880
4881 // Check if stream type is music, then only allow offload as of now.
4882 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4883 {
4884 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4885 return false;
4886 }
4887
4888 //TODO: enable audio offloading with video when ready
4889 const bool allowOffloadWithVideo =
4890 property_get_bool("audio.offload.video", false /* default_value */);
4891 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4892 ALOGV("%s: has_video == true, returning false", __func__);
4893 return false;
4894 }
4895
4896 //If duration is less than minimum value defined in property, return false
4897 const int min_duration_secs = property_get_int32(
4898 "audio.offload.min.duration.secs", -1 /* default_value */);
4899 if (!durationIgnored) {
4900 if (min_duration_secs >= 0) {
4901 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4902 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4903 __func__, min_duration_secs);
4904 return false;
4905 }
4906 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4907 ALOGV("%s: Offload denied by duration < default min(=%u)",
4908 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4909 return false;
4910 }
4911 }
4912
4913 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4914 // creating an offloaded track and tearing it down immediately after start when audioflinger
4915 // detects there is an active non offloadable effect.
4916 // FIXME: We should check the audio session here but we do not have it in this context.
4917 // This may prevent offloading in rare situations where effects are left active by apps
4918 // in the background.
4919 if (mEffects.isNonOffloadableEffectEnabled()) {
4920 return false;
4921 }
4922
4923 return true;
4924}
4925
4926audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4927 const audio_config_t *config) {
4928 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4929 offloadInfo.format = config->format;
4930 offloadInfo.sample_rate = config->sample_rate;
4931 offloadInfo.channel_mask = config->channel_mask;
4932 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4933 offloadInfo.has_video = false;
4934 offloadInfo.is_streaming = false;
4935 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4936
4937 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4938 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4939 audio_flags_to_audio_output_flags(attr->flags, &flags);
4940 // only retain flags that will drive compressed offload or passthrough
4941 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4942 if (offloadPossible) {
4943 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4944 }
4945 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4946
Dorin Drimusfae3c642022-03-17 18:36:30 +01004947 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004948 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4949 [this, attr](sp<DeviceDescriptor> device) {
4950 return getPreferredMixerAttributesInfo(
4951 device->getId(),
4952 mEngine->getProductStrategyForAttributes(*attr),
4953 true /*activeBitPerfectPreferred*/) != nullptr;
4954 })) {
4955 // Bit-perfect playback is active on one of the selected devices, direct output will
4956 // be rejected at this instant.
4957 return AUDIO_DIRECT_NOT_SUPPORTED;
4958 }
jiabin2b9d5a12021-12-10 01:06:29 +00004959 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004960 DeviceVector outputDevices = engineOutputDevices;
4961 // the MSD module checks for different conditions and output devices
4962 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4963 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4964 continue;
4965 }
4966 outputDevices = getMsdAudioOutDevices();
4967 }
jiabin2b9d5a12021-12-10 01:06:29 +00004968 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004969 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004970 config->sample_rate, nullptr /*updatedSamplingRate*/,
4971 config->format, nullptr /*updatedFormat*/,
4972 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004973 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004974 continue;
4975 }
4976 // reject profiles not corresponding to a device currently available
4977 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4978 continue;
4979 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004980 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4981 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004982 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004983 != AUDIO_DIRECT_NOT_SUPPORTED) {
4984 // Already reports offload gapless supported. No need to report offload support.
4985 continue;
4986 }
4987 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4988 != AUDIO_OUTPUT_FLAG_NONE) {
4989 // If offload gapless is reported, no need to report offload support.
4990 directMode = (audio_direct_mode_t) ((directMode &
4991 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4992 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4993 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004994 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004995 }
4996 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004997 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004998 }
4999 }
5000 }
5001 return directMode;
5002}
5003
Dorin Drimusf2196d82022-01-03 12:11:18 +01005004status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
5005 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00005006 if (mEffects.isNonOffloadableEffectEnabled()) {
5007 return OK;
5008 }
jiabinf1c73972022-04-14 16:28:52 -07005009 DeviceVector devices;
5010 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01005011 if (status != OK) {
5012 return status;
5013 }
5014 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
5015 if (devices.empty()) {
5016 return OK; // no output devices for the attributes
5017 }
jiabinf1c73972022-04-14 16:28:52 -07005018 return getProfilesForDevices(devices, audioProfilesVector,
5019 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01005020}
5021
jiabina84c3d32022-12-02 18:59:55 +00005022status_t AudioPolicyManager::getSupportedMixerAttributes(
5023 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
5024 ALOGV("%s, portId=%d", __func__, portId);
5025 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5026 if (deviceDescriptor == nullptr) {
5027 ALOGE("%s the requested device is currently unavailable", __func__);
5028 return BAD_VALUE;
5029 }
jiabin96daffc2023-05-11 17:51:55 +00005030 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5031 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
5032 deviceDescriptor->type());
5033 return BAD_VALUE;
5034 }
jiabina84c3d32022-12-02 18:59:55 +00005035 for (const auto& hwModule : mHwModules) {
5036 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5037 if (curProfile->supportsDevice(deviceDescriptor)) {
5038 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5039 }
5040 }
5041 }
5042 return NO_ERROR;
5043}
5044
5045status_t AudioPolicyManager::setPreferredMixerAttributes(
5046 const audio_attributes_t *attr,
5047 audio_port_handle_t portId,
5048 uid_t uid,
5049 const audio_mixer_attributes_t *mixerAttributes) {
5050 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5051 "mixerBehavior=%d}, uid=%d, portId=%u",
5052 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5053 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5054 mixerAttributes->mixer_behavior, uid, portId);
5055 if (attr->usage != AUDIO_USAGE_MEDIA) {
5056 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5057 return BAD_VALUE;
5058 }
5059 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5060 if (deviceDescriptor == nullptr) {
5061 ALOGE("%s the requested device is currently unavailable", __func__);
5062 return BAD_VALUE;
5063 }
5064 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5065 ALOGE("%s(%d), type=%d, is not a usb output device",
5066 __func__, portId, deviceDescriptor->type());
5067 return BAD_VALUE;
5068 }
5069
5070 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5071 audio_flags_to_audio_output_flags(attr->flags, &flags);
5072 flags = (audio_output_flags_t) (flags |
5073 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5074 sp<IOProfile> profile = nullptr;
5075 DeviceVector devices(deviceDescriptor);
5076 for (const auto& hwModule : mHwModules) {
5077 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5078 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005079 && curProfile->getCompatibilityScore(
5080 devices,
5081 mixerAttributes->config.sample_rate,
5082 nullptr /*updatedSamplingRate*/,
5083 mixerAttributes->config.format,
5084 nullptr /*updatedFormat*/,
5085 mixerAttributes->config.channel_mask,
5086 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005087 flags)
jiabin66acc432024-02-06 00:57:36 +00005088 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005089 profile = curProfile;
5090 break;
5091 }
5092 }
5093 }
5094 if (profile == nullptr) {
5095 ALOGE("%s, there is no compatible profile found", __func__);
5096 return BAD_VALUE;
5097 }
5098
5099 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5100 sp<PreferredMixerAttributesInfo>::make(
5101 uid, portId, profile, flags, *mixerAttributes);
5102 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5103 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5104
5105 // If 1) there is any client from the preferred mixer configuration owner that is currently
5106 // active and matches the strategy and 2) current output is on the preferred device and the
5107 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5108 // configuration.
5109 std::vector<audio_io_handle_t> outputsToReopen;
5110 for (size_t i = 0; i < mOutputs.size(); i++) {
5111 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005112 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5113 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005114 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005115 } else {
5116 for (const auto &client: output->getActiveClients()) {
5117 if (client->uid() == uid && client->strategy() == strategy) {
5118 client->setIsInvalid();
5119 outputsToReopen.push_back(output->mIoHandle);
5120 }
jiabina84c3d32022-12-02 18:59:55 +00005121 }
5122 }
5123 }
5124 }
5125 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5126 config.sample_rate = mixerAttributes->config.sample_rate;
5127 config.channel_mask = mixerAttributes->config.channel_mask;
5128 config.format = mixerAttributes->config.format;
5129 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005130 sp<SwAudioOutputDescriptor> desc =
5131 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5132 if (desc == nullptr) {
5133 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5134 continue;
5135 }
jiabin220eea12024-05-17 17:55:20 +00005136 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005137 }
5138
5139 return NO_ERROR;
5140}
5141
5142sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005143 audio_port_handle_t devicePortId,
5144 product_strategy_t strategy,
5145 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005146 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5147 if (it == mPreferredMixerAttrInfos.end()) {
5148 return nullptr;
5149 }
jiabind9a58d32023-06-01 17:57:30 +00005150 if (activeBitPerfectPreferred) {
5151 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005152 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005153 return info;
5154 }
5155 }
jiabina84c3d32022-12-02 18:59:55 +00005156 }
jiabind9a58d32023-06-01 17:57:30 +00005157 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5158 return strategyMatchedMixerAttrInfoIt == it->second.end()
5159 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005160}
5161
5162status_t AudioPolicyManager::getPreferredMixerAttributes(
5163 const audio_attributes_t *attr,
5164 audio_port_handle_t portId,
5165 audio_mixer_attributes_t* mixerAttributes) {
5166 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5167 portId, mEngine->getProductStrategyForAttributes(*attr));
5168 if (info == nullptr) {
5169 return NAME_NOT_FOUND;
5170 }
5171 *mixerAttributes = info->getMixerAttributes();
5172 return NO_ERROR;
5173}
5174
5175status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5176 audio_port_handle_t portId,
5177 uid_t uid) {
5178 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5179 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5180 if (preferredMixerAttrInfo == nullptr) {
5181 return NAME_NOT_FOUND;
5182 }
5183 if (preferredMixerAttrInfo->getUid() != uid) {
5184 ALOGE("%s, requested uid=%d, owned uid=%d",
5185 __func__, uid, preferredMixerAttrInfo->getUid());
5186 return PERMISSION_DENIED;
5187 }
5188 mPreferredMixerAttrInfos[portId].erase(strategy);
5189 if (mPreferredMixerAttrInfos[portId].empty()) {
5190 mPreferredMixerAttrInfos.erase(portId);
5191 }
5192
5193 // Reconfig existing output
5194 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5195 for (size_t i = 0; i < mOutputs.size(); i++) {
5196 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5197 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5198 }
5199 }
5200 for (const auto output : potentialOutputsToReopen) {
5201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5202 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5203 preferredMixerAttrInfo->getFlags())) {
5204 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5205 }
5206 }
5207 return NO_ERROR;
5208}
5209
Eric Laurent6a94d692014-05-20 11:18:06 -07005210status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5211 audio_port_type_t type,
5212 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005213 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 unsigned int *generation)
5215{
jiabin19cdba52020-11-24 11:28:58 -08005216 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5217 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005218 return BAD_VALUE;
5219 }
5220 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005221 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 *num_ports = 0;
5223 }
5224
5225 size_t portsWritten = 0;
5226 size_t portsMax = *num_ports;
5227 *num_ports = 0;
5228 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005229 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5230 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005232 for (const auto& dev : mAvailableOutputDevices) {
5233 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005234 continue;
5235 }
5236 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005237 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005238 }
5239 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005241 }
5242 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005243 for (const auto& dev : mAvailableInputDevices) {
5244 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005245 continue;
5246 }
5247 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005248 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005249 }
5250 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 }
5253 }
5254 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5255 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5256 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5257 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5258 }
5259 *num_ports += mInputs.size();
5260 }
5261 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005262 size_t numOutputs = 0;
5263 for (size_t i = 0; i < mOutputs.size(); i++) {
5264 if (!mOutputs[i]->isDuplicated()) {
5265 numOutputs++;
5266 if (portsWritten < portsMax) {
5267 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5268 }
5269 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 }
Eric Laurent84c70242014-06-23 08:46:27 -07005271 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 }
5273 }
jiabina84c3d32022-12-02 18:59:55 +00005274
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005276 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 return NO_ERROR;
5278}
5279
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005280status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5281 std::vector<media::AudioPortFw>* _aidl_return) {
5282 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5283 audio_port_v7 port;
5284 dev->toAudioPort(&port);
5285 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5286 _aidl_return->push_back(std::move(aidlPort));
5287 return OK;
5288 };
5289
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005290 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005291 for (const auto& dev : module->getDeclaredDevices()) {
5292 if (role == media::AudioPortRole::NONE ||
5293 ((role == media::AudioPortRole::SOURCE)
5294 == audio_is_input_device(dev->type()))) {
5295 RETURN_STATUS_IF_ERROR(pushPort(dev));
5296 }
5297 }
5298 }
5299 return OK;
5300}
5301
jiabin19cdba52020-11-24 11:28:58 -08005302status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005303{
Eric Laurent99fcae42018-05-17 16:59:18 -07005304 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5305 return BAD_VALUE;
5306 }
5307 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5308 if (dev != 0) {
5309 dev->toAudioPort(port);
5310 return NO_ERROR;
5311 }
5312 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5313 if (dev != 0) {
5314 dev->toAudioPort(port);
5315 return NO_ERROR;
5316 }
5317 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5318 if (out != 0) {
5319 out->toAudioPort(port);
5320 return NO_ERROR;
5321 }
5322 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5323 if (in != 0) {
5324 in->toAudioPort(port);
5325 return NO_ERROR;
5326 }
5327 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005328}
5329
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005330status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5331 audio_patch_handle_t *handle,
5332 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005333{
François Gaffieafd4cea2019-11-18 15:50:22 +01005334 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 if (handle == NULL || patch == NULL) {
5336 return BAD_VALUE;
5337 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005339 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005340 return BAD_VALUE;
5341 }
5342 // only one source per audio patch supported for now
5343 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 return INVALID_OPERATION;
5345 }
Eric Laurent874c42872014-08-08 15:13:39 -07005346 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 return INVALID_OPERATION;
5348 }
Eric Laurent874c42872014-08-08 15:13:39 -07005349 for (size_t i = 0; i < patch->num_sinks; i++) {
5350 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5351 return INVALID_OPERATION;
5352 }
5353 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005354
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005355 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5356 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5357 if (srcDevice == nullptr || sinkDevice == nullptr) {
5358 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5359 return BAD_VALUE;
5360 }
5361 ALOGV("%s between source %s and sink %s", __func__,
5362 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5363 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5364 // Default attributes, default volume priority, not to infer with non raw audio patches.
5365 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5366 const struct audio_port_config *source = &patch->sources[0];
5367 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005368 new SourceClientDescriptor(
5369 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5370 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005371 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005372 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005373
5374 status_t status =
5375 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5376
5377 if (status != NO_ERROR) {
5378 return INVALID_OPERATION;
5379 }
5380 mAudioSources.add(portId, sourceDesc);
5381 return NO_ERROR;
5382}
5383
5384status_t AudioPolicyManager::connectAudioSourceToSink(
5385 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5386 const struct audio_patch *patch,
5387 audio_patch_handle_t &handle,
5388 uid_t uid, uint32_t delayMs)
5389{
5390 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5391 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5392 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5393 return INVALID_OPERATION;
5394 }
5395 sourceDesc->connect(handle, sinkDevice);
5396 if (isMsdPatch(handle)) {
5397 return NO_ERROR;
5398 }
5399 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5400 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5401 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5402 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5403 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5404 goto FailurePatchAdded;
5405 }
5406 status = swOutput->start();
5407 if (status != NO_ERROR) {
5408 goto FailureSourceAdded;
5409 }
5410 swOutput->addClient(sourceDesc);
5411 status = startSource(swOutput, sourceDesc, &delayMs);
5412 if (status != NO_ERROR) {
5413 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5414 goto FailureSourceActive;
5415 }
5416 if (delayMs != 0) {
5417 usleep(delayMs * 1000);
5418 }
5419 return NO_ERROR;
5420
5421FailureSourceActive:
5422 swOutput->stop();
5423 releaseOutput(sourceDesc->portId());
5424FailureSourceAdded:
5425 sourceDesc->setSwOutput(nullptr);
5426FailurePatchAdded:
5427 releaseAudioPatchInternal(handle);
5428 return INVALID_OPERATION;
5429}
5430
5431status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5432 audio_patch_handle_t *handle,
5433 uid_t uid, uint32_t delayMs,
5434 const sp<SourceClientDescriptor>& sourceDesc)
5435{
5436 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005437 sp<AudioPatch> patchDesc;
5438 ssize_t index = mAudioPatches.indexOfKey(*handle);
5439
François Gaffieafd4cea2019-11-18 15:50:22 +01005440 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5441 patch->sources[0].role,
5442 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005443#if LOG_NDEBUG == 0
5444 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005445 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5446 patch->sinks[i].role,
5447 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005448 }
5449#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005450
5451 if (index >= 0) {
5452 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5454 __func__, mUidCached, patchDesc->getUid(), uid);
5455 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005456 return INVALID_OPERATION;
5457 }
5458 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005459 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005460 }
5461
5462 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005463 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005464 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005465 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005466 return BAD_VALUE;
5467 }
Eric Laurent84c70242014-06-23 08:46:27 -07005468 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5469 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005470 if (patchDesc != 0) {
5471 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005472 ALOGV("%s source id differs for patch current id %d new id %d",
5473 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005474 return BAD_VALUE;
5475 }
5476 }
Eric Laurent874c42872014-08-08 15:13:39 -07005477 DeviceVector devices;
5478 for (size_t i = 0; i < patch->num_sinks; i++) {
5479 // Only support mix to devices connection
5480 // TODO add support for mix to mix connection
5481 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005482 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005483 return INVALID_OPERATION;
5484 }
5485 sp<DeviceDescriptor> devDesc =
5486 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5487 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005488 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005489 return BAD_VALUE;
5490 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005491
jiabin66acc432024-02-06 00:57:36 +00005492 if (outputDesc->mProfile->getCompatibilityScore(
5493 DeviceVector(devDesc),
5494 patch->sources[0].sample_rate,
5495 nullptr, // updatedSamplingRate
5496 patch->sources[0].format,
5497 nullptr, // updatedFormat
5498 patch->sources[0].channel_mask,
5499 nullptr, // updatedChannelMask
5500 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005501 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005502 return INVALID_OPERATION;
5503 }
5504 devices.add(devDesc);
5505 }
5506 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005507 return INVALID_OPERATION;
5508 }
Eric Laurent874c42872014-08-08 15:13:39 -07005509
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005511 ALOGV("%s setting device %s on output %d",
5512 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305513 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005514 index = mAudioPatches.indexOfKey(*handle);
5515 if (index >= 0) {
5516 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005517 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005518 }
5519 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005520 patchDesc->setUid(uid);
5521 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005522 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005523 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005524 return INVALID_OPERATION;
5525 }
5526 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5527 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5528 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005529 // only one sink supported when connecting an input device to a mix
5530 if (patch->num_sinks > 1) {
5531 return INVALID_OPERATION;
5532 }
François Gaffie53615e22015-03-19 09:24:12 +01005533 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 if (inputDesc == NULL) {
5535 return BAD_VALUE;
5536 }
5537 if (patchDesc != 0) {
5538 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5539 return BAD_VALUE;
5540 }
5541 }
François Gaffie11d30102018-11-02 16:09:09 +01005542 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005543 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005544 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005545 return BAD_VALUE;
5546 }
5547
jiabin66acc432024-02-06 00:57:36 +00005548 if (inputDesc->mProfile->getCompatibilityScore(
5549 DeviceVector(device),
5550 patch->sinks[0].sample_rate,
5551 nullptr, /*updatedSampleRate*/
5552 patch->sinks[0].format,
5553 nullptr, /*updatedFormat*/
5554 patch->sinks[0].channel_mask,
5555 nullptr, /*updatedChannelMask*/
5556 // FIXME for the parameter type,
5557 // and the NONE
5558 (audio_output_flags_t)
5559 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005560 return INVALID_OPERATION;
5561 }
5562 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005563 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005564 device->toString().c_str(), inputDesc->mIoHandle);
5565 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005566 index = mAudioPatches.indexOfKey(*handle);
5567 if (index >= 0) {
5568 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005570 }
5571 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005572 patchDesc->setUid(uid);
5573 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005574 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005575 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005576 return INVALID_OPERATION;
5577 }
5578 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5579 // device to device connection
5580 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005581 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005582 return BAD_VALUE;
5583 }
5584 }
François Gaffie11d30102018-11-02 16:09:09 +01005585 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005586 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005587 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005588 return BAD_VALUE;
5589 }
Eric Laurent874c42872014-08-08 15:13:39 -07005590
Eric Laurent6a94d692014-05-20 11:18:06 -07005591 //update source and sink with our own data as the data passed in the patch may
5592 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005593 PatchBuilder patchBuilder;
5594 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005595
5596 // if first sink is to MSD, establish single MSD patch
5597 if (getMsdAudioOutDevices().contains(
5598 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5599 ALOGV("%s patching to MSD", __FUNCTION__);
5600 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5601 goto installPatch;
5602 }
5603
François Gaffieafd4cea2019-11-18 15:50:22 +01005604 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5605 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005606
Eric Laurent874c42872014-08-08 15:13:39 -07005607 for (size_t i = 0; i < patch->num_sinks; i++) {
5608 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005609 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005610 return INVALID_OPERATION;
5611 }
François Gaffie11d30102018-11-02 16:09:09 +01005612 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005613 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005614 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005615 return BAD_VALUE;
5616 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005617 audio_port_config sinkPortConfig = {};
5618 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5619 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005620
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005621 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5622 // volume management purpose (tracking activity)
5623 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5624 // in config XML to reach the sink so that is can be declared as available.
5625 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005626 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005627 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005628 // take care of dynamic routing for SwOutput selection,
5629 audio_attributes_t attributes = sourceDesc->attributes();
5630 audio_stream_type_t stream = sourceDesc->stream();
5631 audio_attributes_t resultAttr;
5632 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5633 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005634 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5635 config.channel_mask =
5636 (audio_channel_mask_get_representation(sourceMask)
5637 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5638 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005639 config.format = sourceDesc->config().format;
5640 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Robert Wufb971192024-10-30 21:54:35 +00005641 DeviceIdVector selectedDeviceIds;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005642 bool isRequestedDeviceForExclusiveUse = false;
5643 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005644 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005645 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005646 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5647 &stream, sourceDesc->uid(), &config, &flags,
Robert Wufb971192024-10-30 21:54:35 +00005648 &selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005649 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005650 if (output == AUDIO_IO_HANDLE_NONE) {
5651 ALOGV("%s no output for device %s",
5652 __FUNCTION__, sinkDevice->toString().c_str());
5653 return INVALID_OPERATION;
5654 }
5655 outputDesc = mOutputs.valueFor(output);
5656 if (outputDesc->isDuplicated()) {
5657 ALOGE("%s output is duplicated", __func__);
5658 return INVALID_OPERATION;
5659 }
François Gaffie7e39df22022-04-26 12:48:49 +02005660 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5661 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005662 } else {
5663 // Same for "raw patches" aka created from createAudioPatch API
5664 SortedVector<audio_io_handle_t> outputs =
5665 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5666 // if the sink device is reachable via an opened output stream, request to
5667 // go via this output stream by adding a second source to the patch
5668 // description
5669 output = selectOutput(outputs);
5670 if (output == AUDIO_IO_HANDLE_NONE) {
5671 ALOGE("%s no output available for internal patch sink", __func__);
5672 return INVALID_OPERATION;
5673 }
5674 outputDesc = mOutputs.valueFor(output);
5675 if (outputDesc->isDuplicated()) {
5676 ALOGV("%s output for device %s is duplicated",
5677 __func__, sinkDevice->toString().c_str());
5678 return INVALID_OPERATION;
5679 }
François Gaffie7e39df22022-04-26 12:48:49 +02005680 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005681 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005682 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005683 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005684 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005685 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005686 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5687 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005688 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5689 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005690 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005691 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005692 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005693 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005694 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005695 return INVALID_OPERATION;
5696 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005697 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005698 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005699 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005700 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005701 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005702 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005703 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005704 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5705 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005706 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005707 }
Eric Laurent83b88082014-06-20 18:31:16 -07005708 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005709 }
5710 // TODO: check from routing capabilities in config file and other conflicting patches
5711
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005712installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005713 status_t status = installPatch(
5714 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005715 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005716 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005717 return INVALID_OPERATION;
5718 }
5719 } else {
5720 return BAD_VALUE;
5721 }
5722 } else {
5723 return BAD_VALUE;
5724 }
5725 return NO_ERROR;
5726}
5727
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005728status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005729{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005730 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005731 ssize_t index = mAudioPatches.indexOfKey(handle);
5732
5733 if (index < 0) {
5734 return BAD_VALUE;
5735 }
5736 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005737 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5738 __func__, mUidCached, patchDesc->getUid(), uid);
5739 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005740 return INVALID_OPERATION;
5741 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005742 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5743 for (size_t i = 0; i < mAudioSources.size(); i++) {
5744 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5745 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5746 portId = sourceDesc->portId();
5747 break;
5748 }
5749 }
5750 return portId != AUDIO_PORT_HANDLE_NONE ?
5751 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005752}
Eric Laurent6a94d692014-05-20 11:18:06 -07005753
François Gaffieafd4cea2019-11-18 15:50:22 +01005754status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005755 uint32_t delayMs,
5756 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005757{
5758 ALOGV("%s patch %d", __func__, handle);
5759 if (mAudioPatches.indexOfKey(handle) < 0) {
5760 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5761 return BAD_VALUE;
5762 }
5763 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005764 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005765 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005766 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005767 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005768 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005769 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005770 return BAD_VALUE;
5771 }
5772
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305773 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005774 getNewOutputDevices(outputDesc, true /*fromCache*/),
5775 true,
5776 0,
5777 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005778 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5779 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005780 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005781 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005782 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005783 return BAD_VALUE;
5784 }
5785 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005786 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005787 true,
5788 NULL);
5789 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005790 status_t status =
5791 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5792 ALOGV("%s patch panel returned %d patchHandle %d",
5793 __func__, status, patchDesc->getAfHandle());
5794 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005795 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005796 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005797 // SW or HW Bridge
5798 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5799 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005800 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005801 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5802 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5803 outputDesc = sourceDesc->swOutput().promote();
5804 }
5805 if (outputDesc == nullptr) {
5806 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5807 // releaseOutput has already called closeOutput in case of direct output
5808 return NO_ERROR;
5809 }
François Gaffie7e39df22022-04-26 12:48:49 +02005810 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005811 // While using a HwBridge, force reconsidering device only if not reusing an existing
5812 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005813 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005814 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5815 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5816 // Reconsider device only for cases:
5817 // 1 / Active Output
5818 // 2 / Inactive Output previously hosting HwBridge
5819 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5820 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5821 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305822 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005823 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5824 outputDesc->devices(),
5825 force,
5826 0,
5827 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005828 } else {
5829 return BAD_VALUE;
5830 }
5831 } else {
5832 return BAD_VALUE;
5833 }
5834 return NO_ERROR;
5835}
5836
5837status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5838 struct audio_patch *patches,
5839 unsigned int *generation)
5840{
François Gaffie53615e22015-03-19 09:24:12 +01005841 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005842 return BAD_VALUE;
5843 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005844 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005845 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005846}
5847
Eric Laurente1715a42014-05-20 11:30:42 -07005848status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005849{
Eric Laurente1715a42014-05-20 11:30:42 -07005850 ALOGV("setAudioPortConfig()");
5851
5852 if (config == NULL) {
5853 return BAD_VALUE;
5854 }
5855 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5856 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005857 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5858 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005859 }
5860
Eric Laurenta121f902014-06-03 13:32:54 -07005861 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005862 if (config->type == AUDIO_PORT_TYPE_MIX) {
5863 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005864 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005865 if (outputDesc == NULL) {
5866 return BAD_VALUE;
5867 }
Eric Laurent84c70242014-06-23 08:46:27 -07005868 ALOG_ASSERT(!outputDesc->isDuplicated(),
5869 "setAudioPortConfig() called on duplicated output %d",
5870 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005871 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005872 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005873 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005874 if (inputDesc == NULL) {
5875 return BAD_VALUE;
5876 }
Eric Laurenta121f902014-06-03 13:32:54 -07005877 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005878 } else {
5879 return BAD_VALUE;
5880 }
5881 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5882 sp<DeviceDescriptor> deviceDesc;
5883 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5884 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5885 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5886 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5887 } else {
5888 return BAD_VALUE;
5889 }
5890 if (deviceDesc == NULL) {
5891 return BAD_VALUE;
5892 }
Eric Laurenta121f902014-06-03 13:32:54 -07005893 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005894 } else {
5895 return BAD_VALUE;
5896 }
5897
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005898 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005899 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5900 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005901 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005902 audioPortConfig->toAudioPortConfig(&newConfig, config);
5903 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005904 }
Eric Laurenta121f902014-06-03 13:32:54 -07005905 if (status != NO_ERROR) {
5906 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005907 }
Eric Laurente1715a42014-05-20 11:30:42 -07005908
5909 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005910}
5911
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005912void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5913{
Eric Laurentd60560a2015-04-10 11:31:20 -07005914 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005915 clearAudioPatches(uid);
5916 clearSessionRoutes(uid);
5917}
5918
Eric Laurent6a94d692014-05-20 11:18:06 -07005919void AudioPolicyManager::clearAudioPatches(uid_t uid)
5920{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005921 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005922 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005923 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005924 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005925 }
5926 }
5927}
5928
François Gaffiec005e562018-11-06 15:04:49 +01005929void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005930{
François Gaffiec005e562018-11-06 15:04:49 +01005931 // Take the first attributes following the product strategy as it is used to retrieve the routed
5932 // device. All attributes wihin a strategy follows the same "routing strategy"
5933 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5934 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005935 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005936 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005937 for (size_t j = 0; j < mOutputs.size(); j++) {
5938 if (mOutputs.keyAt(j) == ouptutToSkip) {
5939 continue;
5940 }
5941 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005942 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005943 continue;
5944 }
5945 // If the default device for this strategy is on another output mix,
5946 // invalidate all tracks in this strategy to force re connection.
5947 // Otherwise select new device on the output mix.
5948 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005949 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005950 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005951 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005952 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005953 // If the device is using preferred mixer attributes, the output need to reopen
5954 // with default configuration when the new selected devices are different from
5955 // current routing devices.
5956 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5957 continue;
5958 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305959 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005960 }
5961 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005962 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005963}
5964
5965void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5966{
5967 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005968 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005969 for (size_t i = 0; i < mOutputs.size(); i++) {
5970 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005971 for (const auto& client : outputDesc->getClientIterable()) {
5972 if (client->hasPreferredDevice() && client->uid() == uid) {
5973 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005974 auto clientStrategy = client->strategy();
5975 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5976 end(affectedStrategies)) {
5977 continue;
5978 }
5979 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005980 }
5981 }
5982 }
5983 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005984 for (const auto& strategy : affectedStrategies) {
5985 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005986 }
5987
5988 // remove input routes associated with this uid
5989 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005990 for (size_t i = 0; i < mInputs.size(); i++) {
5991 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005992 for (const auto& client : inputDesc->getClientIterable()) {
5993 if (client->hasPreferredDevice() && client->uid() == uid) {
5994 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5995 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005996 }
5997 }
5998 }
5999 // reroute inputs if necessary
6000 SortedVector<audio_io_handle_t> inputsToClose;
6001 for (size_t i = 0; i < mInputs.size(); i++) {
6002 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08006003 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006004 inputsToClose.add(inputDesc->mIoHandle);
6005 }
6006 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006007 for (const auto& input : inputsToClose) {
6008 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006009 }
6010}
6011
Eric Laurentd60560a2015-04-10 11:31:20 -07006012void AudioPolicyManager::clearAudioSources(uid_t uid)
6013{
6014 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006015 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6016 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006017 stopAudioSource(mAudioSources.keyAt(i));
6018 }
6019 }
6020}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006021
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006022status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
6023 audio_io_handle_t *ioHandle,
6024 audio_devices_t *device)
6025{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08006026 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
6027 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01006028 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00006029 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
6030 if (deviceDesc == nullptr) {
6031 return INVALID_OPERATION;
6032 }
6033 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006034
François Gaffiedf372692015-03-19 10:43:27 +01006035 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006036}
6037
Eric Laurentd60560a2015-04-10 11:31:20 -07006038status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006039 const audio_attributes_t *attributes,
6040 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00006041 uid_t uid) {
6042 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006043 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006044}
6045
6046status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6047 const audio_attributes_t *attributes,
6048 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006049 uid_t uid, bool internal, bool isCallRx,
6050 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006051{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006052 ALOGV("%s", __FUNCTION__);
6053 *portId = AUDIO_PORT_HANDLE_NONE;
6054
6055 if (source == NULL || attributes == NULL || portId == NULL) {
6056 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6057 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006058 return BAD_VALUE;
6059 }
6060
Eric Laurentd60560a2015-04-10 11:31:20 -07006061 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6062 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006063 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6064 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006065 return INVALID_OPERATION;
6066 }
6067
François Gaffie11d30102018-11-02 16:09:09 +01006068 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006069 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006070 String8(source->ext.device.address),
6071 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006072 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006073 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006074 return BAD_VALUE;
6075 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006076
jiabin4ef93452019-09-10 14:29:54 -07006077 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006078
François Gaffieaaac0fd2018-11-22 17:56:39 +01006079 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006080 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006081 mEngine->getStreamTypeForAttributes(*attributes),
6082 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006083 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006084
David Lif85c5e32024-07-01 13:14:10 +00006085 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006086 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006087 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006088 }
6089 return status;
6090}
6091
David Lif85c5e32024-07-01 13:14:10 +00006092status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6093 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006094{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006095 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006096
6097 // make sure we only have one patch per source.
6098 disconnectAudioSource(sourceDesc);
6099
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006100 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006101 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6102 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6103 sourceDesc->srcDevice()->type(),
6104 String8(sourceDesc->srcDevice()->address().c_str()),
6105 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006106 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006107 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006108 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006109 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006110 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6111 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6112 return INVALID_OPERATION;
6113 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006114 PatchBuilder patchBuilder;
6115 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6116 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006117
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006118 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006119 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006120}
6121
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006122status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006123{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006124 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6125 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006126 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006127 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006128 return BAD_VALUE;
6129 }
6130 status_t status = disconnectAudioSource(sourceDesc);
6131
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006132 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006133 return status;
6134}
6135
Andy Hung2ddee192015-12-18 17:34:44 -08006136status_t AudioPolicyManager::setMasterMono(bool mono)
6137{
6138 if (mMasterMono == mono) {
6139 return NO_ERROR;
6140 }
6141 mMasterMono = mono;
6142 // if enabling mono we close all offloaded devices, which will invalidate the
6143 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6144 // for recreating the new AudioTrack as non-offloaded PCM.
6145 //
6146 // If disabling mono, we leave all tracks as is: we don't know which clients
6147 // and tracks are able to be recreated as offloaded. The next "song" should
6148 // play back offloaded.
6149 if (mMasterMono) {
6150 Vector<audio_io_handle_t> offloaded;
6151 for (size_t i = 0; i < mOutputs.size(); ++i) {
6152 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6153 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6154 offloaded.push(desc->mIoHandle);
6155 }
6156 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006157 for (const auto& handle : offloaded) {
6158 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006159 }
6160 }
6161 // update master mono for all remaining outputs
6162 for (size_t i = 0; i < mOutputs.size(); ++i) {
6163 updateMono(mOutputs.keyAt(i));
6164 }
6165 return NO_ERROR;
6166}
6167
6168status_t AudioPolicyManager::getMasterMono(bool *mono)
6169{
6170 *mono = mMasterMono;
6171 return NO_ERROR;
6172}
6173
Eric Laurentac9cef52017-06-09 15:46:26 -07006174float AudioPolicyManager::getStreamVolumeDB(
6175 audio_stream_type_t stream, int index, audio_devices_t device)
6176{
Vlad Popa9d482762024-06-21 16:40:23 -07006177 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6178 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006179}
6180
jiabin81772902018-04-02 17:52:27 -07006181status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6182 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006183 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006184{
Kriti Dang6537def2021-03-02 13:46:59 +01006185 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6186 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006187 return BAD_VALUE;
6188 }
Kriti Dang6537def2021-03-02 13:46:59 +01006189 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6190 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006191
6192 size_t formatsWritten = 0;
6193 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006194
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006195 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006196 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6197 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006198 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006199 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006200 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006201 bool formatEnabled = true;
6202 switch (forceUse) {
6203 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006204 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006205 break;
6206 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6207 formatEnabled = false;
6208 break;
6209 default: // AUTO or ALWAYS => true
6210 break;
jiabin81772902018-04-02 17:52:27 -07006211 }
6212 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6213 }
jiabin81772902018-04-02 17:52:27 -07006214 }
6215 return NO_ERROR;
6216}
6217
Kriti Dang6537def2021-03-02 13:46:59 +01006218status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6219 audio_format_t *surroundFormats) {
6220 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6221 return BAD_VALUE;
6222 }
6223 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6224 __func__, *numSurroundFormats, surroundFormats);
6225
6226 size_t formatsWritten = 0;
6227 size_t formatsMax = *numSurroundFormats;
6228 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6229
6230 // Return formats from all device profiles that have already been resolved by
6231 // checkOutputsForDevice().
6232 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6233 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6234 audio_devices_t deviceType = device->type();
6235 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6236 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006237 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6238 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006239 continue;
6240 }
6241 // Formats reported by sink devices
6242 std::unordered_set<audio_format_t> formatset;
6243 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6244 formatset.insert(it->second.begin(), it->second.end());
6245 }
6246
6247 // Formats hard-coded in the in policy configuration file (if any).
6248 FormatVector encodedFormats = device->encodedFormats();
6249 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6250 // Filter the formats which are supported by the vendor hardware.
6251 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006252 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006253 formats.insert(*it);
6254 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006255 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006256 if (pair.second.count(*it) != 0) {
6257 formats.insert(pair.first);
6258 break;
6259 }
6260 }
6261 }
6262 }
6263 }
6264 *numSurroundFormats = formats.size();
6265 for (const auto& format: formats) {
6266 if (formatsWritten < formatsMax) {
6267 surroundFormats[formatsWritten++] = format;
6268 }
6269 }
6270 return NO_ERROR;
6271}
6272
jiabin81772902018-04-02 17:52:27 -07006273status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6274{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006275 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006276 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6277 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006278 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006279 return BAD_VALUE;
6280 }
6281
Mikhail Naganov100f0122018-11-29 11:22:16 -08006282 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6283 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006284 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006285 return INVALID_OPERATION;
6286 }
6287
Mikhail Naganov100f0122018-11-29 11:22:16 -08006288 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006289 return NO_ERROR;
6290 }
6291
Mikhail Naganov100f0122018-11-29 11:22:16 -08006292 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006293 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006294 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006295 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006296 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006297 }
6298 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006299 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006300 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006301 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006302 }
6303 }
6304
6305 sp<SwAudioOutputDescriptor> outputDesc;
6306 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006307 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6308 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006309 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6310 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006311 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006312 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006313 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006314 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6315 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006316 name.c_str(),
6317 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006318 if (status != NO_ERROR) {
6319 continue;
6320 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006321 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006322 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6323 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006324 name.c_str(),
6325 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006326 profileUpdated |= (status == NO_ERROR);
6327 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006328 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006329 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006330 AUDIO_DEVICE_IN_HDMI);
6331 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6332 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006333 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006334 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006335 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6336 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6337 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006338 name.c_str(),
6339 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006340 if (status != NO_ERROR) {
6341 continue;
6342 }
6343 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6344 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6345 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006346 name.c_str(),
6347 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006348 profileUpdated |= (status == NO_ERROR);
6349 }
6350
jiabin81772902018-04-02 17:52:27 -07006351 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006352 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006353 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006354 }
6355
6356 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6357}
6358
Eric Laurent5ada82e2019-08-29 17:53:54 -07006359void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006360{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006361 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006362 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006363 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006364 }
6365}
6366
jiabin6012f912018-11-02 17:06:30 -07006367bool AudioPolicyManager::isHapticPlaybackSupported()
6368{
6369 for (const auto& hwModule : mHwModules) {
6370 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6371 for (const auto &outProfile : outputProfiles) {
6372 struct audio_port audioPort;
6373 outProfile->toAudioPort(&audioPort);
6374 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6375 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6376 return true;
6377 }
6378 }
6379 }
6380 }
6381 return false;
6382}
6383
Carter Hsu325a8eb2022-01-19 19:56:51 +08006384bool AudioPolicyManager::isUltrasoundSupported()
6385{
6386 bool hasUltrasoundOutput = false;
6387 bool hasUltrasoundInput = false;
6388 for (const auto& hwModule : mHwModules) {
6389 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6390 if (!hasUltrasoundOutput) {
6391 for (const auto &outProfile : outputProfiles) {
6392 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6393 hasUltrasoundOutput = true;
6394 break;
6395 }
6396 }
6397 }
6398
6399 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6400 if (!hasUltrasoundInput) {
6401 for (const auto &inputProfile : inputProfiles) {
6402 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6403 hasUltrasoundInput = true;
6404 break;
6405 }
6406 }
6407 }
6408
6409 if (hasUltrasoundOutput && hasUltrasoundInput)
6410 return true;
6411 }
6412 return false;
6413}
6414
Atneya Nair698f5ef2022-12-15 16:15:09 -08006415bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6416{
6417 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6418 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6419 for (const auto& hwModule : mHwModules) {
6420 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6421 for (const auto &inputProfile : inputProfiles) {
6422 if ((inputProfile->getFlags() & mask) == mask) {
6423 return true;
6424 }
6425 }
6426 }
6427 return false;
6428}
6429
Eric Laurent8340e672019-11-06 11:01:08 -08006430bool AudioPolicyManager::isCallScreenModeSupported()
6431{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006432 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006433}
6434
6435
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006436status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006437{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006438 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006439 if (!sourceDesc->isConnected()) {
6440 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6441 return NO_ERROR;
6442 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006443 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6444 if (swOutput != 0) {
6445 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006446 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006447 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006448 }
jiabinbce0c1d2020-10-05 11:20:18 -07006449 if (releaseOutput(sourceDesc->portId())) {
6450 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6451 // no need to release audio patch here but just return NO_ERROR.
6452 return NO_ERROR;
6453 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006454 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006455 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006456 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006457 // close Hwoutput and remove from mHwOutputs
6458 } else {
6459 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6460 }
6461 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006462 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006463 sourceDesc->disconnect();
6464 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006465}
6466
François Gaffiec005e562018-11-06 15:04:49 +01006467sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6468 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006469{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006470 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006471 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006472 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006473 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006474 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6475 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006476 source = sourceDesc;
6477 break;
6478 }
6479 }
6480 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006481}
6482
Eric Laurentb4f42a92022-01-17 17:37:31 +01006483bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006484 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006485 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006486{
6487 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6488 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006489 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006490 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006491 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6492 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6493 return false;
6494 }
6495 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6496 return false;
6497 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006498 }
6499
Eric Laurentd332bc82023-08-04 11:45:23 +02006500 // The caller can have the audio config criteria ignored by either passing a null ptr or
6501 // the AUDIO_CONFIG_INITIALIZER value.
6502 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006503 // some positional channel masks and PCM format and for stereo if low latency performance
6504 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006505
6506 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006507 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006508 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6509 ? audio_channel_mask_contains_stereo(config->channel_mask)
6510 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006511 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006512 return false;
6513 }
6514 if (!audio_is_linear_pcm(config->format)) {
6515 return false;
6516 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006517 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6518 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6519 return false;
6520 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006521 }
6522
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006523 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006524 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006525 if (profile == nullptr) {
6526 return false;
6527 }
6528
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006529 return true;
6530}
6531
Shunkai Yao4c3af932024-04-26 04:12:21 +00006532// The Spatializer output is compatible with Haptic use cases if:
6533// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6534// with client if client haptic channel bits were set, or
6535// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6536// including the haptic bits or creating the HapticGenerator effect for same session.
6537bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6538 const audio_config_t* config, audio_session_t sessionId) const {
6539 const auto clientHapticChannel =
6540 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6541 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6542 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6543
6544 if (threadOutputHapticChannel) {
6545 // check format and sampleRate match if client haptic channel mask exist
6546 if (clientHapticChannel) {
6547 return mSpatializerOutput->getFormat() == config->format &&
6548 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6549 }
6550 return true;
6551 } else {
6552 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6553 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6554 // HapticGenerator effect for this session) are not supported.
6555 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006556 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006557 }
6558}
6559
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006560void AudioPolicyManager::checkVirtualizerClientRoutes() {
6561 std::set<audio_stream_type_t> streamsToInvalidate;
6562 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006563 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6564 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006565 audio_attributes_t attr = client->attributes();
6566 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6567 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6568 audio_config_base_t clientConfig = client->config();
6569 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006570 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006571 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006572 streamsToInvalidate.insert(client->stream());
6573 }
6574 }
6575 }
6576
jiabinc44b3462022-12-08 12:52:31 -08006577 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006578}
6579
Eric Laurente191d1b2022-04-15 11:59:25 +02006580
6581bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6582 const sp<SwAudioOutputDescriptor>& outputDesc) {
6583 if (outputDesc->isDuplicated()) {
6584 return false;
6585 }
6586 DeviceVector devices = outputDesc->supportedDevices();
6587 for (size_t i = 0; i < mOutputs.size(); i++) {
6588 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6589 if (desc == outputDesc || desc->isDuplicated()) {
6590 continue;
6591 }
6592 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6593 if (!sharedDevices.isEmpty()
6594 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6595 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6596 return false;
6597 }
6598 }
6599 return true;
6600}
6601
6602
Eric Laurentfa0f6742021-08-17 18:39:44 +02006603status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006604 const audio_attributes_t *attr,
6605 audio_io_handle_t *output) {
6606 *output = AUDIO_IO_HANDLE_NONE;
6607
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006608 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6609 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6610 audio_config_t *configPtr = nullptr;
6611 audio_config_t config;
6612 if (mixerConfig != nullptr) {
6613 config = audio_config_initializer(mixerConfig);
6614 configPtr = &config;
6615 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006616 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006617 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006618 return BAD_VALUE;
6619 }
6620
6621 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006622 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006623 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006624 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006625 return BAD_VALUE;
6626 }
6627
Eric Laurente191d1b2022-04-15 11:59:25 +02006628 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006629 for (size_t i = 0; i < mOutputs.size(); i++) {
6630 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006631 if (!desc->isDuplicated()
6632 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6633 spatializerOutputs.push_back(desc);
6634 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006635 }
6636 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006637 mSpatializerOutput.clear();
6638 bool outputsChanged = false;
6639 for (const auto& desc : spatializerOutputs) {
6640 if (desc->mProfile == profile
6641 && (configPtr == nullptr
6642 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6643 mSpatializerOutput = desc;
6644 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6645 } else {
6646 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6647 " and devices %s", __func__, desc->mIoHandle,
6648 configPtr != nullptr ? configPtr->channel_mask : 0,
6649 devices.toString().c_str());
6650 closeOutput(desc->mIoHandle);
6651 outputsChanged = true;
6652 }
Eric Laurent39095982021-08-24 18:29:27 +02006653 }
6654
Eric Laurente191d1b2022-04-15 11:59:25 +02006655 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006656 sp<SwAudioOutputDescriptor> desc =
6657 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006658 if (desc != nullptr) {
6659 mSpatializerOutput = desc;
6660 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006661 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006662 }
6663
6664 checkVirtualizerClientRoutes();
6665
Eric Laurente191d1b2022-04-15 11:59:25 +02006666 if (outputsChanged) {
6667 mPreviousOutputs = mOutputs;
6668 mpClientInterface->onAudioPortListUpdate();
6669 }
6670
6671 if (mSpatializerOutput == nullptr) {
6672 ALOGV("%s could not open spatializer output with requested config", __func__);
6673 return BAD_VALUE;
6674 }
Eric Laurent39095982021-08-24 18:29:27 +02006675 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006676 ALOGV("%s returning new spatializer output %d", __func__, *output);
6677 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006678}
6679
Eric Laurentfa0f6742021-08-17 18:39:44 +02006680status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6681 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006682 return INVALID_OPERATION;
6683 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006684 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006685 return BAD_VALUE;
6686 }
Eric Laurent39095982021-08-24 18:29:27 +02006687
Eric Laurente191d1b2022-04-15 11:59:25 +02006688 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6689 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6690 closeOutput(mSpatializerOutput->mIoHandle);
6691 //from now on mSpatializerOutput is null
6692 checkVirtualizerClientRoutes();
6693 }
Eric Laurent39095982021-08-24 18:29:27 +02006694
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006695 return NO_ERROR;
6696}
6697
Eric Laurente552edb2014-03-10 17:42:56 -07006698// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006699// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006700// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006701uint32_t AudioPolicyManager::nextAudioPortGeneration()
6702{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006703 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006704}
6705
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006706AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006707 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006708 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006709 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006710 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006711 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006712 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006713 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006714 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006715 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006716 mAudioPortGeneration(1),
6717 mBeaconMuteRefCount(0),
6718 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006719 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006720 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006721 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006722 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006723{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006724}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006725
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006726status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006727 if (mEngine == nullptr) {
6728 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006729 }
6730 mEngine->setObserver(this);
6731 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006732 if (status != NO_ERROR) {
6733 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6734 return status;
6735 }
François Gaffie2110e042015-03-24 08:41:51 +01006736
jiabin29230182023-04-04 21:02:36 +00006737 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6738 // at the end of this function.
6739 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006740 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6741 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6742
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006743 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006744 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006745 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006746
Eric Laurent3a4311c2014-03-17 12:00:47 -07006747 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006748 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6749 defaultOutputDevice == nullptr ||
6750 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6751 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6752 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006753 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006754 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006755 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006756
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006757 // Silence ALOGV statements
6758 property_set("log.tag." LOG_TAG, "D");
6759
Eric Laurente552edb2014-03-10 17:42:56 -07006760 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006761 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006762}
6763
Eric Laurente0720872014-03-11 09:30:41 -07006764AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006765{
Eric Laurente552edb2014-03-10 17:42:56 -07006766 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006767 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006768 }
6769 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006770 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006771 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006772 mAvailableOutputDevices.clear();
6773 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006774 mOutputs.clear();
6775 mInputs.clear();
6776 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006777 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006778 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006779}
6780
Eric Laurente0720872014-03-11 09:30:41 -07006781status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006782{
Eric Laurent87ffa392015-05-22 10:32:38 -07006783 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006784}
6785
Eric Laurente552edb2014-03-10 17:42:56 -07006786// ---
6787
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006788void AudioPolicyManager::onNewAudioModulesAvailable()
6789{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006790 DeviceVector newDevices;
6791 onNewAudioModulesAvailableInt(&newDevices);
6792 if (!newDevices.empty()) {
6793 nextAudioPortGeneration();
6794 mpClientInterface->onAudioPortListUpdate();
6795 }
6796}
6797
6798void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6799{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006800 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006801 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6802 continue;
6803 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006804 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006805 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6806 handle != AUDIO_MODULE_HANDLE_NONE) {
6807 hwModule->setHandle(handle);
6808 } else {
6809 ALOGW("could not load HW module %s", hwModule->getName());
6810 continue;
6811 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006812 }
6813 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006814 // open all output streams needed to access attached devices.
6815 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006816 // This also validates mAvailableOutputDevices list
6817 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6818 if (!outProfile->canOpenNewIo()) {
6819 ALOGE("Invalid Output profile max open count %u for profile %s",
6820 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6821 continue;
6822 }
6823 if (!outProfile->hasSupportedDevices()) {
6824 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6825 continue;
6826 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006827 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6828 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006829 mTtsOutputAvailable = true;
6830 }
6831
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006832 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006833 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006834 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006835 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6836 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006837 } else {
6838 // choose first device present in profile's SupportedDevices also part of
6839 // mAvailableOutputDevices.
6840 if (availProfileDevices.isEmpty()) {
6841 continue;
6842 }
6843 supportedDevice = availProfileDevices.itemAt(0);
6844 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006845 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006846 continue;
6847 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306848
6849 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6850 && availProfileDevices.areAllDevicesAttached()) {
6851 ALOGV("%s skip opening output for mmap profile %s", __func__,
6852 outProfile->getTagName().c_str());
6853 continue;
6854 }
6855
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006856 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6857 mpClientInterface);
6858 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006859 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006860 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006861 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6862 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006863 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006864 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006865 if (status != NO_ERROR) {
6866 ALOGW("Cannot open output stream for devices %s on hw module %s",
6867 supportedDevice->toString().c_str(), hwModule->getName());
6868 continue;
6869 }
6870 for (const auto &device : availProfileDevices) {
6871 // give a valid ID to an attached device once confirmed it is reachable
6872 if (!device->isAttached()) {
6873 device->attach(hwModule);
6874 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006875 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006876 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006877 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6878 }
6879 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006880 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006881 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6882 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006883 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006884 }
Eric Laurent39095982021-08-24 18:29:27 +02006885 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006886 outputDesc->close();
6887 } else {
6888 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306889 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006890 DeviceVector(supportedDevice),
6891 true,
6892 0,
6893 NULL);
6894 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006895 }
6896 // open input streams needed to access attached devices to validate
6897 // mAvailableInputDevices list
6898 for (const auto& inProfile : hwModule->getInputProfiles()) {
6899 if (!inProfile->canOpenNewIo()) {
6900 ALOGE("Invalid Input profile max open count %u for profile %s",
6901 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6902 continue;
6903 }
6904 if (!inProfile->hasSupportedDevices()) {
6905 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6906 continue;
6907 }
6908 // chose first device present in profile's SupportedDevices also part of
6909 // available input devices
6910 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006911 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006912 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006913 ALOGV("%s: Input device list is empty! for profile %s",
6914 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006915 continue;
6916 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306917
6918 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6919 && availProfileDevices.areAllDevicesAttached()) {
6920 ALOGV("%s skip opening input for mmap profile %s", __func__,
6921 inProfile->getTagName().c_str());
6922 continue;
6923 }
6924
Eric Laurentc71b11b2024-06-03 12:54:53 +00006925 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6926 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006927
6928 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6929 status_t status = inputDesc->open(nullptr,
6930 availProfileDevices.itemAt(0),
6931 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306932 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006933 &input);
6934 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306935 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6936 __func__, availProfileDevices.toString().c_str(),
6937 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006938 continue;
6939 }
6940 for (const auto &device : availProfileDevices) {
6941 // give a valid ID to an attached device once confirmed it is reachable
6942 if (!device->isAttached()) {
6943 device->attach(hwModule);
6944 device->importAudioPortAndPickAudioProfile(inProfile, true);
6945 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006946 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006947 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6948 }
6949 }
6950 inputDesc->close();
6951 }
6952 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006953
6954 // Check if spatializer outputs can be closed until used.
6955 // mOutputs vector never contains duplicated outputs at this point.
6956 std::vector<audio_io_handle_t> outputsClosed;
6957 for (size_t i = 0; i < mOutputs.size(); i++) {
6958 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6959 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6960 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6961 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006962 nextAudioPortGeneration();
6963 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6964 if (index >= 0) {
6965 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6966 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6967 patchDesc->getAfHandle(), 0);
6968 mAudioPatches.removeItemsAt(index);
6969 mpClientInterface->onAudioPatchListUpdate();
6970 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006971 desc->close();
6972 }
6973 }
6974 for (auto output : outputsClosed) {
6975 removeOutput(output);
6976 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006977}
6978
Eric Laurent98e38192018-02-15 18:31:53 -08006979void AudioPolicyManager::addOutput(audio_io_handle_t output,
6980 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006981{
Eric Laurent1c333e22014-05-20 10:48:17 -07006982 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006983 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006984 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006985 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006986 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006987}
6988
François Gaffie53615e22015-03-19 09:24:12 +01006989void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6990{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006991 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6992 ALOGV("%s: removing primary output", __func__);
6993 mPrimaryOutput = nullptr;
6994 }
François Gaffie53615e22015-03-19 09:24:12 +01006995 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006996 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006997}
6998
Eric Laurent98e38192018-02-15 18:31:53 -08006999void AudioPolicyManager::addInput(audio_io_handle_t input,
7000 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07007001{
Eric Laurent1c333e22014-05-20 10:48:17 -07007002 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07007003 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07007004}
Eric Laurente552edb2014-03-10 17:42:56 -07007005
François Gaffie11d30102018-11-02 16:09:09 +01007006status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01007007 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01007008 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007009{
François Gaffie11d30102018-11-02 16:09:09 +01007010 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07007011 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07007012 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07007013
François Gaffie11d30102018-11-02 16:09:09 +01007014 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007015 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007016 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007017 }
Eric Laurente552edb2014-03-10 17:42:56 -07007018
Eric Laurent3b73df72014-03-11 09:06:29 -07007019 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07007020 // first call getAudioPort to get the supported attributes from the HAL
7021 struct audio_port_v7 port = {};
7022 device->toAudioPort(&port);
7023 status_t status = mpClientInterface->getAudioPort(&port);
7024 if (status == NO_ERROR) {
7025 device->importAudioPort(port);
7026 }
7027
7028 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07007029 for (size_t i = 0; i < mOutputs.size(); i++) {
7030 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007031 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07007032 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01007033 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
7034 mOutputs.keyAt(i), device->toString().c_str());
7035 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007036 }
7037 }
7038 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007039 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007040 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007041 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7042 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007043 if (profile->supportsDevice(device)) {
7044 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307045 ALOGV("%s(): adding profile %s from module %s",
7046 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007047 }
7048 }
7049 }
7050
Eric Laurent7b279bb2015-12-14 10:18:23 -08007051 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007052
Eric Laurente552edb2014-03-10 17:42:56 -07007053 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007054 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007055 return BAD_VALUE;
7056 }
7057
7058 // open outputs for matching profiles if needed. Direct outputs are also opened to
7059 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7060 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007061 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007062
7063 // nothing to do if one output is already opened for this profile
7064 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007065 for (j = 0; j < outputs.size(); j++) {
7066 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007067 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007068 // matching profile: save the sample rates, format and channel masks supported
7069 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007070 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007071 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007072 }
Eric Laurente552edb2014-03-10 17:42:56 -07007073 break;
7074 }
7075 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007076 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007077 continue;
7078 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307079 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7080 ALOGV("%s skip opening output for mmap profile %s",
7081 __func__, profile->getTagName().c_str());
7082 continue;
7083 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007084 if (!profile->canOpenNewIo()) {
7085 ALOGW("Max Output number %u already opened for this profile %s",
7086 profile->maxOpenCount, profile->getTagName().c_str());
7087 continue;
7088 }
7089
Eric Laurent83efe1c2017-07-09 16:51:08 -07007090 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007091 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007092 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7093 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007094 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007095 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007096 profiles.removeAt(profile_index);
7097 profile_index--;
7098 } else {
7099 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007100 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007101 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007102 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7103 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007104 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007105 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007106
François Gaffie11d30102018-11-02 16:09:09 +01007107 if (device_distinguishes_on_address(deviceType)) {
7108 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7109 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307110 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7111 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007112 }
Eric Laurente552edb2014-03-10 17:42:56 -07007113 ALOGV("checkOutputsForDevice(): adding output %d", output);
7114 }
7115 }
7116
7117 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007118 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007119 return BAD_VALUE;
7120 }
Eric Laurentd4692962014-05-05 18:13:44 -07007121 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007122 // check if one opened output is not needed any more after disconnecting one device
7123 for (size_t i = 0; i < mOutputs.size(); i++) {
7124 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007125 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007126 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007127 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007128 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007129 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007130 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007131 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7132 mOutputs.keyAt(i));
7133 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007134 }
Eric Laurente552edb2014-03-10 17:42:56 -07007135 }
7136 }
Eric Laurentd4692962014-05-05 18:13:44 -07007137 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007138 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007139 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7140 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007141 if (!profile->supportsDevice(device)) {
7142 continue;
7143 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307144 ALOGV("%s(): clearing direct output profile %s on module %s",
7145 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007146 profile->clearAudioProfiles();
7147 if (!profile->hasDynamicAudioProfile()) {
7148 continue;
7149 }
7150 // When a device is disconnected, if there is an IOProfile that contains dynamic
7151 // profiles and supports the disconnected device, call getAudioPort to repopulate
7152 // the capabilities of the devices that is supported by the IOProfile.
7153 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7154 if (supportedDevice == device ||
7155 !mAvailableOutputDevices.contains(supportedDevice)) {
7156 continue;
7157 }
7158 struct audio_port_v7 port;
7159 supportedDevice->toAudioPort(&port);
7160 status_t status = mpClientInterface->getAudioPort(&port);
7161 if (status == NO_ERROR) {
7162 supportedDevice->importAudioPort(port);
7163 }
Eric Laurente552edb2014-03-10 17:42:56 -07007164 }
7165 }
7166 }
7167 }
7168 return NO_ERROR;
7169}
7170
François Gaffie11d30102018-11-02 16:09:09 +01007171status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007172 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007173{
François Gaffie11d30102018-11-02 16:09:09 +01007174 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007175 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007176 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007177 }
7178
Eric Laurentd4692962014-05-05 18:13:44 -07007179 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007180 sp<AudioInputDescriptor> desc;
7181
jiabinbf5f4262023-04-12 21:48:34 +00007182 // first call getAudioPort to get the supported attributes from the HAL
7183 struct audio_port_v7 port = {};
7184 device->toAudioPort(&port);
7185 status_t status = mpClientInterface->getAudioPort(&port);
7186 if (status == NO_ERROR) {
7187 device->importAudioPort(port);
7188 }
7189
Eric Laurent0dd51852019-04-19 18:18:58 -07007190 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007191 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007192 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007193 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007194 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007195 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007196 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007197
François Gaffie11d30102018-11-02 16:09:09 +01007198 if (profile->supportsDevice(device)) {
7199 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307200 ALOGV("%s : adding profile %s from module %s", __func__,
7201 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007202 }
7203 }
7204 }
7205
Eric Laurent0dd51852019-04-19 18:18:58 -07007206 if (profiles.isEmpty()) {
7207 ALOGW("%s: No input profile available for device %s",
7208 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007209 return BAD_VALUE;
7210 }
7211
7212 // open inputs for matching profiles if needed. Direct inputs are also opened to
7213 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7214 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7215
Eric Laurent1c333e22014-05-20 10:48:17 -07007216 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007217
Eric Laurentd4692962014-05-05 18:13:44 -07007218 // nothing to do if one input is already opened for this profile
7219 size_t input_index;
7220 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7221 desc = mInputs.valueAt(input_index);
7222 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007223 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007224 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007225 }
Eric Laurentd4692962014-05-05 18:13:44 -07007226 break;
7227 }
7228 }
7229 if (input_index != mInputs.size()) {
7230 continue;
7231 }
7232
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307233 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7234 ALOGV("%s skip opening input for mmap profile %s",
7235 __func__, profile->getTagName().c_str());
7236 continue;
7237 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007238 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307239 ALOGW("%s Max Input number %u already opened for this profile %s",
7240 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007241 continue;
7242 }
7243
Eric Laurentc71b11b2024-06-03 12:54:53 +00007244 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007245 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307246 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307247 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7248 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007249
Eric Laurentcf2c0212014-07-25 16:20:43 -07007250 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007251 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007252 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007253 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007254 mpClientInterface->setParameters(input, String8(param));
7255 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007256 }
jiabin12537fc2023-10-12 17:56:08 +00007257 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007258 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307259 ALOGW("%s direct input missing param for profile %s", __func__,
7260 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007261 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007262 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007263 }
7264
Eric Laurent0dd51852019-04-19 18:18:58 -07007265 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007266 addInput(input, desc);
7267 }
7268 } // endif input != 0
7269
Eric Laurentcf2c0212014-07-25 16:20:43 -07007270 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307271 ALOGW("%s could not open input for device %s on profile %s", __func__,
7272 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007273 profiles.removeAt(profile_index);
7274 profile_index--;
7275 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007276 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007277 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007278 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307279 ALOGV("%s: adding input %d for profile %s", __func__,
7280 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007281
7282 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307283 ALOGV("%s: closing input %d for profile %s", __func__,
7284 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007285 closeInput(input);
7286 }
Eric Laurentd4692962014-05-05 18:13:44 -07007287 }
7288 } // end scan profiles
7289
7290 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007291 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007292 return BAD_VALUE;
7293 }
7294 } else {
7295 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007296 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007297 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007298 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007299 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007300 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007301 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007302 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307303 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7304 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007305 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007306 }
7307 }
7308 }
7309 } // end disconnect
7310
7311 return NO_ERROR;
7312}
7313
7314
Eric Laurente0720872014-03-11 09:30:41 -07007315void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007316{
7317 ALOGV("closeOutput(%d)", output);
7318
François Gaffie1c878552018-11-22 16:53:21 +01007319 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7320 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007321 ALOGW("closeOutput() unknown output %d", output);
7322 return;
7323 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007324 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007325 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007326
Eric Laurente552edb2014-03-10 17:42:56 -07007327 // look for duplicated outputs connected to the output being removed.
7328 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007329 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7330 if (dupOutput->isDuplicated() &&
7331 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7332 sp<SwAudioOutputDescriptor> remainingOutput =
7333 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007334 // As all active tracks on duplicated output will be deleted,
7335 // and as they were also referenced on the other output, the reference
7336 // count for their stream type must be adjusted accordingly on
7337 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007338 const bool wasActive = remainingOutput->isActive();
7339 // Note: no-op on the closing output where all clients has already been set inactive
7340 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007341 // stop() will be a no op if the output is still active but is needed in case all
7342 // active streams refcounts where cleared above
7343 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007344 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007345 }
Eric Laurente552edb2014-03-10 17:42:56 -07007346 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7347 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7348
7349 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007350 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007351 }
7352 }
7353
Eric Laurent05b90f82014-08-27 15:32:29 -07007354 nextAudioPortGeneration();
7355
François Gaffie1c878552018-11-22 16:53:21 +01007356 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007357 if (index >= 0) {
7358 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007359 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7360 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007361 mAudioPatches.removeItemsAt(index);
7362 mpClientInterface->onAudioPatchListUpdate();
7363 }
7364
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007365 if (closingOutputWasActive) {
7366 closingOutput->stop();
7367 }
François Gaffie1c878552018-11-22 16:53:21 +01007368 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007369 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007370 for (const auto device : closingOutput->devices()) {
7371 device->setPreferredConfig(nullptr);
7372 }
7373 }
Eric Laurente552edb2014-03-10 17:42:56 -07007374
François Gaffie53615e22015-03-19 09:24:12 +01007375 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007376 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007377 if (closingOutput == mSpatializerOutput) {
7378 mSpatializerOutput.clear();
7379 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007380
7381 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7382 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007383 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007384 bool directOutputOpen = false;
7385 for (size_t i = 0; i < mOutputs.size(); i++) {
7386 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7387 directOutputOpen = true;
7388 break;
7389 }
7390 }
7391 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007392 ALOGV("no direct outputs open, reset MSD patches");
7393 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7394 // how output devices for patching are resolved. Avoid by caching and reusing the
7395 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7396 // devices to patch to. This may be complicated by the fact that devices may become
7397 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007398 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007399 }
7400 }
jiabin220eea12024-05-17 17:55:20 +00007401
7402 if (closingOutput->mPreferredAttrInfo != nullptr) {
7403 closingOutput->mPreferredAttrInfo->resetActiveClient();
7404 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007405}
7406
7407void AudioPolicyManager::closeInput(audio_io_handle_t input)
7408{
7409 ALOGV("closeInput(%d)", input);
7410
7411 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7412 if (inputDesc == NULL) {
7413 ALOGW("closeInput() unknown input %d", input);
7414 return;
7415 }
7416
Eric Laurent6a94d692014-05-20 11:18:06 -07007417 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007418
François Gaffie11d30102018-11-02 16:09:09 +01007419 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007420 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007421 if (index >= 0) {
7422 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007423 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7424 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007425 mAudioPatches.removeItemsAt(index);
7426 mpClientInterface->onAudioPatchListUpdate();
7427 }
7428
François Gaffie6ebbce02023-07-19 13:27:53 +02007429 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007430 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007431 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007432
François Gaffie11d30102018-11-02 16:09:09 +01007433 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7434 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007435 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007436 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007437 }
Eric Laurente552edb2014-03-10 17:42:56 -07007438}
7439
François Gaffie11d30102018-11-02 16:09:09 +01007440SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7441 const DeviceVector &devices,
7442 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007443{
7444 SortedVector<audio_io_handle_t> outputs;
7445
François Gaffie11d30102018-11-02 16:09:09 +01007446 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007447 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007448 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007449 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007450 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007451 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007452 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007453 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007454 outputs.add(openOutputs.keyAt(i));
7455 }
7456 }
7457 return outputs;
7458}
7459
Mikhail Naganov37977152018-07-11 15:54:44 -07007460void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7461{
7462 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7463 // output is suspended before any tracks are moved to it
7464 checkA2dpSuspend();
7465 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007466 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007467 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007468 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007469 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007470 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7471 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7472 // configuration changes will ultimately be rerouted correctly. We can still avoid
7473 // unnecessary rerouting by caching and reusing the arguments to
7474 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7475 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007476 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007477 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007478 // an event that changed routing likely occurred, inform upper layers
7479 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007480}
7481
François Gaffiec005e562018-11-06 15:04:49 +01007482bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7483 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007484{
François Gaffiec005e562018-11-06 15:04:49 +01007485 return mEngine->getProductStrategyForAttributes(lAttr) ==
7486 mEngine->getProductStrategyForAttributes(rAttr);
7487}
7488
Francois Gaffieff1eb522020-05-06 18:37:04 +02007489void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7490{
7491 for (size_t i = 0; i < mAudioSources.size(); i++) {
7492 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7493 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007494 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007495 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007496 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007497 }
7498 }
7499}
7500
7501void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7502{
7503 for (size_t i = 0; i < mAudioSources.size(); i++) {
7504 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7505 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7506 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7507 disconnectAudioSource(sourceDesc);
7508 }
7509 }
7510}
7511
François Gaffiec005e562018-11-06 15:04:49 +01007512void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7513{
7514 auto psId = mEngine->getProductStrategyForAttributes(attr);
7515
7516 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7517 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007518
François Gaffie11d30102018-11-02 16:09:09 +01007519 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7520 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007521
Eric Laurentc209fe42020-06-05 18:11:23 -07007522 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007523 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007524 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007525 // take into account dynamic audio policies related changes: if a client is now associated
7526 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007527 // invalidate clients on outputs that do not support all the newly selected devices for the
7528 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007529 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007530 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007531 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007532 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007533 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007534
Eric Laurentc209fe42020-06-05 18:11:23 -07007535 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7536 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7537 continue;
7538 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007539 if (!desc->supportsAllDevices(newDevices)) {
7540 invalidatedOutputs.push_back(desc);
7541 break;
7542 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007543 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007544 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007545 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7546 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7547 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007548 if (status == OK) {
7549 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7550 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7551 maxLatency = desc->latency();
7552 }
7553 invalidatedOutputs.push_back(desc);
7554 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007555 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007556 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007557 }
7558 }
7559
Eric Laurent56ed8842022-11-15 16:04:41 +01007560 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007561 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7562 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007563 for (audio_io_handle_t srcOut : srcOutputs) {
7564 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007565 if (desc == nullptr) continue;
7566
7567 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007568 maxLatency = desc->latency();
7569 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007570
Eric Laurent56ed8842022-11-15 16:04:41 +01007571 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007572 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007573 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007574 // a client on a non direct outputs has necessarily a linear PCM format
7575 // so we can call selectOutput() safely
7576 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7577 client->flags(),
7578 client->config().format,
7579 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007580 client->config().sample_rate,
7581 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007582 if (newOutput != srcOut) {
7583 invalidate = true;
7584 break;
7585 }
7586 } else {
7587 sp<IOProfile> profile = getProfileForOutput(newDevices,
7588 client->config().sample_rate,
7589 client->config().format,
7590 client->config().channel_mask,
7591 client->flags(),
7592 true /* directOnly */);
7593 if (profile != desc->mProfile) {
7594 invalidate = true;
7595 break;
7596 }
7597 }
7598 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007599 // mute strategy while moving tracks from one output to another
7600 if (invalidate) {
7601 invalidatedOutputs.push_back(desc);
7602 if (desc->isStrategyActive(psId)) {
7603 setStrategyMute(psId, true, desc);
7604 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7605 newDevices.types());
7606 }
Eric Laurente552edb2014-03-10 17:42:56 -07007607 }
François Gaffiec005e562018-11-06 15:04:49 +01007608 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007609 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007610 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007611 }
Eric Laurente552edb2014-03-10 17:42:56 -07007612 }
7613
Eric Laurent56ed8842022-11-15 16:04:41 +01007614 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7615 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7616 std::to_string(srcOutputs[0]).c_str(),
7617 std::to_string(dstOutputs[0]).c_str());
7618
François Gaffiec005e562018-11-06 15:04:49 +01007619 // Move effects associated to this stream from previous output to new output
7620 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007621 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007622 }
François Gaffiec005e562018-11-06 15:04:49 +01007623 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007624 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007625 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007626 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007627 desc->setTracksInvalidatedStatusByStrategy(psId);
7628 }
Eric Laurente552edb2014-03-10 17:42:56 -07007629 }
7630 }
7631}
7632
Eric Laurente0720872014-03-11 09:30:41 -07007633void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007634{
François Gaffiec005e562018-11-06 15:04:49 +01007635 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7636 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7637 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007638 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007639 }
Eric Laurente552edb2014-03-10 17:42:56 -07007640}
7641
Kevin Rocard153f92d2018-12-18 18:33:28 -08007642void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007643 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007644 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007645 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007646 for (size_t i = 0; i < mOutputs.size(); i++) {
7647 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7648 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007649 sp<AudioPolicyMix> primaryMix;
7650 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007651 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007652 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7653 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7654 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007655 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7656 for (auto &secondaryMix : secondaryMixes) {
7657 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7658 if (outputDesc != nullptr &&
jiabin6838cda2024-11-22 21:54:30 +00007659 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE &&
7660 outputDesc != outputDescriptor) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007661 secondaryDescs.push_back(outputDesc);
7662 }
7663 }
7664
jiabinc44b3462022-12-08 12:52:31 -08007665 if (status != OK &&
7666 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7667 // When it failed to query secondary output, only invalidate the client that is not
7668 // MMAP. The reason is that MMAP stream will not support secondary output.
7669 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007670 } else if (!std::equal(
7671 client->getSecondaryOutputs().begin(),
7672 client->getSecondaryOutputs().end(),
7673 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007674 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7675 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007676 // If the format is not PCM, the tracks should be invalidated to get correct
7677 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007678 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007679 } else {
7680 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7681 std::vector<audio_io_handle_t> secondaryOutputIds;
7682 for (const auto &secondaryDesc: secondaryDescs) {
7683 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7684 weakSecondaryDescs.push_back(secondaryDesc);
7685 }
7686 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7687 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007688 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007689 }
7690 }
7691 }
jiabin10a03f12021-05-07 23:46:28 +00007692 if (!trackSecondaryOutputs.empty()) {
7693 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7694 }
jiabinc44b3462022-12-08 12:52:31 -08007695 if (!clientsToInvalidate.empty()) {
7696 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7697 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007698 }
7699}
7700
Eric Laurent2517af32020-11-25 15:31:27 +01007701bool AudioPolicyManager::isScoRequestedForComm() const {
7702 AudioDeviceTypeAddrVector devices;
7703 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7704 for (const auto &device : devices) {
7705 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7706 return true;
7707 }
7708 }
7709 return false;
7710}
7711
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007712bool AudioPolicyManager::isHearingAidUsedForComm() const {
7713 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7714 true /*fromCache*/);
7715 for (const auto &device : devices) {
7716 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7717 return true;
7718 }
7719 }
7720 return false;
7721}
7722
7723
Eric Laurente0720872014-03-11 09:30:41 -07007724void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007725{
François Gaffie53615e22015-03-19 09:24:12 +01007726 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007727 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007728 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007729 return;
7730 }
7731
Eric Laurent3a4311c2014-03-17 12:00:47 -07007732 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007733 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7734 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007735 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007736
7737 // if suspended, restore A2DP output if:
7738 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007739 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007740 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007741 //
Eric Laurentf732e072016-08-03 19:30:28 -07007742 // if not suspended, suspend A2DP output if:
7743 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007744 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007745 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007746 //
7747 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007748 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007749 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007750 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007751 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007752
7753 mpClientInterface->restoreOutput(a2dpOutput);
7754 mA2dpSuspended = false;
7755 }
7756 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007757 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007758 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007759 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007760 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007761
7762 mpClientInterface->suspendOutput(a2dpOutput);
7763 mA2dpSuspended = true;
7764 }
7765 }
7766}
7767
François Gaffie11d30102018-11-02 16:09:09 +01007768DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7769 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007770{
François Gaffiedb1755b2023-09-01 11:50:35 +02007771 if (outputDesc == nullptr) {
7772 return DeviceVector{};
7773 }
François Gaffie11d30102018-11-02 16:09:09 +01007774
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007775 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007776 if (index >= 0) {
7777 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007778 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007779 ALOGV("%s device %s forced by patch %d", __func__,
7780 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7781 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007782 }
7783 }
7784
Dean Wheatley514b4312020-06-17 21:45:00 +10007785 // Do not retrieve engine device for outputs through MSD
7786 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7787 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7788 return outputDesc->devices();
7789 }
7790
Eric Laurent97ac8712018-07-27 18:59:02 -07007791 // Honor explicit routing requests only if no client using default routing is active on this
7792 // input: a specific app can not force routing for other apps by setting a preferred device.
7793 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007794 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007795 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007796 if (device != nullptr) {
7797 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007798 }
7799
François Gaffiea807ef92018-11-05 10:44:33 +01007800 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7801 // of setForceUse / Default Bus device here
7802 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7803 if (device != nullptr) {
7804 return DeviceVector(device);
7805 }
7806
François Gaffiedb1755b2023-09-01 11:50:35 +02007807 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007808 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7809 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307810 auto hasStreamActive = [&](auto stream) {
7811 return hasStream(streams, stream) && isStreamActive(stream, 0);
7812 };
Eric Laurent484e9272018-06-07 17:29:23 -07007813
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307814 auto doGetOutputDevicesForVoice = [&]() {
7815 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007816 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307817 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007818 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7819 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307820 };
7821
7822 // With low-latency playing on speaker, music on WFD, when the first low-latency
7823 // output is stopped, getNewOutputDevices checks for a product strategy
7824 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007825 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307826 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7827 // stream is associated to the output descriptor.
7828 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7829 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7830 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7831 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007832 // Retrieval of devices for voice DL is done on primary output profile, cannot
7833 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007834 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007835 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7836 break;
7837 }
Eric Laurente552edb2014-03-10 17:42:56 -07007838 }
François Gaffiec005e562018-11-06 15:04:49 +01007839 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007840 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007841}
7842
François Gaffie11d30102018-11-02 16:09:09 +01007843sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7844 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007845{
François Gaffie11d30102018-11-02 16:09:09 +01007846 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007847
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007848 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007849 if (index >= 0) {
7850 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007851 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007852 ALOGV("getNewInputDevice() device %s forced by patch %d",
7853 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7854 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007855 }
7856 }
7857
Eric Laurent97ac8712018-07-27 18:59:02 -07007858 // Honor explicit routing requests only if no client using default routing is active on this
Eric Laurentd8add2b2024-11-15 16:05:32 +00007859 // input or if all active clients are from the same app: a specific app can not force routing
7860 // for other apps by setting a preferred device.
Eric Laurent97ac8712018-07-27 18:59:02 -07007861 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007862 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7863 if (device != nullptr) {
7864 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007865 }
7866
Eric Laurentdc95a252018-04-12 12:46:56 -07007867 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007868 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007869 audio_attributes_t attributes;
7870 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007871 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007872 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7873 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007874 attributes = topClient->attributes();
7875 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007876 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007877 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007878 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7879 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007880 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007881 }
7882
Francois Gaffie716e1432019-01-14 16:58:59 +01007883 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7884 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007885 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007886 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007887 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007888 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007889
Eric Laurente552edb2014-03-10 17:42:56 -07007890 return device;
7891}
7892
Eric Laurent794fde22016-03-11 09:50:45 -08007893bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7894 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007895 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007896}
7897
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007898status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007899 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007900 if (devices == nullptr) {
7901 return BAD_VALUE;
7902 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007903
Andy Hung6d23c0f2022-02-16 09:37:15 -08007904 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007905 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7906 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007907 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007908 for (const auto& device : curDevices) {
7909 devices->push_back(device->getDeviceTypeAddr());
7910 }
7911 return NO_ERROR;
7912}
7913
Eric Laurente0720872014-03-11 09:30:41 -07007914void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007915 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007916 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007917 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007918 updateDevicesAndOutputs();
7919 break;
7920 default:
7921 break;
7922 }
7923}
7924
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007925uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007926
7927 // skip beacon mute management if a dedicated TTS output is available
7928 if (mTtsOutputAvailable) {
7929 return 0;
7930 }
7931
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007932 switch(event) {
7933 case STARTING_OUTPUT:
7934 mBeaconMuteRefCount++;
7935 break;
7936 case STOPPING_OUTPUT:
7937 if (mBeaconMuteRefCount > 0) {
7938 mBeaconMuteRefCount--;
7939 }
7940 break;
7941 case STARTING_BEACON:
7942 mBeaconPlayingRefCount++;
7943 break;
7944 case STOPPING_BEACON:
7945 if (mBeaconPlayingRefCount > 0) {
7946 mBeaconPlayingRefCount--;
7947 }
7948 break;
7949 }
7950
7951 if (mBeaconMuteRefCount > 0) {
7952 // any playback causes beacon to be muted
7953 return setBeaconMute(true);
7954 } else {
7955 // no other playback: unmute when beacon starts playing, mute when it stops
7956 return setBeaconMute(mBeaconPlayingRefCount == 0);
7957 }
7958}
7959
7960uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7961 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7962 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7963 // keep track of muted state to avoid repeating mute/unmute operations
7964 if (mBeaconMuted != mute) {
7965 // mute/unmute AUDIO_STREAM_TTS on all outputs
7966 ALOGV("\t muting %d", mute);
7967 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007968 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7969 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7970 ALOGV("\t no tts volume source available");
7971 return 0;
7972 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007973 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007974 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007975 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7976 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007977 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007978 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007979 maxLatency = latency;
7980 }
7981 }
7982 mBeaconMuted = mute;
7983 return maxLatency;
7984 }
7985 return 0;
7986}
7987
Eric Laurente0720872014-03-11 09:30:41 -07007988void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007989{
François Gaffiec005e562018-11-06 15:04:49 +01007990 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007991 mPreviousOutputs = mOutputs;
7992}
7993
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007994uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007995 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007996 uint32_t delayMs)
7997{
7998 // mute/unmute strategies using an incompatible device combination
7999 // if muting, wait for the audio in pcm buffer to be drained before proceeding
8000 // if unmuting, unmute only after the specified delay
8001 if (outputDesc->isDuplicated()) {
8002 return 0;
8003 }
8004
8005 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01008006 DeviceVector devices = outputDesc->devices();
8007 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07008008
François Gaffiec005e562018-11-06 15:04:49 +01008009 auto productStrategies = mEngine->getOrderedProductStrategies();
8010 for (const auto &productStrategy : productStrategies) {
8011 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
8012 DeviceVector curDevices =
8013 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
8014 curDevices = curDevices.filter(outputDesc->supportedDevices());
8015 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07008016 bool doMute = false;
8017
François Gaffiec005e562018-11-06 15:04:49 +01008018 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07008019 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01008020 outputDesc->setStrategyMutedByDevice(productStrategy, true);
8021 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07008022 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01008023 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07008024 }
Eric Laurent99401132014-05-07 19:48:15 -07008025 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07008026 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07008027 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07008028 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01008029 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07008030 continue;
8031 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308032 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01008033 mute ? "muting" : "unmuting", curDevices.toString().c_str());
8034 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
8035 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07008036 if (mute) {
8037 // FIXME: should not need to double latency if volume could be applied
8038 // immediately by the audioflinger mixer. We must account for the delay
8039 // between now and the next time the audioflinger thread for this output
8040 // will process a buffer (which corresponds to one buffer size,
8041 // usually 1/2 or 1/4 of the latency).
8042 if (muteWaitMs < desc->latency() * 2) {
8043 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008044 }
8045 }
8046 }
8047 }
8048 }
8049 }
8050
Eric Laurent99401132014-05-07 19:48:15 -07008051 // temporary mute output if device selection changes to avoid volume bursts due to
8052 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008053 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008054 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008055
Eric Laurentdc462862016-07-19 12:29:53 -07008056 if (muteWaitMs < tempMuteWaitMs) {
8057 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008058 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008059
8060 // If recommended duration is defined, replace temporary mute duration to avoid
8061 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8062 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8063 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8064 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8065 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8066
François Gaffieaaac0fd2018-11-22 17:56:39 +01008067 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8068 // make sure that we do not start the temporary mute period too early in case of
8069 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008070 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8071 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8072 delayMs + tempMuteDurationMs,
8073 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008074 }
8075 }
8076
Eric Laurente552edb2014-03-10 17:42:56 -07008077 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8078 if (muteWaitMs > delayMs) {
8079 muteWaitMs -= delayMs;
8080 usleep(muteWaitMs * 1000);
8081 return muteWaitMs;
8082 }
8083 return 0;
8084}
8085
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308086uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8087 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008088 const DeviceVector &devices,
8089 bool force,
8090 int delayMs,
8091 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008092 bool requiresMuteCheck, bool requiresVolumeCheck,
8093 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008094{
jiabin3ff8d7d2022-12-13 06:27:44 +00008095 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308096 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8097 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8098 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008099 uint32_t muteWaitMs;
8100
8101 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308102 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008103 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308104 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008105 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008106 return muteWaitMs;
8107 }
Eric Laurente552edb2014-03-10 17:42:56 -07008108
8109 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008110 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008111 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008112 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008113
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308114 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8115 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008116
8117 if (!filteredDevices.isEmpty()) {
8118 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008119 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008120
8121 // if the outputs are not materially active, there is no need to mute.
8122 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008123 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008124 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308125 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8126 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008127 muteWaitMs = 0;
8128 }
Eric Laurente552edb2014-03-10 17:42:56 -07008129
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008130 bool outputRouted = outputDesc->isRouted();
8131
Eric Laurent79ea9582020-06-11 18:49:24 -07008132 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8133 // output profile or if new device is not supported AND previous device(s) is(are) still
8134 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008135 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308136 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8137 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008138 // restore previous device after evaluating strategy mute state
8139 outputDesc->setDevices(prevDevices);
8140 return muteWaitMs;
8141 }
8142
Eric Laurente552edb2014-03-10 17:42:56 -07008143 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008144 // the requested device is AUDIO_DEVICE_NONE
8145 // OR the requested device is the same as current device
8146 // AND force is not specified
8147 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008148 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008149 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308150 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8151 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8152 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008153 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308154 ALOGV("%s %s setting same device on routed output, force apply volumes",
8155 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008156 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8157 }
Eric Laurente552edb2014-03-10 17:42:56 -07008158 return muteWaitMs;
8159 }
8160
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308161 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8162 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008163
Eric Laurente552edb2014-03-10 17:42:56 -07008164 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008165 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008166 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008167 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008168 PatchBuilder patchBuilder;
8169 patchBuilder.addSource(outputDesc);
8170 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8171 for (const auto &filteredDevice : filteredDevices) {
8172 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008173 }
8174
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008175 // Add half reported latency to delayMs when muteWaitMs is null in order
8176 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008177 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8178 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8179 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008180 }
Eric Laurente552edb2014-03-10 17:42:56 -07008181
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008182 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8183 if (!skipMuteDelay) {
8184 // update stream volumes according to new device
8185 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8186 }
Eric Laurente552edb2014-03-10 17:42:56 -07008187
8188 return muteWaitMs;
8189}
8190
Eric Laurentc75307b2015-03-17 15:29:32 -07008191status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008192 int delayMs,
8193 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008194{
Eric Laurent6a94d692014-05-20 11:18:06 -07008195 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008196 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8197 return INVALID_OPERATION;
8198 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008199 if (patchHandle) {
8200 index = mAudioPatches.indexOfKey(*patchHandle);
8201 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008202 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008203 }
8204 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008205 return INVALID_OPERATION;
8206 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008207 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008208 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008209 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008210 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008211 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008212 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008213 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008214 return status;
8215}
8216
8217status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008218 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008219 bool force,
8220 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008221{
8222 status_t status = NO_ERROR;
8223
Eric Laurent1f2f2232014-06-02 12:01:23 -07008224 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008225 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8226 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008227
François Gaffie11d30102018-11-02 16:09:09 +01008228 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008229 PatchBuilder patchBuilder;
8230 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008231 // AUDIO_SOURCE_HOTWORD is for internal use only:
8232 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008233 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8234 auto result = usecase;
8235 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8236 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8237 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008238 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008239 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008240 if (audio_is_remote_submix_device(device->type())) {
8241 // remote submix HAL does not support audio conversion, need source device
8242 // audio config to match the sink input descriptor audio config, otherwise AIDL
8243 // HAL patching will fail
8244 audio_port_config srcDevicePortConfig = {};
8245 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8246 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8247 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8248 srcDevicePortConfig.format = inputDesc->getFormat();
8249 patchBuilder.addSource(srcDevicePortConfig);
8250 } else {
8251 patchBuilder.addSource(device);
8252 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008253 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008254 }
8255 }
8256 return status;
8257}
8258
Eric Laurent6a94d692014-05-20 11:18:06 -07008259status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8260 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008261{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008262 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008263 ssize_t index;
8264 if (patchHandle) {
8265 index = mAudioPatches.indexOfKey(*patchHandle);
8266 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008267 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008268 }
8269 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008270 return INVALID_OPERATION;
8271 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008272 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008273 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008274 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008275 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008276 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008277 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008278 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008279 return status;
8280}
8281
François Gaffie11d30102018-11-02 16:09:09 +01008282sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008283 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008284 audio_format_t& format,
8285 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008286 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008287{
8288 // Choose an input profile based on the requested capture parameters: select the first available
8289 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008290 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008291
Atneya Nair0f0a8032022-12-12 16:20:12 -08008292 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8293 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8294 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8295
8296 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008297
jiabin2fd710d2022-05-02 23:20:22 +00008298 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008299 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008300 uint32_t inexactSamplingRate = 0;
8301 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8302 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008303 uint32_t updatedSamplingRate = 0;
8304 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8305 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8306 for (const auto& hwModule : mHwModules) {
8307 for (const auto& profile : hwModule->getInputProfiles()) {
8308 // profile->log();
8309 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008310 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008311 DeviceVector(device),
8312 samplingRate,
8313 &updatedSamplingRate,
8314 format,
8315 &updatedFormat,
8316 channelMask,
8317 &updatedChannelMask,
8318 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008319 (audio_output_flags_t) flags);
8320 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008321 samplingRate = updatedSamplingRate;
8322 format = updatedFormat;
8323 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008324 return profile;
jiabin91beb492024-10-16 21:53:36 +00008325 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8326 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8327 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8328 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008329 inexactSamplingRate = updatedSamplingRate;
8330 inexactFormat = updatedFormat;
8331 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008332 }
8333 }
8334 }
8335
jiabin91beb492024-10-16 21:53:36 +00008336 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008337 samplingRate = inexactSamplingRate;
8338 format = inexactFormat;
8339 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008340 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008341 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8342 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8343 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8344 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8345 flags = AUDIO_INPUT_FLAG_NONE;
8346 } else { // fail
8347 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8348 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8349 samplingRate, format, channelMask, oriFlags);
8350 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008351 }
8352 }
jiabin2fd710d2022-05-02 23:20:22 +00008353
8354 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008355}
8356
Vlad Popa87e0e582024-05-20 18:49:20 -07008357float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8358 VolumeSource volumeSource,
8359 int index,
8360 const DeviceTypeSet &deviceTypes)
8361{
8362 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8363 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8364 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8365
8366 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008367 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8368 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8369 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008370 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8371 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8372 ALOGD("%s: no group matching with %s", __FUNCTION__,
8373 toString(attributesToDriveAbs).c_str());
8374 return volumeDb;
8375 }
8376
8377 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8378 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8379 if (vsToDriveAbs == volumeSource) {
8380 // attenuation is applied by the abs volume controller
Vlad Popa444e95e2024-11-07 18:26:20 -08008381 // do not mute LE broadcast to allow the secondary device to continue playing
8382 return (index != 0 || volumeDevice == AUDIO_DEVICE_OUT_BLE_BROADCAST) ? volumeDbMax
8383 : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008384 } else {
8385 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8386 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8387 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8388 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8389 curvesAbs.getVolumeIndexMax());
8390 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8391 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8392 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8393 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8394 return newVolumeDb;
8395 }
8396 }
8397 return volumeDb;
8398 } else {
8399 return volumeDb;
8400 }
8401}
8402
François Gaffieaaac0fd2018-11-22 17:56:39 +01008403float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8404 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008405 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008406 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008407 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008408 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008409{
Vlad Popa9d482762024-06-21 16:40:23 -07008410 float volumeDb;
8411 if (adjustAttenuation) {
8412 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8413 } else {
8414 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8415 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008416 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8417 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8418
8419 if (!computeInternalInteraction) {
8420 return volumeDb;
8421 }
8422
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008423 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8424 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8425 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8426 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008427 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8428 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8429 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8430 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8431 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008432 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008433 mOutputs.isActive(ringVolumeSrc, 0)) {
8434 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008435 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008436 adjustAttenuation,
8437 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008438 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008439 }
8440
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008441 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008442 if ((volumeSource != callVolumeSrc && (isInCall() ||
8443 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008444 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8446 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008447 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8448 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8449 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008450 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008451 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008452 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008453 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008454 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008455 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008456 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008457 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8458 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8459 // programmatically muted.
8460 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8461 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8462 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008463 bool exemptFromCapping =
8464 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8465 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008466 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8467 volumeSource, volumeDb);
8468 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008469 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8470 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8471 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008472 }
8473 }
Eric Laurente552edb2014-03-10 17:42:56 -07008474 // if a headset is connected, apply the following rules to ring tones and notifications
8475 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008476 // - always attenuate notifications volume by 6dB
8477 // - attenuate ring tones volume by 6dB unless music is not playing and
8478 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008479 // - if music is playing, always limit the volume to current music volume,
8480 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008481 if (!Intersection(deviceTypes,
8482 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8483 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008484 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8485 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008486 ((volumeSource == alarmVolumeSrc ||
8487 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008488 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8489 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8490 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008491 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8492 curves.canBeMuted()) {
8493
Eric Laurente552edb2014-03-10 17:42:56 -07008494 // when the phone is ringing we must consider that music could have been paused just before
8495 // by the music application and behave as if music was active if the last music track was
8496 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008497 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8498 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008499 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008500 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008501 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8502 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008503 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008504 float musicVolDb = computeVolume(musicCurves,
8505 musicVolumeSrc,
8506 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008507 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008508 adjustAttenuation,
8509 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008510 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8511 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8512 if (volumeDb > minVolDb) {
8513 volumeDb = minVolDb;
8514 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008515 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008516 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8517 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008518 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8519 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8520 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8521 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008522 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008523 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008524 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8525 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008526 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8527 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008528 }
8529 }
jiabin9a3361e2019-10-01 09:38:30 -07008530 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008531 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008532 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008533 }
8534 }
8535
François Gaffie43c73442018-11-08 08:21:55 +01008536 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008537}
8538
Eric Laurent3839bc02018-07-10 18:33:34 -07008539int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008540 VolumeSource fromVolumeSource,
8541 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008542{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008543 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008544 return srcIndex;
8545 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008546 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8547 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008548 float minSrc = (float)srcCurves.getVolumeIndexMin();
8549 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8550 float minDst = (float)dstCurves.getVolumeIndexMin();
8551 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008552
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008553 // preserve mute request or correct range
8554 if (srcIndex < minSrc) {
8555 if (srcIndex == 0) {
8556 return 0;
8557 }
8558 srcIndex = minSrc;
8559 } else if (srcIndex > maxSrc) {
8560 srcIndex = maxSrc;
8561 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008562 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8563}
8564
François Gaffieaaac0fd2018-11-22 17:56:39 +01008565status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8566 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008567 int index,
8568 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008569 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008570 int delayMs,
8571 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008572{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008573 // APM is single threaded, and single instance.
8574 static std::set<IVolumeCurves*> invalidCurvesReported;
8575
François Gaffieaaac0fd2018-11-22 17:56:39 +01008576 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008577 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008578 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8579 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008580 return NO_ERROR;
8581 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008582
Eric Laurentae6e88c2024-01-10 14:42:57 +01008583 bool isVoiceVolSrc;
8584 bool isBtScoVolSrc;
8585 if (!isVolumeConsistentForCalls(
8586 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008587 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008588 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008589 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008590 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008591
jiabin9a3361e2019-10-01 09:38:30 -07008592 if (deviceTypes.empty()) {
8593 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008594 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008595 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008596 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008597 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008598
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008599 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008600 if (!invalidCurvesReported.count(&curves)) {
8601 invalidCurvesReported.insert(&curves);
8602 String8 dump;
8603 curves.dump(&dump);
8604 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8605 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008606 return BAD_VALUE;
8607 }
8608
jiabin9a3361e2019-10-01 09:38:30 -07008609 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008610 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008611 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008612 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008613 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8614 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008615 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8616 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008617 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008618 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008619
8620 bool muted;
8621 if (!com_android_media_audio_ring_my_car()) {
8622 muted = (index == 0) && (volumeDb != 0.0f);
8623 } else {
8624 muted = curves.isMuted();
8625 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008626 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8627 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008628
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008629 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08008630 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08008631 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8632 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008633 }
Eric Laurente552edb2014-03-10 17:42:56 -07008634 return NO_ERROR;
8635}
8636
Eric Laurentae6e88c2024-01-10 14:42:57 +01008637void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008638 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008639 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008640
8641 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8642 index = 0;
8643 }
8644
chenxin2095559032024-06-15 13:59:29 +08008645 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008646 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008647 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008648 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8649 } else {
8650 voiceVolume = index == 0 ? 0.0 : 1.0;
8651 }
8652 if (voiceVolume != mLastVoiceVolume) {
8653 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8654 mLastVoiceVolume = voiceVolume;
8655 }
8656}
8657
8658bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8659 const DeviceTypeSet& deviceTypes,
8660 bool& isVoiceVolSrc,
8661 bool& isBtScoVolSrc,
8662 const char* caller) {
8663 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008664 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8665
Eric Laurentae6e88c2024-01-10 14:42:57 +01008666 const bool isScoRequested = isScoRequestedForComm();
8667 const bool isHAUsed = isHearingAidUsedForComm();
8668
Vlad Popa695b76b2024-06-14 16:49:25 -07008669 if (com_android_media_audio_replace_stream_bt_sco()) {
Vlad Popa695b76b2024-06-14 16:49:25 -07008670 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8671 (isScoRequested || isHAUsed);
8672 return true;
8673 }
8674
8675 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008676 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8677
8678 if ((callVolSrc != btScoVolSrc) &&
8679 ((isVoiceVolSrc && isScoRequested) ||
8680 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8681 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8682 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8683 volumeSource, isScoRequested ? " " : " not ");
8684 return false;
8685 }
8686 return true;
8687}
8688
Eric Laurentc75307b2015-03-17 15:29:32 -07008689void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008690 const DeviceTypeSet& deviceTypes,
8691 int delayMs,
8692 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008693{
jiabincd510522020-01-22 09:40:55 -08008694 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008695 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8696 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008697 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008698 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008699 }
8700}
8701
François Gaffiec005e562018-11-06 15:04:49 +01008702void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8703 bool on,
8704 const sp<AudioOutputDescriptor>& outputDesc,
8705 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008706 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008707{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008708 std::vector<VolumeSource> sourcesToMute;
8709 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8710 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8711 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008712 VolumeSource source = toVolumeSource(attributes, false);
8713 if ((source != VOLUME_SOURCE_NONE) &&
8714 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8715 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008716 sourcesToMute.push_back(source);
8717 }
Eric Laurente552edb2014-03-10 17:42:56 -07008718 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008719 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008720 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008721 }
8722
Eric Laurente552edb2014-03-10 17:42:56 -07008723}
8724
Vlad Popa1e865e62024-08-15 19:11:42 -07008725void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8726 bool on,
8727 const sp<AudioOutputDescriptor>& outputDesc,
8728 int delayMs,
8729 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008730{
jiabin9a3361e2019-10-01 09:38:30 -07008731 if (deviceTypes.empty()) {
8732 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008733 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008734 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008735 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008736 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008737 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008738 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008739 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8740 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008741 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008742 }
8743 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008744 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8745 // ignored
8746 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008747 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008748 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008749 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008750 return;
8751 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008752 if (outputDesc->decMuteCount(volumeSource) == 0) {
8753 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008754 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008755 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008756 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008757 delayMs);
8758 }
8759 }
8760}
8761
François Gaffie53615e22015-03-19 09:24:12 +01008762bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8763{
Vlad Popa7f1823b2024-11-05 15:37:52 -08008764 if ((paa->flags & AUDIO_FLAG_SCO) != 0) {
8765 ALOGW("%s: deprecated use of AUDIO_FLAG_SCO in attributes flags %d", __func__, paa->flags);
8766 }
8767
François Gaffiec005e562018-11-06 15:04:49 +01008768 // has flags that map to a stream type?
Vlad Popa7f1823b2024-11-05 15:37:52 -08008769 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_BEACON)) != 0) {
Eric Laurente83b55d2014-11-14 10:06:21 -08008770 return true;
8771 }
8772
8773 // has known usage?
8774 switch (paa->usage) {
8775 case AUDIO_USAGE_UNKNOWN:
8776 case AUDIO_USAGE_MEDIA:
8777 case AUDIO_USAGE_VOICE_COMMUNICATION:
8778 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8779 case AUDIO_USAGE_ALARM:
8780 case AUDIO_USAGE_NOTIFICATION:
8781 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8782 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8783 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8784 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8785 case AUDIO_USAGE_NOTIFICATION_EVENT:
8786 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8787 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8788 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8789 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008790 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008791 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008792 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008793 case AUDIO_USAGE_EMERGENCY:
8794 case AUDIO_USAGE_SAFETY:
8795 case AUDIO_USAGE_VEHICLE_STATUS:
8796 case AUDIO_USAGE_ANNOUNCEMENT:
Jean-Michel Trivid9add572024-11-05 14:48:40 -08008797 case AUDIO_USAGE_SPEAKER_CLEANUP:
Eric Laurente83b55d2014-11-14 10:06:21 -08008798 break;
8799 default:
8800 return false;
8801 }
8802 return true;
8803}
8804
François Gaffie2110e042015-03-24 08:41:51 +01008805audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8806{
8807 return mEngine->getForceUse(usage);
8808}
8809
Eric Laurent96d1dda2022-03-14 17:14:19 +01008810bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008811 return isStateInCall(mEngine->getPhoneState());
8812}
8813
Eric Laurent96d1dda2022-03-14 17:14:19 +01008814bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008815 return is_state_in_call(state);
8816}
8817
Eric Laurentf9cccec2022-11-16 19:12:00 +01008818bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008819 audio_mode_t mode = mEngine->getPhoneState();
8820 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008821 || (mode == AUDIO_MODE_CALL_SCREEN)
8822 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008823}
8824
Eric Laurentf9cccec2022-11-16 19:12:00 +01008825bool AudioPolicyManager::isInCallOrScreening() const {
8826 audio_mode_t mode = mEngine->getPhoneState();
8827 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8828}
8829
Eric Laurentd60560a2015-04-10 11:31:20 -07008830void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8831{
8832 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008833 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008834 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008835 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008836 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008837 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008838 }
8839 }
8840
8841 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8842 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8843 bool release = false;
8844 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8845 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8846 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8847 source->ext.device.type == deviceDesc->type()) {
8848 release = true;
8849 }
8850 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008851 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008852 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8853 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8854 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008855 sink->ext.device.type == deviceDesc->type() &&
8856 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8857 || strncmp(sink->ext.device.address, address,
8858 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008859 release = true;
8860 }
8861 }
8862 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008863 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8864 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008865 }
8866 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008867
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008868 mInputs.clearSessionRoutesForDevice(deviceDesc);
8869
Francois Gaffie716e1432019-01-14 16:58:59 +01008870 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008871}
8872
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008873void AudioPolicyManager::modifySurroundFormats(
8874 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008875 std::unordered_set<audio_format_t> enforcedSurround(
8876 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008877 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008878 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008879 allSurround.insert(pair.first);
8880 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8881 }
Phil Burk09bc4612016-02-24 15:58:15 -08008882
8883 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8884 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008885 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008886 // This is the resulting set of formats depending on the surround mode:
8887 // 'all surround' = allSurround
8888 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8889 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8890 // 'manual surround' = mManualSurroundFormats
8891 // AUTO: formats v 'enforced surround'
8892 // ALWAYS: formats v 'all surround' v 'enforced surround'
8893 // NEVER: formats ^ 'non-surround'
8894 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008895
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008896 std::unordered_set<audio_format_t> formatSet;
8897 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8898 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008899 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008900 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008901 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008902 formatSet.insert(*formatIter);
8903 }
8904 }
8905 } else {
8906 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8907 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008908 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008909
jiabin81772902018-04-02 17:52:27 -07008910 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008911 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008912 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8913 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8914 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008915 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008916 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8917 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8918 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008919 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008920 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008921 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008922 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008923 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008924 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008925}
8926
jiabin06e4bab2019-07-29 10:13:34 -07008927void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8928 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008929 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8930 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8931
8932 // If NEVER, then remove support for channelMasks > stereo.
8933 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008934 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8935 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008936 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008937 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008938 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008939 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008940 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008941 }
8942 }
jiabin81772902018-04-02 17:52:27 -07008943 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8944 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8945 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008946 bool supports5dot1 = false;
8947 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008948 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008949 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8950 supports5dot1 = true;
8951 break;
8952 }
8953 }
8954 // If not then add 5.1 support.
8955 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008956 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008957 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008958 }
Phil Burk09bc4612016-02-24 15:58:15 -08008959 }
8960}
8961
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008962void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008963 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008964 const sp<IOProfile>& profile) {
8965 if (!profile->hasDynamicAudioProfile()) {
8966 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008967 }
François Gaffie112b0af2015-11-19 16:13:25 +01008968
jiabin12537fc2023-10-12 17:56:08 +00008969 audio_port_v7 devicePort;
8970 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008971
jiabin12537fc2023-10-12 17:56:08 +00008972 audio_port_v7 mixPort;
8973 profile->toAudioPort(&mixPort);
8974 mixPort.ext.mix.handle = ioHandle;
8975
8976 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8977 if (status != NO_ERROR) {
8978 ALOGE("%s failed to query the attributes of the mix port", __func__);
8979 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008980 }
jiabin12537fc2023-10-12 17:56:08 +00008981
8982 std::set<audio_format_t> supportedFormats;
8983 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8984 supportedFormats.insert(mixPort.audio_profiles[i].format);
8985 }
8986 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8987 mReportedFormatsMap[devDesc] = formats;
8988
8989 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008990 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8991 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008992 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8993 modifySurroundFormats(devDesc, &formats);
8994 size_t modifiedNumProfiles = 0;
8995 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8996 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8997 formats.end()) {
8998 // Skip the format that is not present after modifying surround formats.
8999 continue;
9000 }
9001 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
9002 sizeof(struct audio_profile));
9003 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
9004 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
9005 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
9006 modifySurroundChannelMasks(&channels);
9007 std::copy(channels.begin(), channels.end(),
9008 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
9009 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
9010 }
9011 mixPort.num_audio_profiles = modifiedNumProfiles;
9012 }
9013 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01009014}
Eric Laurentd60560a2015-04-10 11:31:20 -07009015
Mikhail Naganovdc769682018-05-04 15:34:08 -07009016status_t AudioPolicyManager::installPatch(const char *caller,
9017 audio_patch_handle_t *patchHandle,
9018 AudioIODescriptorInterface *ioDescriptor,
9019 const struct audio_patch *patch,
9020 int delayMs)
9021{
9022 ssize_t index = mAudioPatches.indexOfKey(
9023 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
9024 *patchHandle : ioDescriptor->getPatchHandle());
9025 sp<AudioPatch> patchDesc;
9026 status_t status = installPatch(
9027 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
9028 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009029 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07009030 }
9031 return status;
9032}
9033
9034status_t AudioPolicyManager::installPatch(const char *caller,
9035 ssize_t index,
9036 audio_patch_handle_t *patchHandle,
9037 const struct audio_patch *patch,
9038 int delayMs,
9039 uid_t uid,
9040 sp<AudioPatch> *patchDescPtr)
9041{
9042 sp<AudioPatch> patchDesc;
9043 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9044 if (index >= 0) {
9045 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01009046 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009047 }
9048
9049 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9050 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9051 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9052 if (status == NO_ERROR) {
9053 if (index < 0) {
9054 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009055 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009056 } else {
9057 patchDesc->mPatch = *patch;
9058 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009059 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009060 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009061 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009062 }
9063 nextAudioPortGeneration();
9064 mpClientInterface->onAudioPatchListUpdate();
9065 }
9066 if (patchDescPtr) *patchDescPtr = patchDesc;
9067 return status;
9068}
9069
jiabinbce0c1d2020-10-05 11:20:18 -07009070bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9071{
9072 const TrackClientVector activeClients = output->getActiveClients();
9073 if (activeClients.empty()) {
9074 return true;
9075 }
9076 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9077 if (index < 0) {
9078 ALOGE("%s, no audio patch found while there are active clients on output %d",
9079 __func__, output->getId());
9080 return false;
9081 }
9082 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9083 DeviceVector routedDevices;
9084 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9085 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9086 patchDesc->mPatch.sinks[i].id);
9087 if (device == nullptr) {
9088 ALOGE("%s, no audio device found with id(%d)",
9089 __func__, patchDesc->mPatch.sinks[i].id);
9090 return false;
9091 }
9092 routedDevices.add(device);
9093 }
9094 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009095 if (client->isInvalid()) {
9096 // No need to take care about invalidated clients.
9097 continue;
9098 }
jiabinbce0c1d2020-10-05 11:20:18 -07009099 sp<DeviceDescriptor> preferredDevice =
9100 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9101 if (mEngine->getOutputDevicesForAttributes(
9102 client->attributes(), preferredDevice, false) == routedDevices) {
9103 return false;
9104 }
9105 }
9106 return true;
9107}
9108
9109sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009110 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009111 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9112 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009113{
9114 for (const auto& device : devices) {
9115 // TODO: This should be checking if the profile supports the device combo.
9116 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009117 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9118 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009119 return nullptr;
9120 }
9121 }
9122 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9123 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009124 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009125 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009126 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009127 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009128 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009129 return nullptr;
9130 }
jiabin14b50cc2023-12-13 19:01:52 +00009131 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9132 auto portConfig = desc->getConfig();
9133 for (const auto& device : devices) {
9134 device->setPreferredConfig(&portConfig);
9135 }
9136 }
jiabinbce0c1d2020-10-05 11:20:18 -07009137
9138 // Here is where the out_set_parameters() for card & device gets called
9139 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9140 const audio_devices_t deviceType = device->type();
9141 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009142 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009143 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9144 mpClientInterface->setParameters(output, String8(param));
9145 free(param);
9146 }
jiabin12537fc2023-10-12 17:56:08 +00009147 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009148 if (!profile->hasValidAudioProfile()) {
9149 ALOGW("%s() missing param", __func__);
9150 desc->close();
9151 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009152 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9153 // Reopen the output with the best audio profile picked by APM when the profile supports
9154 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009155 desc->close();
9156 output = AUDIO_IO_HANDLE_NONE;
9157 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9158 profile->pickAudioProfile(
9159 config.sample_rate, config.channel_mask, config.format);
9160 config.offload_info.sample_rate = config.sample_rate;
9161 config.offload_info.channel_mask = config.channel_mask;
9162 config.offload_info.format = config.format;
9163
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009164 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009165 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009166 if (status != NO_ERROR) {
9167 return nullptr;
9168 }
9169 }
9170
9171 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009172 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9173 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9174 hwModule->getHalVersionMajor() >= 3) {
9175 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9176 }
baek.kim -61c20122022-07-27 10:05:32 +00009177 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9178 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9179
jiabinbce0c1d2020-10-05 11:20:18 -07009180 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9181 sp<AudioPolicyMix> policyMix;
9182 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9183 policyMix->setOutput(desc);
9184 desc->mPolicyMix = policyMix;
9185 } else {
9186 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009187 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009188 }
9189
baek.kim -61c20122022-07-27 10:05:32 +00009190 } else if (hasPrimaryOutput() && speaker != nullptr
9191 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009192 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9193 // no duplicated output for:
9194 // - direct outputs
9195 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009196 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009197 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9198
9199 //TODO: configure audio effect output stage here
9200
9201 // open a duplicating output thread for the new output and the primary output
9202 sp<SwAudioOutputDescriptor> dupOutputDesc =
9203 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9204 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9205 if (status == NO_ERROR) {
9206 // add duplicated output descriptor
9207 addOutput(duplicatedOutput, dupOutputDesc);
9208 } else {
9209 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9210 mPrimaryOutput->mIoHandle, output);
9211 desc->close();
9212 removeOutput(output);
9213 nextAudioPortGeneration();
9214 return nullptr;
9215 }
9216 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009217 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9218 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9219 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009220 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009221 }
jiabinbce0c1d2020-10-05 11:20:18 -07009222 return desc;
9223}
9224
jiabinf1c73972022-04-14 16:28:52 -07009225status_t AudioPolicyManager::getDevicesForAttributes(
9226 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009227 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9228 // over any usage or content type also present in attr.
9229 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9230 attr.source != AUDIO_SOURCE_INVALID) {
9231 return getInputDevicesForAttributes(attr, devices);
9232 }
9233
jiabinf1c73972022-04-14 16:28:52 -07009234 // Devices are determined in the following precedence:
9235 //
9236 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9237 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9238 //
9239 // If no such dynamic policy then
9240 // 2) Devices containing an active client using setPreferredDevice
9241 // with same strategy as the attributes.
9242 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9243 //
9244 // If no corresponding active client with setPreferredDevice then
9245 // 3) Devices associated with the strategy determined by the attributes
9246 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9247 //
9248 // See related getOutputForAttrInt().
9249
9250 // check dynamic policies but only for primary descriptors (secondary not used for audible
9251 // audio routing, only used for duplication for playback capture)
9252 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009253 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009254 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009255 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9256 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9257 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009258 if (status != OK) {
9259 return status;
9260 }
9261
9262 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9263 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9264 // as they are unaffected by device/stream volume
9265 // (per SwAudioOutputDescriptor::isFixedVolume()).
9266 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9267 ) {
9268 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9269 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9270 devices.add(deviceDesc);
9271 } else {
9272 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9273 // which selects setPreferredDevice if active. This means forVolume call
9274 // will take an active setPreferredDevice, if such exists.
9275
9276 devices = mEngine->getOutputDevicesForAttributes(
9277 attr, nullptr /* preferredDevice */, false /* fromCache */);
9278 }
9279
9280 if (forVolume) {
9281 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9282 // for single volume control in AudioService (such relationship should exist if
9283 // SPEAKER_SAFE is present).
9284 //
9285 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9286 DeviceVector speakerSafeDevices =
9287 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9288 if (!speakerSafeDevices.isEmpty()) {
9289 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9290 devices.remove(speakerSafeDevices);
9291 }
9292 }
9293
9294 return NO_ERROR;
9295}
9296
wenyu zhang8558a332024-09-09 15:12:48 +00009297status_t AudioPolicyManager::getInputDevicesForAttributes(
9298 const audio_attributes_t &attr, DeviceVector &devices) {
9299 devices = DeviceVector(
9300 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9301 AUDIO_SESSION_NONE,
9302 nullptr /* mix */));
9303 return NO_ERROR;
9304}
9305
jiabinf1c73972022-04-14 16:28:52 -07009306status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9307 AudioProfileVector& audioProfiles,
9308 uint32_t flags,
9309 bool isInput) {
9310 for (const auto& hwModule : mHwModules) {
9311 // the MSD module checks for different conditions
9312 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9313 continue;
9314 }
9315 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9316 : hwModule->getOutputProfiles();
9317 for (const auto& profile : ioProfiles) {
9318 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009319 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009320 continue;
9321 }
9322 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9323 }
9324 }
9325
9326 if (!isInput) {
9327 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9328 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9329 if (msdModule != nullptr) {
9330 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9331 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9332 for (const auto &profile: msdModule->getOutputProfiles()) {
9333 if (!profile->asAudioPort()->isDirectOutput()) {
9334 continue;
9335 }
9336 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9337 }
9338 } else {
9339 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9340 }
9341 }
9342 }
9343
9344 return NO_ERROR;
9345}
9346
jiabin3ff8d7d2022-12-13 06:27:44 +00009347sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9348 const audio_config_t *config,
9349 audio_output_flags_t flags,
9350 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009351 closeOutput(outputDesc->mIoHandle);
9352 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9353 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9354 if (preferredOutput == nullptr) {
9355 ALOGE("%s failed to reopen output device=%d, caller=%s",
9356 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009357 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009358 return preferredOutput;
9359}
9360
9361void AudioPolicyManager::reopenOutputsWithDevices(
9362 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9363 for (const auto& [output, devices] : outputsToReopen) {
9364 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9365 closeOutput(output);
9366 openOutputWithProfileAndDevice(desc->mProfile, devices);
9367 }
jiabina84c3d32022-12-02 18:59:55 +00009368}
9369
jiabinc44b3462022-12-08 12:52:31 -08009370PortHandleVector AudioPolicyManager::getClientsForStream(
9371 audio_stream_type_t streamType) const {
9372 PortHandleVector clients;
9373 for (size_t i = 0; i < mOutputs.size(); ++i) {
9374 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9375 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9376 }
9377 return clients;
9378}
9379
9380void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9381 PortHandleVector clients;
9382 for (auto stream : streams) {
9383 PortHandleVector clientsForStream = getClientsForStream(stream);
9384 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9385 }
9386 mpClientInterface->invalidateTracks(clients);
9387}
9388
jiabin220eea12024-05-17 17:55:20 +00009389void AudioPolicyManager::updateClientsInternalMute(
9390 const sp<android::SwAudioOutputDescriptor> &desc) {
9391 if (!desc->isBitPerfect() ||
9392 !com::android::media::audioserver::
9393 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9394 // This is only used for bit perfect output now.
9395 return;
9396 }
9397 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9398 bool bitPerfectClientInternalMute = false;
9399 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9400 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9401 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9402 bitPerfectClient = client;
9403 continue;
9404 }
9405 bool muted = false;
9406 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9407 // System sound is muted.
9408 muted = true;
9409 } else {
9410 bitPerfectClientInternalMute = true;
9411 }
9412 if (client->setInternalMute(muted)) {
9413 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9414 if (!result.ok()) {
9415 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9416 continue;
9417 }
9418 media::TrackInternalMuteInfo info;
9419 info.portId = result.value();
9420 info.muted = client->getInternalMute();
9421 clientsInternalMute.push_back(std::move(info));
9422 }
9423 }
9424 if (bitPerfectClient != nullptr &&
9425 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9426 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9427 if (result.ok()) {
9428 media::TrackInternalMuteInfo info;
9429 info.portId = result.value();
9430 info.muted = bitPerfectClient->getInternalMute();
9431 clientsInternalMute.push_back(std::move(info));
9432 } else {
9433 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9434 __func__, bitPerfectClient->portId());
9435 }
9436 }
9437 if (!clientsInternalMute.empty()) {
9438 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9439 status != NO_ERROR) {
9440 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9441 }
9442 }
9443}
9444
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009445status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9446 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9447 if (policyType != AudioMMapPolicyType::DEFAULT &&
9448 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9449 return BAD_VALUE;
9450 }
9451 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9452 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9453 return status;
9454 }
9455 }
9456 *policyInfos = mMmapPolicyInfos[policyType];
9457 return NO_ERROR;
9458}
9459
9460status_t AudioPolicyManager::getMmapPolicyForDevice(
9461 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9462 if (policyType != AudioMMapPolicyType::DEFAULT &&
9463 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9464 return BAD_VALUE;
9465 }
9466 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9467 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9468 return status;
9469 }
9470 }
9471 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9472 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9473 ? AudioMMapPolicy::NEVER : it->second;
9474 return NO_ERROR;
9475}
9476
9477status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9478 std::vector<AudioMMapPolicyInfo> policyInfos;
9479 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9480 status != NO_ERROR) {
9481 ALOGE("%s, failed, error = %d", __func__, status);
9482 return status;
9483 }
9484 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9485 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9486 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9487 // it indicates the mmap policy is reported via system property. In that case, use the
9488 // routing information to fill details for how mmap is supported for a particular device.
9489 for (const auto &hwModule: mHwModules) {
9490 for (const auto &profile: hwModule->getInputProfiles()) {
9491 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9492 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9493 continue;
9494 }
9495 for (const auto &device: profile->getSupportedDevices()) {
9496 auto deviceDesc =
9497 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9498 if (deviceDesc.ok()) {
9499 mmapPolicyByDeviceType.emplace(
9500 deviceDesc.value(), policyInfos[0].mmapPolicy);
9501 }
9502 }
9503 }
9504 for (const auto &profile: hwModule->getOutputProfiles()) {
9505 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9506 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9507 continue;
9508 }
9509 for (const auto &device: profile->getSupportedDevices()) {
9510 auto deviceDesc =
9511 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9512 if (deviceDesc.ok()) {
9513 mmapPolicyByDeviceType.emplace(
9514 deviceDesc.value(), policyInfos[0].mmapPolicy);
9515 }
9516 }
9517 }
9518 }
9519 } else {
9520 for (const auto &info: policyInfos) {
9521 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9522 }
9523 }
9524 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9525 mMmapPolicyInfos.emplace(policyType, policyInfos);
9526 return NO_ERROR;
9527}
9528
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009529} // namespace android