blob: 18b5ea9d307b1db70c4c3e45cde16b0580acfc5e [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 &&
1562 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1563 secondaryOutputs->push_back(outputDesc->mIoHandle);
1564 weakSecondaryOutputDescs.push_back(outputDesc);
1565 }
1566 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001567 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001568
Eric Laurent8fc147b2018-07-22 19:13:55 -07001569 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001570 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001571 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001572 };
jiabin4ef93452019-09-10 14:29:54 -07001573 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001574
Eric Laurentc209fe42020-06-05 18:11:23 -07001575 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Robert Wufb971192024-10-30 21:54:35 +00001576 // TODO(b/367816690): Add device id sets to TrackClientDescriptor
Eric Laurent8fc147b2018-07-22 19:13:55 -07001577 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001578 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Robert Wufb971192024-10-30 21:54:35 +00001579 getFirstDeviceId(sanitizedRequestedPortIds), *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001580 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001581 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001582 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001583 std::move(weakSecondaryOutputDescs),
1584 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001585 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001586
Andy Hung6b137d12024-08-27 22:35:17 +00001587 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001588 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001589
Robert Wufb971192024-10-30 21:54:35 +00001590 ALOGV("%s() returns output %d requestedPortIds %s selectedDeviceIds %s for port ID %d",
1591 __func__, *output, toString(requestedDeviceIds).c_str(),
1592 toString(*selectedDeviceIds).c_str(), *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001593
Eric Laurente83b55d2014-11-14 10:06:21 -08001594 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001595}
1596
Eric Laurentc529cf62020-04-17 18:19:10 -07001597status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1598 audio_session_t session,
1599 const audio_config_t *config,
1600 audio_output_flags_t flags,
1601 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001602 audio_io_handle_t *output,
1603 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001604
1605 *output = AUDIO_IO_HANDLE_NONE;
1606
1607 // skip direct output selection if the request can obviously be attached to a mixed output
1608 // and not explicitly requested
1609 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1610 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1611 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1612 return NAME_NOT_FOUND;
1613 }
1614
Mikhail Naganov806170e2024-09-05 17:26:50 -07001615 // Reject flag combinations that do not make sense. Note that the requested flags might not
1616 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1617 // combine the requested flags with its own flags, yielding an unsupported combination.
1618 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1619 return NAME_NOT_FOUND;
1620 }
1621
Eric Laurentc529cf62020-04-17 18:19:10 -07001622 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1623 // This prevents creating an offloaded track and tearing it down immediately after start
1624 // when audioflinger detects there is an active non offloadable effect.
1625 // FIXME: We should check the audio session here but we do not have it in this context.
1626 // This may prevent offloading in rare situations where effects are left active by apps
1627 // in the background.
1628 sp<IOProfile> profile;
1629 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1630 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1631 profile = getProfileForOutput(
1632 devices, config->sample_rate, config->format, config->channel_mask,
1633 flags, true /* directOnly */);
1634 }
1635
1636 if (profile == nullptr) {
1637 return NAME_NOT_FOUND;
1638 }
1639
1640 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1641 for (size_t i = 0; i < mOutputs.size(); i++) {
1642 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1643 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1644 // reuse direct output if currently open by the same client
1645 // and configured with same parameters
1646 if ((config->sample_rate == desc->getSamplingRate()) &&
1647 (config->format == desc->getFormat()) &&
1648 (config->channel_mask == desc->getChannelMask()) &&
1649 (session == desc->mDirectClientSession)) {
1650 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301651 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001652 mOutputs.keyAt(i), session);
1653 *output = mOutputs.keyAt(i);
1654 return NO_ERROR;
1655 }
1656 }
1657 }
1658
1659 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001660 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301661 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1662 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001663 return NAME_NOT_FOUND;
1664 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1665 // MMAP gracefully handles lack of an exclusive track resource by mixing
1666 // above the audio framework. For AAudio to know that the limit is reached,
1667 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301668 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1669 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001670 return NAME_NOT_FOUND;
1671 } else {
1672 // Close outputs on this profile, if available, to free resources for this request
1673 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1674 const auto desc = mOutputs.valueAt(i);
1675 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301676 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1677 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001678 closeOutput(desc->mIoHandle);
1679 }
1680 }
1681 }
1682 }
1683
1684 // Unable to close streams to find free resources for this request
1685 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301686 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1687 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001688 return NAME_NOT_FOUND;
1689 }
1690
Atneya Nairb16666a2023-12-11 20:18:33 -08001691 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001692
Michael Chan6fb34492020-12-08 15:44:49 +11001693 // An MSD patch may be using the only output stream that can service this request. Release
1694 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001695 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001696
Eric Laurentf1f22e72021-07-13 14:04:14 +02001697 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001698 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001699 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001700
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001701 // only accept an output with the requested parameters, unless the format can be IEC61937
1702 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1703 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1704 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1705 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001706 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001707 (!ignoreRequestedParametersCheck &&
1708 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1709 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1710 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001711 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1712 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1713 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1714 config->channel_mask, outputDesc->getChannelMask());
1715 if (*output != AUDIO_IO_HANDLE_NONE) {
1716 outputDesc->close();
1717 }
1718 // fall back to mixer output if possible when the direct output could not be open
1719 if (audio_is_linear_pcm(config->format) &&
1720 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1721 return NAME_NOT_FOUND;
1722 }
1723 *output = AUDIO_IO_HANDLE_NONE;
1724 return BAD_VALUE;
1725 }
1726 outputDesc->mDirectOpenCount = 1;
1727 outputDesc->mDirectClientSession = session;
1728
1729 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001730 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1731 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1732 hwModule->getHalVersionMajor() >= 3) {
1733 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1734 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001735 mPreviousOutputs = mOutputs;
1736 ALOGV("%s returns new direct output %d", __func__, *output);
1737 mpClientInterface->onAudioPortListUpdate();
1738 return NO_ERROR;
1739}
1740
François Gaffie11d30102018-11-02 16:09:09 +01001741audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1742 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001743 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001744 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001745 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001746 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001747 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001748 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001749 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001750{
Andy Hungc88b0642018-04-27 15:42:35 -07001751 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001752
jiabine375d412019-02-26 12:54:53 -08001753 // Discard haptic channel mask when forcing muting haptic channels.
1754 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001755 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1756 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001757
Eric Laurente552edb2014-03-10 17:42:56 -07001758 // open a direct output if required by specified parameters
1759 //force direct flag if offload flag is set: offloading implies a direct output stream
1760 // and all common behaviors are driven by checking only the direct flag
1761 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001762 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1763 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001764 }
Nadav Bar766fb022018-01-07 12:18:03 +02001765 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1766 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001767 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001768
1769 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1770
Eric Laurente83b55d2014-11-14 10:06:21 -08001771 // only allow deep buffering for music stream type
1772 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001773 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001774 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001775 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001776 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001777 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001778 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001779 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001780 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001781 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001782 audio_is_linear_pcm(config->format) &&
1783 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001784 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001785 AUDIO_OUTPUT_FLAG_DIRECT);
1786 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001787 }
Eric Laurente552edb2014-03-10 17:42:56 -07001788
Carter Hsua3abb402021-10-26 11:11:20 +08001789 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1790 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1791 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1792 }
1793
Eric Laurentf9230d52024-01-26 18:49:09 +01001794 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001795 // was specified and offload or direct playback is not explicitly requested, and there is no
1796 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001797 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001798 if (mSpatializerOutput != nullptr &&
1799 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1800 prefMixerConfigInfo == nullptr &&
1801 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1802 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001803 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001804 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001805 }
1806
Eric Laurentc529cf62020-04-17 18:19:10 -07001807 audio_config_t directConfig = *config;
1808 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001809
1810 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1811 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001812 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001813 return output;
1814 }
1815
Eric Laurent14cbfca2016-03-17 09:42:16 -07001816 // A request for HW A/V sync cannot fallback to a mixed output because time
1817 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001818 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001819 return AUDIO_IO_HANDLE_NONE;
1820 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001821 // A request for Tuner cannot fallback to a mixed output
1822 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1823 return AUDIO_IO_HANDLE_NONE;
1824 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001825
Eric Laurente552edb2014-03-10 17:42:56 -07001826 // ignoring channel mask due to downmix capability in mixer
1827
1828 // open a non direct output
1829
1830 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001831 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001832 // get which output is suitable for the specified stream. The actual
1833 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001834 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001835 if (prefMixerConfigInfo != nullptr) {
1836 for (audio_io_handle_t outputHandle : outputs) {
1837 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1838 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1839 output = outputHandle;
1840 break;
1841 }
1842 }
1843 if (output == AUDIO_IO_HANDLE_NONE) {
1844 // No output open with the preferred profile. Open a new one.
1845 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1846 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1847 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1848 config.format = prefMixerConfigInfo->getConfigBase().format;
1849 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1850 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1851 &config, prefMixerConfigInfo->getFlags());
1852 if (preferredOutput == nullptr) {
1853 ALOGE("%s failed to open output with preferred mixer config", __func__);
1854 } else {
1855 output = preferredOutput->mIoHandle;
1856 }
1857 }
1858 } else {
1859 // at this stage we should ignore the DIRECT flag as no direct output could be
1860 // found earlier
1861 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001862 if (com::android::media::audioserver::
1863 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1864 // If the preferred mixer attributes is null, do not select the bit-perfect output
1865 // unless the bit-perfect output is the only output.
1866 // The bit-perfect output can exist while the passed in preferred mixer attributes
1867 // info is null when it is a high priority client. The high priority clients are
1868 // ringtone or alarm, which is not a bit-perfect use case.
1869 size_t i = 0;
1870 while (i < outputs.size() && outputs.size() > 1) {
1871 auto desc = mOutputs.valueFor(outputs[i]);
1872 // The output descriptor must not be null here.
1873 if (desc->isBitPerfect()) {
1874 outputs.removeItemsAt(i);
1875 } else {
1876 i += 1;
1877 }
1878 }
1879 }
jiabina84c3d32022-12-02 18:59:55 +00001880 output = selectOutput(
1881 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1882 }
Eric Laurente552edb2014-03-10 17:42:56 -07001883 }
François Gaffie11d30102018-11-02 16:09:09 +01001884 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001885 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001886 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001887
Eric Laurente552edb2014-03-10 17:42:56 -07001888 return output;
1889}
1890
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001891sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001892 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1893 mAvailableInputDevices);
1894 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1895}
1896
1897DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1898 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1899 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900}
1901
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001902const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001904 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1905 if (msdModule != 0) {
1906 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1907 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1908 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1909 const struct audio_port_config *source = &patch->mPatch.sources[j];
1910 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1911 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001912 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001913 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001914 }
1915 }
1916 }
1917 return msdPatches;
1918}
1919
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001920bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1921 ssize_t index = mAudioPatches.indexOfKey(handle);
1922 if (index < 0) {
1923 return false;
1924 }
1925 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1926 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1927 if (msdModule == nullptr) {
1928 return false;
1929 }
1930 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1931 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1932 return true;
1933 }
1934 index = getMsdOutputPatches().indexOfKey(handle);
1935 if (index < 0) {
1936 return false;
1937 }
1938 return true;
1939}
1940
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001941status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1942 const InputProfileCollection &inputProfiles,
1943 const OutputProfileCollection &outputProfiles,
1944 const sp<DeviceDescriptor> &sourceDevice,
1945 const sp<DeviceDescriptor> &sinkDevice,
1946 AudioProfileVector& sourceProfiles,
1947 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001950 return NO_INIT;
1951 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001954 return NO_INIT;
1955 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001956 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001957 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1958 inProfile->supportsDevice(sourceDevice)) {
1959 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001960 }
1961 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001962 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001963 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001964 outProfile->supportsDevice(sinkDevice)) {
1965 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 }
1967 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001968 return NO_ERROR;
1969}
1970
1971status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1972 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1973 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1974{
Dean Wheatley16809da2022-12-09 14:55:46 +11001975 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1976 static const std::vector<audio_format_t> formatsOrder = {{
1977 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001978 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1979 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001980 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1981 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1982 // preferred).
1983 std::vector<audio_channel_mask_t> masks = {{
1984 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1985 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1986 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1987 // insert index masks (higher counts most preferred) as preferred over position masks
1988 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1989 masks.insert(
1990 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1991 }
1992 return masks;
1993 }();
1994
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001995 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001996 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1997 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001998 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001999 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
2000 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07002001 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002002 }
2003 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
2004 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
2005 sinkConfig->format = bestSinkConfig.format;
2006 // For encoded streams force direct flag to prevent downstream mixing.
2007 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2008 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002009 if (audio_is_iec61937_compatible(sinkConfig->format)) {
2010 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002011 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002012 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2013 // raw and IEC61937 framed streams.
2014 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2015 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2016 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002017 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2018 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002019 sourceConfig->channel_mask =
2020 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2021 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2022 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002023 sourceConfig->format = bestSinkConfig.format;
2024 // Copy input stream directly without any processing (e.g. resampling).
2025 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2026 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2027 if (hwAvSync) {
2028 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2029 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2030 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2031 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2032 }
2033 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2034 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2035 sinkConfig->config_mask |= config_mask;
2036 sourceConfig->config_mask |= config_mask;
2037 return NO_ERROR;
2038}
2039
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002040PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2041 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002042{
2043 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002044 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2045 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2046 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2047 if (deviceModule == nullptr) {
2048 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2049 return patchBuilder;
2050 }
2051 const InputProfileCollection inputProfiles = msdIsSource ?
2052 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2053 const OutputProfileCollection outputProfiles = msdIsSource ?
2054 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2055
2056 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2057 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2058 device : getMsdAudioOutDevices().itemAt(0);
2059 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2060
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002061 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2062 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002063 AudioProfileVector sourceProfiles;
2064 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002065 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2066 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002067 for (auto hwAvSync : { true, false }) {
2068 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2069 sourceProfiles, sinkProfiles) != NO_ERROR) {
2070 continue;
2071 }
2072 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2073 &sinkConfig) == NO_ERROR) {
2074 // Found a matching config. Re-create PatchBuilder with this config.
2075 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2076 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002077 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002078 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002079 " supporting PCM format conversion.", __func__);
2080 return patchBuilder;
2081}
2082
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002083status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002084 DeviceVector devices;
2085 if (outputDevices != nullptr && outputDevices->size() > 0) {
2086 devices.add(*outputDevices);
2087 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002088 // Use media strategy for unspecified output device. This should only
2089 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2090 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002091 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002092 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002093 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002094 }
Michael Chan6fb34492020-12-08 15:44:49 +11002095 std::vector<PatchBuilder> patchesToCreate;
2096 for (auto i = 0u; i < devices.size(); ++i) {
2097 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002098 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002099 }
2100 // Retain only the MSD patches associated with outputDevices request.
2101 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002102 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002103 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2104 auto retainedPatch = false;
2105 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2106 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2107 patchesToRemove.removeItemsAt(i);
2108 retainedPatch = true;
2109 break;
2110 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002111 }
Michael Chan6fb34492020-12-08 15:44:49 +11002112 if (retainedPatch) {
2113 it = patchesToCreate.erase(it);
2114 continue;
2115 }
2116 ++it;
2117 }
2118 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2119 return NO_ERROR;
2120 }
2121 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2122 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002123 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002124 }
Michael Chan6fb34492020-12-08 15:44:49 +11002125 status_t status = NO_ERROR;
2126 for (const auto &p : patchesToCreate) {
2127 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2128 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2129 char message[256];
2130 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2131 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2132 currStatus == NO_ERROR ? "Success" : "Error",
2133 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2134 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2135 if (currStatus == NO_ERROR) {
2136 ALOGD("%s", message);
2137 } else {
2138 ALOGE("%s", message);
2139 if (status == NO_ERROR) {
2140 status = currStatus;
2141 }
2142 }
2143 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002144 return status;
2145}
2146
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002147void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2148 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002149 for (size_t i = 0; i < msdPatches.size(); i++) {
2150 const auto& patch = msdPatches[i];
2151 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2152 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2153 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2154 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2155 releaseAudioPatch(patch->getHandle(), mUidCached);
2156 break;
2157 }
2158 }
2159 }
2160}
2161
Dorin Drimus94d94412022-02-02 09:05:02 +01002162bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002163 DeviceVector devicesToCheck =
2164 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002165 AudioPatchCollection msdPatches = getMsdOutputPatches();
2166 for (size_t i = 0; i < msdPatches.size(); i++) {
2167 const auto& patch = msdPatches[i];
2168 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2169 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2170 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2171 const auto& foundDevice = devicesToCheck.getDevice(
2172 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2173 if (foundDevice != nullptr) {
2174 devicesToCheck.remove(foundDevice);
2175 if (devicesToCheck.isEmpty()) {
2176 return true;
2177 }
2178 }
2179 }
2180 }
2181 }
2182 return false;
2183}
2184
Eric Laurente0720872014-03-11 09:30:41 -07002185audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002186 audio_output_flags_t flags,
2187 audio_format_t format,
2188 audio_channel_mask_t channelMask,
2189 uint32_t samplingRate,
2190 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002191{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002192 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2193 "%s called with format %#x", __func__, format);
2194
jiabinebb6af42020-06-09 17:31:17 -07002195 // Return the output that haptic-generating attached to when 1) session id is specified,
2196 // 2) haptic-generating effect exists for given session id and 3) the output that
2197 // haptic-generating effect attached to is in given outputs.
2198 if (sessionId != AUDIO_SESSION_NONE) {
2199 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2200 sessionId, FX_IID_HAPTICGENERATOR);
2201 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2202 return hapticGeneratingOutput;
2203 }
2204 }
2205
Eric Laurent16c66dd2019-05-01 17:54:10 -07002206 // Flags disqualifying an output: the match must happen before calling selectOutput()
2207 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2208 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2209
2210 // Flags expressing a functional request: must be honored in priority over
2211 // other criteria
2212 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2213 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002214 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2215 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002216 // Flags expressing a performance request: have lower priority than serving
2217 // requested sampling rate or channel mask
2218 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2219 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2220 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2221
2222 const audio_output_flags_t functionalFlags =
2223 (audio_output_flags_t)(flags & kFunctionalFlags);
2224 const audio_output_flags_t performanceFlags =
2225 (audio_output_flags_t)(flags & kPerformanceFlags);
2226
2227 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2228
Eric Laurente552edb2014-03-10 17:42:56 -07002229 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002230 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002231 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002232 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002233 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002234 // with tiebreak preferring the minimum number of extra functional flags
2235 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002236 // 3: the output supporting the exact channel mask
2237 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002238 // 5: the output with the highest sampling rate if the requested sample rate is
2239 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002240 // 6: the output with the highest number of requested performance flags
2241 // 7: the output with the bit depth the closest to the requested one
2242 // 8: the primary output
2243 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002244
Eric Laurent16c66dd2019-05-01 17:54:10 -07002245 // matching criteria values in priority order for best matching output so far
2246 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002247
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002248 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002249 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2250 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2251 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002252
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002253 for (audio_io_handle_t output : outputs) {
2254 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002255 // matching criteria values in priority order for current output
2256 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002257
Eric Laurent16c66dd2019-05-01 17:54:10 -07002258 if (outputDesc->isDuplicated()) {
2259 continue;
2260 }
2261 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2262 continue;
2263 }
Eric Laurent8838a382014-09-08 16:44:28 -07002264
Eric Laurent16c66dd2019-05-01 17:54:10 -07002265 // If haptic channel is specified, use the haptic output if present.
2266 // When using haptic output, same audio format and sample rate are required.
2267 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002268 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002269 // skip if haptic channel specified but output does not support it, or output support haptic
2270 // but there is no haptic channel requested AND no orphan haptic effect exist
2271 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2272 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002273 continue;
2274 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002275 // In the case of audio-coupled-haptic playback, there is no format conversion and
2276 // resampling in the framework, same format/channel/sampleRate for client and the output
2277 // thread is required. In the case of HapticGenerator effect, do not require format
2278 // matching.
2279 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2280 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002281 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002282 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002283 }
2284
2285 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002286 const int matchingFunctionalFlags =
2287 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2288 const int totalFunctionalFlags =
2289 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2290 // Prefer matching functional flags, but subtract unnecessary functional flags.
2291 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002292
2293 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002294 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2295 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002296 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2297 channelCount <= outputChannelCount) {
2298 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002299 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2300 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002301 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002302 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002303 currentMatchCriteria[3] = outputChannelCount;
2304 }
2305
2306 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002307 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002308 int diff; // avoid unsigned integer overflow.
2309 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2310
2311 // prefer the closest output sampling rate greater than or equal to target
2312 // if none exists, prefer the closest output sampling rate less than target.
2313 //
2314 // criteria is offset to make non-negative.
2315 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002316 }
2317
2318 // performance flags match
2319 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2320
2321 // format match
2322 if (format != AUDIO_FORMAT_INVALID) {
2323 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002324 PolicyAudioPort::kFormatDistanceMax -
2325 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002326 }
2327
2328 // primary output match
2329 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2330
2331 // compare match criteria by priority then value
2332 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2333 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2334 bestMatchCriteria = currentMatchCriteria;
2335 bestOutput = output;
2336
2337 std::stringstream result;
2338 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2339 std::ostream_iterator<int>(result, " "));
2340 ALOGV("%s new bestOutput %d criteria %s",
2341 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002342 }
2343 }
2344
Eric Laurent16c66dd2019-05-01 17:54:10 -07002345 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002346}
2347
Eric Laurent8fc147b2018-07-22 19:13:55 -07002348status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002349{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002350 ALOGV("%s portId %d", __FUNCTION__, portId);
2351
2352 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2353 if (outputDesc == 0) {
2354 ALOGW("startOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002355 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002356 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002357 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002358
Eric Laurent8fc147b2018-07-22 19:13:55 -07002359 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002360 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002361
jiabin220eea12024-05-17 17:55:20 +00002362 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2363 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2364 && outputDesc->isBitPerfect()) {
2365 // Usually, APM selects bit-perfect output for high priority use cases only when
2366 // bit-perfect output is the only output that can be routed to the selected device.
2367 // However, here is no need to play high priority use cases such as ringtone and alarm
2368 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2369 // can attach to new output.
2370 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2371 __func__, client->stream());
2372 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2373 return DEAD_OBJECT;
2374 }
2375
Eric Laurent733ce942017-12-07 12:18:25 -08002376 status_t status = outputDesc->start();
2377 if (status != NO_ERROR) {
2378 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002379 }
2380
Eric Laurent97ac8712018-07-27 18:59:02 -07002381 uint32_t delayMs;
2382 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002383
2384 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002385 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002386 if (status == DEAD_OBJECT) {
2387 sp<SwAudioOutputDescriptor> desc =
2388 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2389 if (desc == nullptr) {
2390 // This is not common, it may indicate something wrong with the HAL.
2391 ALOGE("%s unable to open output with default config", __func__);
2392 return status;
2393 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002394 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002395 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002396 }
jiabina84c3d32022-12-02 18:59:55 +00002397
2398 // If the client is the first one active on preferred mixer parameters, reopen the output
2399 // if the current mixer parameters doesn't match the preferred one.
2400 if (outputDesc->devices().size() == 1) {
2401 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2402 outputDesc->devices()[0]->getId(), client->strategy());
2403 if (info != nullptr && info->getUid() == client->uid()) {
2404 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2405 info->getConfigBase(), info->getFlags())) {
2406 stopSource(outputDesc, client);
2407 outputDesc->stop();
2408 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2409 config.channel_mask = info->getConfigBase().channel_mask;
2410 config.sample_rate = info->getConfigBase().sample_rate;
2411 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002412 sp<SwAudioOutputDescriptor> desc =
2413 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2414 if (desc == nullptr) {
2415 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002416 }
jiabin220eea12024-05-17 17:55:20 +00002417 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002418 // Intentionally return error to let the client side resending request for
2419 // creating and starting.
2420 return DEAD_OBJECT;
2421 }
2422 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002423 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002424 // If it is first bit-perfect client, reroute all clients that will be routed to
2425 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2426 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002427 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002428 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002429 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2430 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002431 continue;
2432 }
jiabine6b87492024-09-18 23:36:14 +00002433 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2434 outputsToResetDevice.push_back(mOutputs[i]);
2435 }
jiabine3d1f552023-06-14 17:42:17 +00002436 for (const auto& c : mOutputs[i]->getClientIterable()) {
2437 clientsToInvalidate.push_back(c->portId());
2438 }
2439 }
2440 if (!clientsToInvalidate.empty()) {
2441 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2442 __func__);
2443 mpClientInterface->invalidateTracks(clientsToInvalidate);
2444 }
jiabine6b87492024-09-18 23:36:14 +00002445 for (const auto& output : outputsToResetDevice) {
2446 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2447 }
jiabine3d1f552023-06-14 17:42:17 +00002448 }
jiabina84c3d32022-12-02 18:59:55 +00002449 }
2450 }
2451
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002452 if (client->hasPreferredDevice()) {
2453 // playback activity with preferred device impacts routing occurred, inform upper layers
2454 mpClientInterface->onRoutingUpdated();
2455 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002456 if (delayMs != 0) {
2457 usleep(delayMs * 1000);
2458 }
2459
jiabin220eea12024-05-17 17:55:20 +00002460 if (status == NO_ERROR &&
2461 outputDesc->mPreferredAttrInfo != nullptr &&
2462 outputDesc->isBitPerfect() &&
2463 com::android::media::audioserver::
2464 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2465 // A new client is started on bit-perfect output, update all clients internal mute.
2466 updateClientsInternalMute(outputDesc);
2467 }
2468
Eric Laurentc75307b2015-03-17 15:29:32 -07002469 return status;
2470}
2471
Eric Laurent96d1dda2022-03-14 17:14:19 +01002472bool AudioPolicyManager::isLeUnicastActive() const {
2473 if (isInCall()) {
2474 return true;
2475 }
2476 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2477}
2478
2479bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2480 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2481 return false;
2482 }
2483 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2484 ALOGV("%s active %d", __func__, active);
2485 return active;
2486}
2487
Eric Laurent97ac8712018-07-27 18:59:02 -07002488status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2489 const sp<TrackClientDescriptor>& client,
2490 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002491{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002492 // cannot start playback of STREAM_TTS if any other output is being used
2493 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002494
2495 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002496 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002497 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002498 auto clientStrategy = client->strategy();
2499 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002500 if (stream == AUDIO_STREAM_TTS) {
2501 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002502 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002503 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002504 return INVALID_OPERATION;
2505 } else {
2506 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2507 }
2508 } else {
2509 // some playback other than beacon starts
2510 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2511 }
2512
Eric Laurent77305a62016-07-25 16:39:22 -07002513 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002514 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002515 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002516
François Gaffie11d30102018-11-02 16:09:09 +01002517 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002518 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002519 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002520 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002521 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002522 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002523 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002524 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002525 } else {
2526 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002527 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002528 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2529 AUDIO_FORMAT_DEFAULT);
2530 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2531 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002532 }
2533
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002534 // requiresMuteCheck is false when we can bypass mute strategy.
2535 // It covers a common case when there is no materially active audio
2536 // and muting would result in unnecessary delay and dropped audio.
2537 const uint32_t outputLatencyMs = outputDesc->latency();
2538 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002539 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002540
Eric Laurente552edb2014-03-10 17:42:56 -07002541 // increment usage count for this stream on the requested output:
2542 // NOTE that the usage count is the same for duplicated output and hardware output which is
2543 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002544 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002545
2546 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002547 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002548 // Preferred device may be exclusive, use only if no other active clients on this output
2549 devices = DeviceVector(
2550 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2551 } else {
2552 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2553 }
François Gaffie11d30102018-11-02 16:09:09 +01002554 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002555 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002556 }
2557 }
Eric Laurente552edb2014-03-10 17:42:56 -07002558
François Gaffiec005e562018-11-06 15:04:49 +01002559 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002560 selectOutputForMusicEffects();
2561 }
2562
François Gaffie1c878552018-11-22 16:53:21 +01002563 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002564 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002565 if (devices.isEmpty()) {
2566 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002567 }
François Gaffiec005e562018-11-06 15:04:49 +01002568 bool shouldWait =
2569 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2570 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2571 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002572 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002573 const bool needToCloseBitPerfectOutput =
2574 (com::android::media::audioserver::
2575 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2576 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2577 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002578 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002580 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002581 // An output has a shared device if
2582 // - managed by the same hw module
2583 // - supports the currently selected device
2584 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002585 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002586
Eric Laurent77305a62016-07-25 16:39:22 -07002587 // force a device change if any other output is:
2588 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002589 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002590 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002591 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002592 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002593 // change the device currently selected by the other output.
2594 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002595 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002596 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002597 force = true;
2598 }
2599 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002600 // a notification so that audio focus effect can propagate, or that a mute/unmute
2601 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002602 const uint32_t latencyMs = desc->latency();
2603 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2604
2605 if (shouldWait && isActive && (waitMs < latencyMs)) {
2606 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002607 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002608
2609 // Require mute check if another output is on a shared device
2610 // and currently active to have proper drain and avoid pops.
2611 // Note restoring AudioTracks onto this output needs to invoke
2612 // a volume ramp if there is no mute.
2613 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002614
2615 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2616 outputsToReopen.push_back(desc);
2617 }
Eric Laurente552edb2014-03-10 17:42:56 -07002618 }
2619 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002620
jiabin220eea12024-05-17 17:55:20 +00002621 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002622 // If the output is open with preferred mixer attributes, but the routed device is
2623 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2624 // changed.
2625 return DEAD_OBJECT;
2626 }
jiabin220eea12024-05-17 17:55:20 +00002627 for (auto& outputToReopen : outputsToReopen) {
2628 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2629 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002630 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302631 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2632 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002633
Eric Laurente552edb2014-03-10 17:42:56 -07002634 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002635 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002636 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002637 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002638 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002639 outputDesc->useHwGain() /*force*/)) {
2640 // request AudioService to reinitialize the volume curves asynchronously
2641 ALOGE("checkAndSetVolume failed, requesting volume range init");
2642 mpClientInterface->onVolumeRangeInitRequest();
2643 };
Eric Laurente552edb2014-03-10 17:42:56 -07002644
2645 // update the outputs if starting an output with a stream that can affect notification
2646 // routing
2647 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002648
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002649 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002650 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002651 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002652 }
Eric Laurentdc462862016-07-19 12:29:53 -07002653
2654 if (waitMs > muteWaitMs) {
2655 *delayMs = waitMs - muteWaitMs;
2656 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002657
2658 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2659 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2660 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2661 // change occurs after the MixerThread starts and causes a stream volume
2662 // glitch.
2663 //
2664 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002665 }
Eric Laurentdc462862016-07-19 12:29:53 -07002666
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002667 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002668 mEngine->getForceUse(
2669 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002670 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002671 }
2672
Eric Laurent97ac8712018-07-27 18:59:02 -07002673 // Automatically enable the remote submix input when output is started on a re routing mix
2674 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002675 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2676 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002677 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2678 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2679 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002680 "remote-submix",
2681 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002682 }
2683
Eric Laurent96d1dda2022-03-14 17:14:19 +01002684 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2685
Eric Laurente552edb2014-03-10 17:42:56 -07002686 return NO_ERROR;
2687}
2688
Eric Laurent96d1dda2022-03-14 17:14:19 +01002689void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2690 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2691 bool isUnicastActive = isLeUnicastActive();
2692
2693 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002694 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002695 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2696 for (size_t i = 0; i < mOutputs.size(); i++) {
2697 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2698 if (desc != ignoredOutput && desc->isActive()
2699 && ((isUnicastActive &&
2700 !desc->devices().
2701 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2702 || (wasUnicastActive &&
2703 !desc->devices().getDevicesFromTypes(
2704 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2705 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2706 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002707 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002708 // If the device is using preferred mixer attributes, the output need to reopen
2709 // with default configuration when the new selected devices are different from
2710 // current routing devices.
2711 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2712 continue;
2713 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302714 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002715 // re-apply device specific volume if not done by setOutputDevice()
2716 if (!force) {
2717 applyStreamVolumes(desc, newDevices.types(), delayMs);
2718 }
2719 }
2720 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002721 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002722 }
2723}
2724
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002726{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002727 ALOGV("%s portId %d", __FUNCTION__, portId);
2728
2729 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2730 if (outputDesc == 0) {
2731 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002732 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002733 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002734 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002735
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002736 if (client->hasPreferredDevice(true)) {
2737 // playback activity with preferred device impacts routing occurred, inform upper layers
2738 mpClientInterface->onRoutingUpdated();
2739 }
2740
Eric Laurent97ac8712018-07-27 18:59:02 -07002741 ALOGV("stopOutput() output %d, stream %d, session %d",
2742 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002743
Eric Laurent97ac8712018-07-27 18:59:02 -07002744 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002745
Eric Laurent733ce942017-12-07 12:18:25 -08002746 if (status == NO_ERROR ) {
2747 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002748 } else {
2749 return status;
2750 }
2751
2752 if (outputDesc->devices().size() == 1) {
2753 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2754 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002755 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002756 if (info != nullptr && info->getUid() == client->uid()) {
2757 info->decreaseActiveClient();
2758 if (info->getActiveClientCount() == 0) {
2759 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002760 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002761 }
2762 }
jiabin220eea12024-05-17 17:55:20 +00002763 if (com::android::media::audioserver::
2764 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2765 !outputReopened && outputDesc->isBitPerfect()) {
2766 // Only need to update the clients' internal mute when the output is bit-perfect and it
2767 // is not reopened.
2768 updateClientsInternalMute(outputDesc);
2769 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002770 }
2771 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002772}
2773
Eric Laurent97ac8712018-07-27 18:59:02 -07002774status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2775 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002776{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002777 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002778 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002779 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002780 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002781
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002782 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2783
François Gaffie1c878552018-11-22 16:53:21 +01002784 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2785 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002786 // Automatically disable the remote submix input when output is stopped on a
2787 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002788 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002789 if (isSingleDeviceType(
2790 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002791 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002792 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002793 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2794 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002795 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002796 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002797 }
2798 }
2799 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002800 if (client->hasPreferredDevice(true) &&
2801 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002802 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002803 forceDeviceUpdate = true;
2804 }
2805
Eric Laurente552edb2014-03-10 17:42:56 -07002806 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002807 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002808
Eric Laurente552edb2014-03-10 17:42:56 -07002809 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002810 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002811 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002812 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002813
2814 // If the routing does not change, if an output is routed on a device using HwGain
2815 // (aka setAudioPortConfig) and there are still active clients following different
2816 // volume group(s), force reapply volume
2817 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2818 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2819
Eric Laurente552edb2014-03-10 17:42:56 -07002820 // delay the device switch by twice the latency because stopOutput() is executed when
2821 // the track stop() command is received and at that time the audio track buffer can
2822 // still contain data that needs to be drained. The latency only covers the audio HAL
2823 // and kernel buffers. Also the latency does not always include additional delay in the
2824 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302825 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002826 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002827
2828 // force restoring the device selection on other active outputs if it differs from the
2829 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002830 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002831 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002832 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002833 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002834 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002835 desc->isActive() &&
2836 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002837 (newDevices != desc->devices())) {
2838 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2839 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002840
jiabin220eea12024-05-17 17:55:20 +00002841 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002842 // If the device is using preferred mixer attributes, the output need to
2843 // reopen with default configuration when the new selected devices are
2844 // different from current routing devices.
2845 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2846 continue;
2847 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302848 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002849
Eric Laurent57de36c2016-09-28 16:59:11 -07002850 // re-apply device specific volume if not done by setOutputDevice()
2851 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002852 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002853 }
Eric Laurente552edb2014-03-10 17:42:56 -07002854 }
2855 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002856 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002857 // update the outputs if stopping one with a stream that can affect notification routing
2858 handleNotificationRoutingForStream(stream);
2859 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002860
2861 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2862 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002863 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002864 }
2865
François Gaffiec005e562018-11-06 15:04:49 +01002866 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002867 selectOutputForMusicEffects();
2868 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002869
2870 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2871
Eric Laurente552edb2014-03-10 17:42:56 -07002872 return NO_ERROR;
2873 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002874 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002875 return INVALID_OPERATION;
2876 }
2877}
2878
jiabinbce0c1d2020-10-05 11:20:18 -07002879bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002880{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002881 ALOGV("%s portId %d", __FUNCTION__, portId);
2882
2883 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2884 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002885 // If an output descriptor is closed due to a device routing change,
2886 // then there are race conditions with releaseOutput from tracks
2887 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2888 // destroyed shortly thereafter.
2889 //
2890 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002891 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002892 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002893 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894
2895 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002896
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302897 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2898 if (outputDesc->isClientActive(client)) {
2899 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2900 stopOutput(portId);
2901 }
2902
Eric Laurent8fc147b2018-07-22 19:13:55 -07002903 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2904 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002905 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002906 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002907 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002908 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002909 if (--outputDesc->mDirectOpenCount == 0) {
2910 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002911 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002912 }
2913 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302914
Andy Hung39efb7a2018-09-26 15:39:28 -07002915 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002916 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2917 // The output is pending reopened to query dynamic profiles and
2918 // there is no active clients
2919 closeOutput(outputDesc->mIoHandle);
2920 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2921 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2922 if (newOutputDesc == nullptr) {
2923 ALOGE("%s failed to open output", __func__);
2924 }
2925 return true;
2926 }
2927 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002928}
2929
Atneya Nair25fbcf22024-11-19 19:53:23 -08002930base::expected<media::GetInputForAttrResponse, std::variant<binder::Status, AudioConfigBase>>
2931AudioPolicyManager::getInputForAttr(audio_attributes_t attributes,
2932 audio_io_handle_t requestedInput,
2933 audio_port_handle_t requestedDeviceId,
2934 audio_config_base_t config,
2935 audio_input_flags_t flags,
2936 audio_unique_id_t riid,
2937 audio_session_t session,
Atneya Nairfda90e82024-11-19 19:55:25 -08002938 const AttributionSourceState& attributionSource)
Eric Laurente552edb2014-03-10 17:42:56 -07002939{
François Gaffiec005e562018-11-06 15:04:49 +01002940 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002941 "flags %#x attributes=%s requested device ID %d",
Atneya Nair25fbcf22024-11-19 19:53:23 -08002942 __func__, attributes.source, config.sample_rate, config.format, config.channel_mask,
2943 session, flags, toString(attributes).c_str(), requestedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002944
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002945 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002946 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002947 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002948 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949 sp<RecordClientDescriptor> clientDesc;
Atneya Nair25fbcf22024-11-19 19:53:23 -08002950 uid_t uid = static_cast<uid_t>(attributionSource.uid);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 bool isSoundTrigger;
Atneya Nair25fbcf22024-11-19 19:53:23 -08002952 int vdi = 0 /* default device id */;
2953 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954
Atneya Nair25fbcf22024-11-19 19:53:23 -08002955 if (attributes.source == AUDIO_SOURCE_DEFAULT) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002956 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002957 }
2958
Atneya Nairfda90e82024-11-19 19:55:25 -08002959 using PermissionReqs = AudioPolicyClientInterface::PermissionReqs;
2960 using MixType = AudioPolicyClientInterface::MixType;
2961 PermissionReqs permReq {
2962 .source = legacy2aidl_audio_source_t_AudioSource(attributes.source).value(),
2963 .mixType = MixType::NONE, // can be modified
2964 .virtualDeviceId = 0, // can be modified
2965 .isHotword = (flags & (AUDIO_INPUT_FLAG_HW_HOTWORD | AUDIO_INPUT_FLAG_HOTWORD_TAP |
2966 AUDIO_INPUT_FLAG_HW_LOOKBACK)) != 0,
2967 .isCallRedir = (attributes.flags & AUDIO_FLAG_CALL_REDIRECTION) != 0,
2968 };
2969
Paul McLean466dc8e2015-04-17 13:15:36 -06002970 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002971 sp<DeviceDescriptor> explicitRoutingDevice =
Atneya Nair25fbcf22024-11-19 19:53:23 -08002972 mAvailableInputDevices.getDeviceFromId(requestedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002973
Eric Laurentad2e7b92017-09-14 20:06:42 -07002974 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2975 // possible
2976 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
Atneya Nair25fbcf22024-11-19 19:53:23 -08002977 requestedInput != AUDIO_IO_HANDLE_NONE) {
2978 input = requestedInput;
2979 ssize_t index = mInputs.indexOfKey(requestedInput);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002980 if (index < 0) {
Atneya Nair25fbcf22024-11-19 19:53:23 -08002981 return base::unexpected{Status::fromExceptionCode(
2982 EX_ILLEGAL_ARGUMENT,
2983 String8::format("%s unknown MMAP input %d", __func__, requestedInput))};
Eric Laurentad2e7b92017-09-14 20:06:42 -07002984 }
2985 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002986 RecordClientVector clients = inputDesc->getClientsForSession(session);
2987 if (clients.size() == 0) {
Atneya Nair25fbcf22024-11-19 19:53:23 -08002988 return base::unexpected{Status::fromExceptionCode(
2989 EX_ILLEGAL_ARGUMENT, String8::format("%s unknown session %d on input %d",
2990 __func__, session, requestedInput))};
Eric Laurentad2e7b92017-09-14 20:06:42 -07002991 }
2992 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2993 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002994 // corresponds to a new client and is only permitted from the same UID.
2995 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002996 if (clients.size() > 1) {
2997 for (const auto& client : clients) {
2998 // The client map is ordered by key values (portId) and portIds are allocated
2999 // incrementaly. So the first client in this list is the one opened by audio flinger
3000 // when the mmap stream is created and should be ignored as it does not correspond
3001 // to an actual client
3002 if (client == *clients.cbegin()) {
3003 continue;
3004 }
3005 if (uid != client->uid() && !client->isSilenced()) {
Atneya Nair25fbcf22024-11-19 19:53:23 -08003006 return base::unexpected{Status::fromExceptionCode(
3007 EX_ILLEGAL_STATE,
3008 String8::format("%s bad uid %d for client %d uid %d", __func__, uid,
3009 client->portId(), client->uid()))};
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010 }
Eric Laurent331679c2018-04-16 17:03:16 -07003011 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 }
François Gaffie11d30102018-11-02 16:09:09 +01003013 device = inputDesc->getDevice();
Atneya Nair25fbcf22024-11-19 19:53:23 -08003014 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, requestedInput, session);
Eric Laurent275e8e92014-11-30 15:14:47 -08003015 } else {
Atneya Nair25fbcf22024-11-19 19:53:23 -08003016 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
3017 extractAddressFromAudioAttributes(attributes).has_value()) {
3018 status_t status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
3019 if (status != NO_ERROR) {
3020 ALOGW("%s could not find input mix for attr %s",
3021 __func__, toString(attributes).c_str());
3022 return base::unexpected {aidl_utils::binderStatusFromStatusT(status)};
3023 }
3024 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3025 String8(attributes.tags + strlen("addr=")),
3026 AUDIO_FORMAT_DEFAULT);
3027 if (device == nullptr) {
3028 return base::unexpected{Status::fromExceptionCode(
3029 EX_ILLEGAL_ARGUMENT,
3030 String8::format(
3031 "%s could not find in Remote Submix device for source %d, tags %s",
3032 __func__, attributes.source, attributes.tags))};
3033 }
3034
3035 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003036 permReq.mixType = MixType::PUBLIC_CAPTURE_PLAYBACK;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003037 } else {
Atneya Nairfda90e82024-11-19 19:55:25 -08003038 permReq.mixType = MixType::EXT_POLICY_REROUTE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003039 }
3040 // TODO is this correct?
Atneya Nairfda90e82024-11-19 19:55:25 -08003041 permReq.virtualDeviceId = policyMix->mVirtualDeviceId;
Eric Laurent97ac8712018-07-27 18:59:02 -07003042 } else {
Atneya Nair25fbcf22024-11-19 19:53:23 -08003043 if (explicitRoutingDevice != nullptr) {
3044 device = explicitRoutingDevice;
3045 } else {
3046 // Prevent from storing invalid requested device id in clients
3047 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
3048 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
3049 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3050 __FUNCTION__, device->type());
Marvin Ramine5a122d2023-12-07 13:57:59 +01003051 }
Atneya Nair25fbcf22024-11-19 19:53:23 -08003052 if (device == nullptr) {
3053 return base::unexpected{Status::fromExceptionCode(
3054 EX_ILLEGAL_ARGUMENT,
3055 String8::format("%s could not find device for source %d", __func__,
3056 attributes.source))};
3057 }
3058 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003059 permReq.mixType = MixType::CAPTURE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003060 } else if (policyMix) {
3061 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3062 // there is an external policy, but this input is attached to a mix of recorders,
3063 // meaning it receives audio injected into the framework, so the recorder doesn't
3064 // know about it and is therefore considered "legacy"
Atneya Nairfda90e82024-11-19 19:55:25 -08003065 permReq.mixType = MixType::NONE;
3066 permReq.virtualDeviceId = policyMix->mVirtualDeviceId;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003067 } else if (audio_is_remote_submix_device(device->type())) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003068 permReq.mixType = MixType::CAPTURE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003069 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Atneya Nairfda90e82024-11-19 19:55:25 -08003070 permReq.mixType = MixType::TELEPHONY_RX_CAPTURE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003071 } else {
Atneya Nairfda90e82024-11-19 19:55:25 -08003072 permReq.mixType = MixType::NONE;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003073 }
Eric Laurentc722f302014-12-10 11:21:49 -08003074 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003075
Atneya Nairfda90e82024-11-19 19:55:25 -08003076 auto permRes = mpClientInterface->checkPermissionForInput(attributionSource, permReq);
3077 if (!permRes.has_value()) return base::unexpected {permRes.error()};
3078 if (!permRes.value()) {
3079 return base::unexpected{Status::fromExceptionCode(
3080 EX_SECURITY, String8::format("%s: %s missing perms for source %d mix %d vdi %d"
3081 "hotword? %d callredir? %d", __func__, attributionSource.toString().c_str(),
3082 static_cast<int>(permReq.source),
3083 static_cast<int>(permReq.mixType),
3084 permReq.virtualDeviceId,
3085 permReq.isHotword,
3086 permReq.isCallRedir))};
3087 }
Atneya Nair25fbcf22024-11-19 19:53:23 -08003088
3089 input = getInputForDevice(device, session, attributes, config, flags, policyMix);
3090 if (input == AUDIO_IO_HANDLE_NONE) {
3091 AudioProfileVector profiles;
3092 status_t ret = getProfilesForDevices(
3093 DeviceVector(device), profiles, flags, true /*isInput*/);
3094 if (ret == NO_ERROR && !profiles.empty()) {
3095 const auto channels = profiles[0]->getChannels();
3096 if (!channels.empty() && (channels.find(config.channel_mask) == channels.end())) {
3097 config.channel_mask = *channels.begin();
3098 }
3099 const auto sampleRates = profiles[0]->getSampleRates();
3100 if (!sampleRates.empty() &&
3101 (sampleRates.find(config.sample_rate) == sampleRates.end())) {
3102 config.sample_rate = *sampleRates.begin();
3103 }
3104 config.format = profiles[0]->getFormat();
3105 }
3106 const auto suggestedConfig = VALUE_OR_FATAL(
3107 legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/));
3108 return base::unexpected {suggestedConfig};
3109 }
Eric Laurent599c7582015-12-07 18:05:55 -08003110 }
3111
Atneya Nair25fbcf22024-11-19 19:53:23 -08003112 auto selectedDeviceId = mAvailableInputDevices.contains(device) ?
François Gaffiec005e562018-11-06 15:04:49 +01003113 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003114
Francois Gaffie716e1432019-01-14 16:58:59 +01003115 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003116 mSoundTriggerSessions.indexOfKey(session) >= 0;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003117
Atneya Nair25fbcf22024-11-19 19:53:23 -08003118 const auto allocatedPortId = PolicyAudioPort::getNextUniqueId();
3119
3120 clientDesc = new RecordClientDescriptor(allocatedPortId, riid, uid, session, attributes, config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003121 requestedDeviceId, attributes.source, flags,
3122 isSoundTrigger);
Atneya Nair25fbcf22024-11-19 19:53:23 -08003123 inputDesc = mInputs.valueFor(input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003124 // Move (if found) effect for the client session to its input
Atneya Nair25fbcf22024-11-19 19:53:23 -08003125 mEffects.moveEffectsForIo(session, input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003126 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003127
Atneya Nairfda90e82024-11-19 19:55:25 -08003128 ALOGV("getInputForAttr() returns input %d selectedDeviceId %d vdi %d for port ID %d",
3129 input, selectedDeviceId, permReq.virtualDeviceId, allocatedPortId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003130
Atneya Nair25fbcf22024-11-19 19:53:23 -08003131 auto ret = media::GetInputForAttrResponse {};
3132 ret.input = input;
3133 ret.selectedDeviceId = selectedDeviceId;
3134 ret.portId = allocatedPortId;
Atneya Nairfda90e82024-11-19 19:55:25 -08003135 ret.virtualDeviceId = permReq.virtualDeviceId;
Atneya Nair25fbcf22024-11-19 19:53:23 -08003136 ret.config = legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/).value();
3137 return ret;
Eric Laurent599c7582015-12-07 18:05:55 -08003138}
3139
Atneya Nair25fbcf22024-11-19 19:53:23 -08003140audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent599c7582015-12-07 18:05:55 -08003141 audio_session_t session,
Atneya Nair25fbcf22024-11-19 19:53:23 -08003142 const audio_attributes_t& attributes,
3143 const audio_config_base_t& config,
Eric Laurent599c7582015-12-07 18:05:55 -08003144 audio_input_flags_t flags,
Atneya Nair25fbcf22024-11-19 19:53:23 -08003145 const sp<AudioPolicyMix>& policyMix) {
Eric Laurent599c7582015-12-07 18:05:55 -08003146 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003147 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003148 bool isSoundTrigger = false;
3149
François Gaffiec005e562018-11-06 15:04:49 +01003150 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003151 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3152 if (index >= 0) {
3153 input = mSoundTriggerSessions.valueFor(session);
3154 isSoundTrigger = true;
3155 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3156 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3157 } else {
3158 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003159 }
François Gaffiec005e562018-11-06 15:04:49 +01003160 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Atneya Nair25fbcf22024-11-19 19:53:23 -08003161 audio_is_linear_pcm(config.format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003162 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003163 }
3164
Carter Hsua3abb402021-10-26 11:11:20 +08003165 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3166 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3167 }
3168
Eric Laurentfe231122017-11-17 17:48:06 -08003169 // sampling rate and flags may be updated by getInputProfile
Atneya Nair25fbcf22024-11-19 19:53:23 -08003170 uint32_t profileSamplingRate = (config.sample_rate == 0) ?
3171 SAMPLE_RATE_HZ_DEFAULT : config.sample_rate;
3172 audio_format_t profileFormat = config.format;
3173 audio_channel_mask_t profileChannelMask = config.channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003174 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003175 // find a compatible input profile (not necessarily identical in parameters)
3176 sp<IOProfile> profile = getInputProfile(
3177 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3178 if (profile == nullptr) {
3179 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003180 }
jiabin2fd710d2022-05-02 23:20:22 +00003181
Glenn Kasten05ddca52016-02-11 08:17:12 -08003182 // Pick input sampling rate if not specified by client
Atneya Nair25fbcf22024-11-19 19:53:23 -08003183 uint32_t samplingRate = config.sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003184 if (samplingRate == 0) {
3185 samplingRate = profileSamplingRate;
3186 }
Eric Laurente552edb2014-03-10 17:42:56 -07003187
Eric Laurent322b4d22015-04-03 15:57:54 -07003188 if (profile->getModuleHandle() == 0) {
3189 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003190 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003191 }
3192
Eric Laurentec376dc2021-04-08 20:41:22 +02003193 // Reuse an already opened input if a client with the same session ID already exists
3194 // on that input
3195 for (size_t i = 0; i < mInputs.size(); i++) {
3196 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3197 if (desc->mProfile != profile) {
3198 continue;
3199 }
3200 RecordClientVector clients = desc->clientsList();
3201 for (const auto &client : clients) {
3202 if (session == client->session()) {
3203 return desc->mIoHandle;
3204 }
3205 }
3206 }
3207
Eric Laurentc71b11b2024-06-03 12:54:53 +00003208 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003209 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003210 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3211 // First pick best candidate for preemption (there may not be any):
3212 // - Preempt and input if:
3213 // - It has only strictly lower priority use cases than the new client
3214 // - It has equal priority use cases than the new client, was not
3215 // opened thanks to preemption or has been active since opened.
3216 // - Order the preemption candidates by inactive first and priority second
3217 sp<AudioInputDescriptor> closeCandidate;
3218 int leastCloseRank = INT_MAX;
3219 static const int sCloseActive = 0x100;
3220
3221 for (size_t i = 0; i < mInputs.size(); i++) {
3222 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3223 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003224 continue;
3225 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003226 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3227 if (topPrioClient == nullptr) {
3228 continue;
3229 }
3230 int topPrio = source_priority(topPrioClient->source());
3231 if (topPrio < source_priority(attributes.source)
3232 || (topPrio == source_priority(attributes.source)
3233 && !desc->isPreemptor())) {
3234 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3235 if (closeRank < leastCloseRank) {
3236 leastCloseRank = closeRank;
3237 closeCandidate = desc;
3238 }
3239 }
3240 }
3241
3242 if (closeCandidate != nullptr) {
3243 closeInput(closeCandidate->mIoHandle);
3244 // Mark the new input as being issued from a preemption
3245 // so that is will not be preempted later
3246 isPreemptor = true;
3247 } else {
3248 // Then pick the best reusable input (There is always one)
3249 // The order of preference is:
3250 // 1) active inputs with same use case as the new client
3251 // 2) inactive inputs with same use case
3252 // 3) active inputs with different use cases
3253 // 4) inactive inputs with different use cases
3254 sp<AudioInputDescriptor> reuseCandidate;
3255 int leastReuseRank = INT_MAX;
3256 static const int sReuseDifferentUseCase = 0x100;
3257
3258 for (size_t i = 0; i < mInputs.size(); i++) {
3259 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3260 if (desc->mProfile != profile) {
3261 continue;
3262 }
3263 int reuseRank = sReuseDifferentUseCase;
3264 for (const auto& client: desc->getClientIterable()) {
3265 if (client->source() == attributes.source) {
3266 reuseRank = 0;
3267 break;
3268 }
3269 }
3270 reuseRank += desc->isActive() ? 0 : 1;
3271 if (reuseRank < leastReuseRank) {
3272 leastReuseRank = reuseRank;
3273 reuseCandidate = desc;
3274 }
3275 }
3276 return reuseCandidate->mIoHandle;
3277 }
3278 } else { // fix_input_sharing_logic()
3279 for (size_t i = 0; i < mInputs.size(); ) {
3280 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3281 if (desc->mProfile != profile) {
3282 i++;
3283 continue;
3284 }
3285 // if sound trigger, reuse input if used by other sound trigger on same session
3286 // else
3287 // reuse input if active client app is not in IDLE state
3288 //
3289 RecordClientVector clients = desc->clientsList();
3290 bool doClose = false;
3291 for (const auto& client : clients) {
3292 if (isSoundTrigger != client->isSoundTrigger()) {
3293 continue;
3294 }
3295 if (client->isSoundTrigger()) {
3296 if (session == client->session()) {
3297 return desc->mIoHandle;
3298 }
3299 continue;
3300 }
3301 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003302 return desc->mIoHandle;
3303 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003304 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003305 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003306 if (doClose) {
3307 closeInput(desc->mIoHandle);
3308 } else {
3309 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003310 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003311 }
3312 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003313 }
3314
Eric Laurentc71b11b2024-06-03 12:54:53 +00003315 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3316 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003317
Eric Laurentfe231122017-11-17 17:48:06 -08003318 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3319 lConfig.sample_rate = profileSamplingRate;
3320 lConfig.channel_mask = profileChannelMask;
3321 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003322
François Gaffie11d30102018-11-02 16:09:09 +01003323 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003324
3325 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003326 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003327 (profileSamplingRate != lConfig.sample_rate) ||
3328 !audio_formats_match(profileFormat, lConfig.format) ||
3329 (profileChannelMask != lConfig.channel_mask)) {
3330 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003331 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003332 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003333 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003334 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003335 }
Eric Laurent599c7582015-12-07 18:05:55 -08003336 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003337 }
3338
Eric Laurentc722f302014-12-10 11:21:49 -08003339 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003340
Eric Laurent599c7582015-12-07 18:05:55 -08003341 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003342 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003343
Eric Laurent599c7582015-12-07 18:05:55 -08003344 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003345}
3346
Eric Laurent4eb58f12018-12-07 16:41:02 -08003347status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003348{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349 ALOGV("%s portId %d", __FUNCTION__, portId);
3350
3351 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3352 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003353 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003354 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003355 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003356 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003357 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003358 if (client->active()) {
3359 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3360 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003361 }
3362
Eric Laurent8f42ea12018-08-08 09:08:25 -07003363 audio_session_t session = client->session();
3364
Eric Laurent4eb58f12018-12-07 16:41:02 -08003365 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003366
Eric Laurent4eb58f12018-12-07 16:41:02 -08003367 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003368
Eric Laurent4eb58f12018-12-07 16:41:02 -08003369 status_t status = inputDesc->start();
3370 if (status != NO_ERROR) {
3371 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003372 }
Eric Laurente552edb2014-03-10 17:42:56 -07003373
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003374 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003375 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003376 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003377
Eric Laurent8f42ea12018-08-08 09:08:25 -07003378 // indicate active capture to sound trigger service if starting capture from a mic on
3379 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003380 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003381 if (device != nullptr) {
3382 status = setInputDevice(input, device, true /* force */);
3383 } else {
3384 ALOGW("%s no new input device can be found for descriptor %d",
3385 __FUNCTION__, inputDesc->getId());
3386 status = BAD_VALUE;
3387 }
Eric Laurente552edb2014-03-10 17:42:56 -07003388
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003389 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003390 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003391 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003392 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003393 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3394 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003395 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003396 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003397
François Gaffie11d30102018-11-02 16:09:09 +01003398 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3399 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003400 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003401 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003402 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003403
Eric Laurent8f42ea12018-08-08 09:08:25 -07003404 // automatically enable the remote submix output when input is started if not
3405 // used by a policy mix of type MIX_TYPE_RECORDERS
3406 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003407 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003409 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003410 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003411 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3412 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003413 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003414 if (address != "") {
3415 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3416 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003417 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003418 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003419 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003420 } else if (status != NO_ERROR) {
3421 // Restore client activity state.
3422 inputDesc->setClientActive(client, false);
3423 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003424 }
3425
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003426 ALOGV("%s input %d source = %d status = %d exit",
3427 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003428
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003429 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003430}
3431
Eric Laurent8fc147b2018-07-22 19:13:55 -07003432status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003433{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003434 ALOGV("%s portId %d", __FUNCTION__, portId);
3435
3436 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3437 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003438 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00003439 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07003440 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003441 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003442 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003443 if (!client->active()) {
3444 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003445 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003446 }
Carter Hsue6139d52021-07-08 10:30:20 +08003447 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003448 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003449
Eric Laurent8f42ea12018-08-08 09:08:25 -07003450 inputDesc->stop();
3451 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003452 auto current_source = inputDesc->source();
3453 setInputDevice(input, getNewInputDevice(inputDesc),
3454 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003455 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003456 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003458 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003459 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3460 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003461 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003462 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003463
3464 // automatically disable the remote submix output when input is stopped if not
3465 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003466 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003467 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003468 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003469 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003470 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3471 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003472 }
3473 if (address != "") {
3474 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3475 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003476 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003477 }
3478 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003479 resetInputDevice(input);
3480
3481 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3482 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003483 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3484 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003485 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003486 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003487 }
3488 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003489 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003490 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003491}
3492
Eric Laurent8fc147b2018-07-22 19:13:55 -07003493void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003494{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003495 ALOGV("%s portId %d", __FUNCTION__, portId);
3496
3497 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3498 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003499 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003500 return;
3501 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003502 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003503 audio_io_handle_t input = inputDesc->mIoHandle;
3504
Eric Laurent8f42ea12018-08-08 09:08:25 -07003505 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003506
Andy Hung39efb7a2018-09-26 15:39:28 -07003507 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003508
3509 // If no more clients are present in this session, park effects to an orphan chain
3510 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3511 if (clientsOnSession.size() == 0) {
3512 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3513 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003514 if (inputDesc->getClientCount() > 0) {
3515 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003516 return;
3517 }
3518
Eric Laurent05b90f82014-08-27 15:32:29 -07003519 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003520 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003521 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003522}
3523
Eric Laurent8f42ea12018-08-08 09:08:25 -07003524void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003525{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003526 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003527
3528 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003529 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003530 }
3531}
3532
Eric Laurent8f42ea12018-08-08 09:08:25 -07003533void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3534{
3535 stopInput(portId);
3536 releaseInput(portId);
3537}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003538
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003539bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3540 if (input->clientsList().size() == 0
3541 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3542 return true;
3543 }
3544 for (const auto& client : input->clientsList()) {
3545 sp<DeviceDescriptor> device =
3546 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3547 client->session());
3548 if (!input->supportedDevices().contains(device)) {
3549 return true;
3550 }
3551 }
3552 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3553 return false;
3554}
3555
Eric Laurent0dd51852019-04-19 18:18:58 -07003556void AudioPolicyManager::checkCloseInputs() {
3557 // After connecting or disconnecting an input device, close input if:
3558 // - it has no client (was just opened to check profile) OR
3559 // - none of its supported devices are connected anymore OR
3560 // - one of its clients cannot be routed to one of its supported
3561 // devices anymore. Otherwise update device selection
3562 std::vector<audio_io_handle_t> inputsToClose;
3563 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003564 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003565 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003566 }
3567 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003568 for (const audio_io_handle_t handle : inputsToClose) {
3569 ALOGV("%s closing input %d", __func__, handle);
3570 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003571 }
Eric Laurentd4692962014-05-05 18:13:44 -07003572}
3573
Vlad Popa87e0e582024-05-20 18:49:20 -07003574status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3575 const char *address __unused,
3576 bool enabled,
3577 audio_stream_type_t streamToDriveAbs)
3578{
Vlad Popa08502d82024-10-22 20:17:47 -07003579 ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3580 streamToDriveAbs);
3581
Vlad Popa6319b2d2024-11-15 18:32:13 -08003582 bool changed = false;
Neha Jain7af15132024-11-16 00:47:18 +00003583 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
Vlad Popa6319b2d2024-11-15 18:32:13 -08003584 if (enabled) {
3585 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3586 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3587 toString(streamToDriveAbs).c_str());
3588 return BAD_VALUE;
3589 }
3590
Vlad Popa3d8d8942024-11-19 21:04:31 -08003591 const auto attrIt = mAbsoluteVolumeDrivingStreams.find(deviceType);
3592 if (attrIt == mAbsoluteVolumeDrivingStreams.end() ||
3593 (attrIt->second.usage != attributesToDriveAbs.usage ||
3594 attrIt->second.content_type != attributesToDriveAbs.content_type ||
3595 attrIt->second.flags != attributesToDriveAbs.flags)) {
Vlad Popa6319b2d2024-11-15 18:32:13 -08003596 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3597 changed = true;
3598 }
3599 } else {
Vlad Popa3d8d8942024-11-19 21:04:31 -08003600 if (mAbsoluteVolumeDrivingStreams.erase(deviceType) != 0) {
Vlad Popa6319b2d2024-11-15 18:32:13 -08003601 changed = true;
3602 }
Vlad Popafb0af7c2024-10-29 16:38:37 -07003603 }
3604
Vlad Popa3d8d8942024-11-19 21:04:31 -08003605 const DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3606 attributesToDriveAbs, nullptr /* preferredDevice */, true /* fromCache */);
3607 changed &= devices.types().contains(deviceType);
3608 // if something changed on the output device for the changed attributes, apply the stream
3609 // volumes regarding the new absolute mode to all the outputs without any delay
Vlad Popa6319b2d2024-11-15 18:32:13 -08003610 if (changed) {
3611 for (size_t i = 0; i < mOutputs.size(); i++) {
3612 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa3d8d8942024-11-19 21:04:31 -08003613 ALOGI("%s: apply stream volumes for portId %d and device type %d", __func__,
3614 desc->getId(), deviceType);
Vlad Popa6319b2d2024-11-15 18:32:13 -08003615 applyStreamVolumes(desc, {deviceType});
3616 }
3617 }
3618
Vlad Popa87e0e582024-05-20 18:49:20 -07003619 return NO_ERROR;
3620}
3621
François Gaffie251c7f02018-11-07 10:41:08 +01003622void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003623{
3624 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003625 if (indexMin < 0 || indexMax < 0) {
3626 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3627 return;
3628 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003629 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003630
3631 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003632 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3633 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003634 continue;
3635 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003636 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003637 }
Eric Laurente552edb2014-03-10 17:42:56 -07003638}
3639
Eric Laurente0720872014-03-11 09:30:41 -07003640status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003641 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003642 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003643 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003644{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003645 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003646 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3647 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3648 return NO_ERROR;
3649 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303650 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3651 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003652 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003653}
3654
Eric Laurente0720872014-03-11 09:30:41 -07003655status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003656 int *index,
3657 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003658{
François Gaffiec005e562018-11-06 15:04:49 +01003659 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3660 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003661 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003662 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003663 deviceTypes = mEngine->getOutputDevicesForStream(
3664 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003665 }
jiabin9a3361e2019-10-01 09:38:30 -07003666 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003667}
3668
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003669status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003670 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003671 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003672 audio_devices_t device)
3673{
3674 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003675 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3676 if (group == VOLUME_GROUP_NONE) {
3677 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003678 return BAD_VALUE;
3679 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003680 ALOGV("%s: group %d matching with %s index %d",
3681 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003682 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3683 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3684 __FUNCTION__, toString(attributes).c_str());
3685 return NO_ERROR;
3686 }
François Gaffiecfe17322018-11-07 13:41:29 +01003687 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003688 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003689 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003690 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3691 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3692 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3693 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003694 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3695
Vlad Popa1e865e62024-08-15 19:11:42 -07003696
3697 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003698 if (status != NO_ERROR) {
3699 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3700 return status;
3701 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003702
jiabin9a3361e2019-10-01 09:38:30 -07003703 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003704 auto curCurvAttrs = curves.getAttributes();
3705 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3706 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003707 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003708 } else if (!curves.getStreamTypes().empty()) {
3709 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003710 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003711 } else {
3712 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3713 return BAD_VALUE;
3714 }
jiabin9a3361e2019-10-01 09:38:30 -07003715 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3716 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003717
François Gaffiecfe17322018-11-07 13:41:29 +01003718 // update volume on all outputs and streams matching the following:
3719 // - The requested stream (or a stream matching for volume control) is active on the output
3720 // - The device (or devices) selected by the engine for this stream includes
3721 // the requested device
3722 // - For non default requested device, currently selected device on the output is either the
3723 // requested device or one of the devices selected by the engine for this stream
3724 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3725 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003726 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003727 for (size_t i = 0; i < mOutputs.size(); i++) {
3728 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003729 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003730
jiabin9a3361e2019-10-01 09:38:30 -07003731 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3732 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003733 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003734
3735 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003736 continue;
3737 }
3738 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3739 curDevices.find(device) == curDevices.end()) {
3740 continue;
3741 }
3742 bool applyVolume = false;
3743 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3744 curSrcDevices.insert(device);
3745 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003746 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3747 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003748 } else {
3749 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3750 }
3751 if (!applyVolume) {
3752 continue; // next output
3753 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003754 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3755 // If a higher priority strategy is active, and the output is routed to a device with a
3756 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003757 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003758 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003759 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003760 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003761 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003762 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3763 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3764 false /*preferredDevice*/);
3765 if (activeClients.empty()) {
3766 continue;
3767 }
3768 bool isPreempted = false;
3769 bool isHigherPriority = productStrategy < strategy;
3770 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003771 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003772 ALOGV("%s: Strategy=%d (\nrequester:\n"
3773 " group %d, volumeGroup=%d attributes=%s)\n"
3774 " higher priority source active:\n"
3775 " volumeGroup=%d attributes=%s) \n"
3776 " on output %zu, bailing out", __func__, productStrategy,
3777 group, group, toString(attributes).c_str(),
3778 client->volumeSource(), toString(client->attributes()).c_str(), i);
3779 applyVolume = false;
3780 isPreempted = true;
3781 break;
3782 }
3783 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003784 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003785 applyVolume = true;
3786 }
3787 }
3788 if (isPreempted || applyVolume) {
3789 break;
3790 }
3791 }
3792 if (!applyVolume) {
3793 continue; // next output
3794 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003795 }
François Gaffieed91f582020-01-31 10:35:37 +01003796 //FIXME: workaround for truncated touch sounds
3797 // delayed volume change for system stream to be removed when the problem is
3798 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003799 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003800 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003801 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3802 if (volStatus != NO_ERROR) {
3803 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003804 }
3805 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003806
3807 // update voice volume if the an active call route exists
3808 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3809 && (curSrcDevices.find(
3810 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3811 != curSrcDevices.end())) {
3812 bool isVoiceVolSrc;
3813 bool isBtScoVolSrc;
3814 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3815 isVoiceVolSrc, isBtScoVolSrc, __func__)
3816 && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08003817 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08003818 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3819 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003820 }
3821 }
3822
François Gaffiecfe17322018-11-07 13:41:29 +01003823 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3824 return status;
3825}
3826
François Gaffieaaac0fd2018-11-22 17:56:39 +01003827status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003828 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003829 audio_devices_t device,
3830 IVolumeCurves &volumeCurves)
3831{
3832 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3833 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003834 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3835 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003836 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303837 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3838 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003839 return BAD_VALUE;
3840 }
3841 if (!audio_is_output_device(device)) {
3842 return BAD_VALUE;
3843 }
3844
3845 // Force max volume if stream cannot be muted
3846 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3847
Vlad Popa1e865e62024-08-15 19:11:42 -07003848 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003849 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003850 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003851 return NO_ERROR;
3852}
3853
3854status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3855 int &index,
3856 audio_devices_t device)
3857{
3858 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3859 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003860 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003861 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003862 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003863 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003864 }
jiabin9a3361e2019-10-01 09:38:30 -07003865 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003866}
3867
3868status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3869 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003870 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003871{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003872 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003873 return BAD_VALUE;
3874 }
jiabin9a3361e2019-10-01 09:38:30 -07003875 index = curves.getVolumeIndex(deviceTypes);
3876 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003877 return NO_ERROR;
3878}
3879
3880status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3881 int &index)
3882{
3883 index = getVolumeCurves(attr).getVolumeIndexMin();
3884 return NO_ERROR;
3885}
3886
3887status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3888 int &index)
3889{
3890 index = getVolumeCurves(attr).getVolumeIndexMax();
3891 return NO_ERROR;
3892}
3893
Eric Laurent36829f92017-04-07 19:04:42 -07003894audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003895{
3896 // select one output among several suitable for global effects.
3897 // The priority is as follows:
3898 // 1: An offloaded output. If the effect ends up not being offloadable,
3899 // AudioFlinger will invalidate the track and the offloaded output
3900 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003901 // 2: Spatializer output if the stereo spatializer feature enabled
3902 // 3: A deep buffer output
3903 // 4: The primary output
3904 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003905
François Gaffiec005e562018-11-06 15:04:49 +01003906 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3907 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003908 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003909
Eric Laurent36829f92017-04-07 19:04:42 -07003910 if (outputs.size() == 0) {
3911 return AUDIO_IO_HANDLE_NONE;
3912 }
Eric Laurente552edb2014-03-10 17:42:56 -07003913
Eric Laurent36829f92017-04-07 19:04:42 -07003914 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3915 bool activeOnly = true;
3916
3917 while (output == AUDIO_IO_HANDLE_NONE) {
3918 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003919 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003920 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3921 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3922
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003923 for (audio_io_handle_t outputLoop : outputs) {
3924 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003925 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003926 continue;
3927 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003928 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003929 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003930 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003931 outputOffloaded = outputLoop;
3932 }
3933 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3934 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3935 outputSpatializer = outputLoop;
3936 }
Eric Laurent36829f92017-04-07 19:04:42 -07003937 }
3938 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003939 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003940 }
3941 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003942 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003943 }
3944 }
3945 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3946 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003947 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3948 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003949 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3950 output = outputDeepBuffer;
3951 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3952 output = outputPrimary;
3953 } else {
3954 output = outputs[0];
3955 }
3956 activeOnly = false;
3957 }
3958
3959 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003960 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3961 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003962 mMusicEffectOutput = output;
3963 }
3964
3965 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003966 return output;
3967}
3968
Eric Laurent36829f92017-04-07 19:04:42 -07003969audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3970{
3971 return selectOutputForMusicEffects();
3972}
3973
Eric Laurente0720872014-03-11 09:30:41 -07003974status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003975 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003976 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003977 int session,
3978 int id)
3979{
Shunkai Yao29d10572024-03-19 04:31:47 +00003980 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003981 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003982 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003983 index = mInputs.indexOfKey(io);
3984 if (index < 0) {
3985 ALOGW("registerEffect() unknown io %d", io);
3986 return INVALID_OPERATION;
3987 }
Eric Laurente552edb2014-03-10 17:42:56 -07003988 }
3989 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003990 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3991 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3992 || strategy == PRODUCT_STRATEGY_NONE));
3993 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003994}
3995
Eric Laurentc241b0d2018-11-28 09:08:49 -08003996status_t AudioPolicyManager::unregisterEffect(int id)
3997{
3998 if (mEffects.getEffect(id) == nullptr) {
3999 return INVALID_OPERATION;
4000 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08004001 if (mEffects.isEffectEnabled(id)) {
4002 ALOGW("%s effect %d enabled", __FUNCTION__, id);
4003 setEffectEnabled(id, false);
4004 }
4005 return mEffects.unregisterEffect(id);
4006}
4007
4008status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
4009{
4010 sp<EffectDescriptor> effect = mEffects.getEffect(id);
4011 if (effect == nullptr) {
4012 return INVALID_OPERATION;
4013 }
4014
4015 status_t status = mEffects.setEffectEnabled(id, enabled);
4016 if (status == NO_ERROR) {
4017 mInputs.trackEffectEnabled(effect, enabled);
4018 }
4019 return status;
4020}
4021
Eric Laurent6c796322019-04-09 14:13:17 -07004022
4023status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
4024{
4025 mEffects.moveEffects(ids, io);
4026 return NO_ERROR;
4027}
4028
Eric Laurentc75307b2015-03-17 15:29:32 -07004029bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
4030{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004031 auto vs = toVolumeSource(stream, false);
4032 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004033}
4034
4035bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4036{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004037 auto vs = toVolumeSource(stream, false);
4038 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004039}
4040
Eric Laurente0720872014-03-11 09:30:41 -07004041bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004042{
4043 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004044 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004045 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004046 return true;
4047 }
4048 }
4049 return false;
4050}
4051
Eric Laurent275e8e92014-11-30 15:14:47 -08004052// Register a list of custom mixes with their attributes and format.
4053// When a mix is registered, corresponding input and output profiles are
4054// added to the remote submix hw module. The profile contains only the
4055// parameters (sampling rate, format...) specified by the mix.
4056// The corresponding input remote submix device is also connected.
4057//
4058// When a remote submix device is connected, the address is checked to select the
4059// appropriate profile and the corresponding input or output stream is opened.
4060//
4061// When capture starts, getInputForAttr() will:
4062// - 1 look for a mix matching the address passed in attribtutes tags if any
4063// - 2 if none found, getDeviceForInputSource() will:
4064// - 2.1 look for a mix matching the attributes source
4065// - 2.2 if none found, default to device selection by policy rules
4066// At this time, the corresponding output remote submix device is also connected
4067// and active playback use cases can be transferred to this mix if needed when reconnecting
4068// after AudioTracks are invalidated
4069//
4070// When playback starts, getOutputForAttr() will:
4071// - 1 look for a mix matching the address passed in attribtutes tags if any
4072// - 2 if none found, look for a mix matching the attributes usage
4073// - 3 if none found, default to device and output selection by policy rules.
4074
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004075status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004076{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004077 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4078 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004079 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004080 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004081 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004082 // examine each mix's route type
4083 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004084 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004085 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4086 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4087 ALOGE("Unsupported Policy Mix %zu of %zu: "
4088 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4089 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004090 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004091 break;
4092 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004093 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4094 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004095 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004096 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4097 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004098 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004099 rSubmixModule = mHwModules.getModuleFromName(
4100 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4101 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004102 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004103 i);
4104 res = INVALID_OPERATION;
4105 break;
4106 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004107 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004108
Eric Laurent97ac8712018-07-27 18:59:02 -07004109 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004110 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004111 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004112 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004113 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4114 } else {
4115 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4116 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004117 }
François Gaffie036e1e92015-03-19 10:16:24 +01004118
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004119 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004120 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004121 res = INVALID_OPERATION;
4122 break;
4123 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004124 audio_config_t outputConfig = mix.mFormat;
4125 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004126 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4127 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004128 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4129 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004130 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004131 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4132 audio_is_linear_pcm(outputConfig.format)
4133 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004134 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004135 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4136 audio_is_linear_pcm(inputConfig.format)
4137 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004138
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004139 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004140 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004141 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004142 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004143 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004144 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004145 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004146 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4147 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004148 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004149 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004150 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004151
4152 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4153 mix.mDeviceType, mix.mDeviceAddress,
4154 String8(), AUDIO_FORMAT_DEFAULT);
4155 if (device == nullptr) {
4156 res = INVALID_OPERATION;
4157 break;
4158 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004159
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004160 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004161 // First try to find an already opened output supporting the device
4162 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004163 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004164
Eric Laurentc529cf62020-04-17 18:19:10 -07004165 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004166 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004167 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004168 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004169 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004170 } else {
4171 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004172 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004173 }
4174 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004175 // If no output found, try to find a direct output profile supporting the device
4176 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4177 sp<HwModule> module = mHwModules[i];
4178 for (size_t j = 0;
4179 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4180 j++) {
4181 sp<IOProfile> profile = module->getOutputProfiles()[j];
4182 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4183 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4184 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004185 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004186 res = INVALID_OPERATION;
4187 } else {
4188 foundOutput = true;
4189 }
4190 }
4191 }
4192 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004193 if (res != NO_ERROR) {
4194 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004195 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004196 res = INVALID_OPERATION;
4197 break;
4198 } else if (!foundOutput) {
4199 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004200 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004201 res = INVALID_OPERATION;
4202 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004203 } else {
4204 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004205 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004206 }
Eric Laurentc722f302014-12-10 11:21:49 -08004207 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004208 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004209 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004210 if (audio_flags::audio_mix_ownership()) {
4211 // Only unregister mixes that were actually registered to not accidentally unregister
4212 // mixes that already existed previously.
4213 unregisterPolicyMixes(registeredMixes);
4214 registeredMixes.clear();
4215 } else {
4216 unregisterPolicyMixes(mixes);
4217 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004218 } else if (checkOutputs) {
4219 checkForDeviceAndOutputChanges();
4220 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004221 }
4222 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004223}
4224
4225status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4226{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004227 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004228 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004229 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004230 sp<HwModule> rSubmixModule;
4231 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004232 for (const auto& mix : mixes) {
4233 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004234
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004235 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004236 rSubmixModule = mHwModules.getModuleFromName(
4237 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4238 if (rSubmixModule == 0) {
4239 res = INVALID_OPERATION;
4240 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004241 }
4242 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004243
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004244 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004245
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004246 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004247 res = INVALID_OPERATION;
4248 continue;
4249 }
4250
Marvin Ramin0783e202024-03-05 12:45:50 +01004251 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004252 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004253 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4254 status_t currentRes =
4255 setDeviceConnectionStateInt(device,
4256 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4257 address.c_str(),
4258 "remote-submix",
4259 AUDIO_FORMAT_DEFAULT);
4260 if (!audio_flags::audio_mix_ownership()) {
4261 res = currentRes;
4262 }
4263 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004264 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004265 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004266 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004267 }
4268 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004269 }
jiabin5740f082019-08-19 15:08:30 -07004270 rSubmixModule->removeOutputProfile(address.c_str());
4271 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004272
Kevin Rocard153f92d2018-12-18 18:33:28 -08004273 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004274 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004275 res = INVALID_OPERATION;
4276 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004277 } else {
4278 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004279 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004280 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004281 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004282
4283 if (res == NO_ERROR && checkOutputs) {
4284 checkForDeviceAndOutputChanges();
4285 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004286 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004287 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004288}
4289
Marvin Raminbdefaf02023-11-01 09:10:32 +01004290status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4291 if (!audio_flags::audio_mix_test_api()) {
4292 return INVALID_OPERATION;
4293 }
4294
4295 _aidl_return.clear();
4296 _aidl_return.reserve(mPolicyMixes.size());
4297 for (const auto &policyMix: mPolicyMixes) {
4298 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4299 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4300 policyMix->mCbFlags);
4301 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004302 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004303 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004304 }
4305
Vlad Popaa5d73f32024-03-08 16:05:38 -08004306 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004307 return OK;
4308}
4309
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004310status_t AudioPolicyManager::updatePolicyMix(
4311 const AudioMix& mix,
4312 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4313 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4314 if (res == NO_ERROR) {
4315 checkForDeviceAndOutputChanges();
4316 updateCallAndOutputRouting();
4317 }
4318 return res;
4319}
4320
Mikhail Naganov100f0122018-11-29 11:22:16 -08004321void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4322{
4323 size_t i = 0;
4324 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4325 for (const auto& fmt : mManualSurroundFormats) {
4326 if (i++ != 0) dst->append(", ");
4327 std::string sfmt;
4328 FormatConverter::toString(fmt, sfmt);
4329 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4330 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4331 }
4332}
4333
Eric Laurentc529cf62020-04-17 18:19:10 -07004334// Returns true if all devices types match the predicate and are supported by one HW module
4335bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004336 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004337 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004338 const char *context,
4339 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004340 for (size_t i = 0; i < devices.size(); i++) {
4341 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004342 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004343 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004344 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004345 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004346 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004347 return false;
4348 }
4349 }
4350 return true;
4351}
4352
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004353void AudioPolicyManager::changeOutputDevicesMuteState(
4354 const AudioDeviceTypeAddrVector& devices) {
4355 ALOGVV("%s() num devices %zu", __func__, devices.size());
4356
4357 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4358 getSoftwareOutputsForDevices(devices);
4359
4360 for (size_t i = 0; i < outputs.size(); i++) {
4361 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4362 DeviceVector prevDevices = outputDesc->devices();
4363 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4364 }
4365}
4366
4367std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4368 const AudioDeviceTypeAddrVector& devices) const
4369{
4370 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4371 DeviceVector deviceDescriptors;
4372 for (size_t j = 0; j < devices.size(); j++) {
4373 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4374 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4375 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4376 ALOGE("%s: device type %#x address %s not supported or not an output device",
4377 __func__, devices[j].mType, devices[j].getAddress());
4378 continue;
4379 }
4380 deviceDescriptors.add(desc);
4381 }
4382 for (size_t i = 0; i < mOutputs.size(); i++) {
4383 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4384 continue;
4385 }
4386 outputs.push_back(mOutputs.valueAt(i));
4387 }
4388 return outputs;
4389}
4390
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004391status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004392 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004393 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004394 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4395 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004396 }
4397 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004398 if (res != NO_ERROR) {
4399 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4400 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004401 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004402
4403 checkForDeviceAndOutputChanges();
4404 updateCallAndOutputRouting();
4405
4406 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004407}
4408
4409status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4410 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004411 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4412 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004413 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004414 __FUNCTION__, uid);
4415 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004416 }
4417
Eric Laurentc529cf62020-04-17 18:19:10 -07004418 checkForDeviceAndOutputChanges();
4419 updateCallAndOutputRouting();
4420
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004421 return res;
4422}
4423
Eric Laurent2517af32020-11-25 15:31:27 +01004424
jiabin0a488932020-08-07 17:32:40 -07004425status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4426 device_role_t role,
4427 const AudioDeviceTypeAddrVector &devices) {
4428 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4429 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004430
Eric Laurentc529cf62020-04-17 18:19:10 -07004431 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004432 return BAD_VALUE;
4433 }
jiabin0a488932020-08-07 17:32:40 -07004434 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004435 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004436 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4437 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004438 return status;
4439 }
4440
4441 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004442
4443 bool forceVolumeReeval = false;
4444 // FIXME: workaround for truncated touch sounds
4445 // to be removed when the problem is handled by system UI
4446 uint32_t delayMs = 0;
4447 if (strategy == mCommunnicationStrategy) {
4448 forceVolumeReeval = true;
4449 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4450 updateInputRouting();
4451 }
4452 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004453
4454 return NO_ERROR;
4455}
4456
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004457void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4458 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004459{
4460 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004461 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004462 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004463 // Only apply special touch sound delay once
4464 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004465 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004466 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004467 for (size_t i = 0; i < mOutputs.size(); i++) {
4468 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4469 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004470 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4471 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004472 // As done in setDeviceConnectionState, we could also fix default device issue by
4473 // preventing the force re-routing in case of default dev that distinguishes on address.
4474 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004475 bool newDevicesNotEmpty = !newDevices.isEmpty();
4476 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4477 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004478 // If the device is using preferred mixer attributes, the output need to reopen
4479 // with default configuration when the new selected devices are different from
4480 // current routing devices.
4481 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4482 continue;
4483 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304484
jiabin2361ed82024-09-20 17:36:31 +00004485 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4486 newDevicesNotEmpty /*force*/, delayMs,
4487 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4488 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004489 // Only apply special touch sound delay once
4490 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004491 }
4492 if (forceVolumeReeval && !newDevices.isEmpty()) {
4493 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4494 }
4495 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004496 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004497 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004498}
4499
Eric Laurent2517af32020-11-25 15:31:27 +01004500void AudioPolicyManager::updateInputRouting() {
4501 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304502 // Skip for hotword recording as the input device switch
4503 // is handled within sound trigger HAL
4504 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4505 continue;
4506 }
Eric Laurent2517af32020-11-25 15:31:27 +01004507 auto newDevice = getNewInputDevice(activeDesc);
4508 // Force new input selection if the new device can not be reached via current input
4509 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4510 setInputDevice(activeDesc->mIoHandle, newDevice);
4511 } else {
4512 closeInput(activeDesc->mIoHandle);
4513 }
4514 }
4515}
4516
Paul Wang5d7cdb52022-11-22 09:45:06 +00004517status_t
4518AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4519 device_role_t role,
4520 const AudioDeviceTypeAddrVector &devices) {
4521 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4522 dumpAudioDeviceTypeAddrVector(devices).c_str());
4523
Eric Laurent78fedbf2023-03-09 14:40:44 +01004524 if (!areAllDevicesSupported(
4525 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004526 return BAD_VALUE;
4527 }
4528 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4529 if (status != NO_ERROR) {
4530 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4531 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4532 return status;
4533 }
4534
4535 checkForDeviceAndOutputChanges();
4536
4537 bool forceVolumeReeval = false;
4538 // TODO(b/263479999): workaround for truncated touch sounds
4539 // to be removed when the problem is handled by system UI
4540 uint32_t delayMs = 0;
4541 if (strategy == mCommunnicationStrategy) {
4542 forceVolumeReeval = true;
4543 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4544 updateInputRouting();
4545 }
4546 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4547
4548 return NO_ERROR;
4549}
4550
4551status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4552 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004553{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004554 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004555
Paul Wang5d7cdb52022-11-22 09:45:06 +00004556 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004557 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004558 ALOGW_IF(status != NAME_NOT_FOUND,
4559 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004560 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004561 return status;
4562 }
4563
4564 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004565
4566 bool forceVolumeReeval = false;
4567 // FIXME: workaround for truncated touch sounds
4568 // to be removed when the problem is handled by system UI
4569 uint32_t delayMs = 0;
4570 if (strategy == mCommunnicationStrategy) {
4571 forceVolumeReeval = true;
4572 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4573 updateInputRouting();
4574 }
4575 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004576
4577 return NO_ERROR;
4578}
4579
jiabin0a488932020-08-07 17:32:40 -07004580status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4581 device_role_t role,
4582 AudioDeviceTypeAddrVector &devices) {
4583 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004584}
4585
Jiabin Huang3b98d322020-09-03 17:54:16 +00004586status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4587 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4588 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4589 dumpAudioDeviceTypeAddrVector(devices).c_str());
4590
Mikhail Naganov55773032020-10-01 15:08:13 -07004591 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004592 return BAD_VALUE;
4593 }
4594 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4595 ALOGW_IF(status != NO_ERROR,
4596 "Engine could not set preferred devices %s for audio source %d role %d",
4597 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4598
Wenyu Zhang47655d22024-10-01 12:24:53 +00004599 if (status == NO_ERROR) {
4600 updateInputRouting();
4601 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004602 return status;
4603}
4604
4605status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4606 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4607 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4608 dumpAudioDeviceTypeAddrVector(devices).c_str());
4609
Mikhail Naganov55773032020-10-01 15:08:13 -07004610 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004611 return BAD_VALUE;
4612 }
4613 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4614 ALOGW_IF(status != NO_ERROR,
4615 "Engine could not add preferred devices %s for audio source %d role %d",
4616 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4617
Eric Laurent2517af32020-11-25 15:31:27 +01004618 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004619 return status;
4620}
4621
4622status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4623 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4624{
4625 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4626 dumpAudioDeviceTypeAddrVector(devices).c_str());
4627
Eric Laurent78fedbf2023-03-09 14:40:44 +01004628 if (!areAllDevicesSupported(
4629 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004630 return BAD_VALUE;
4631 }
4632
4633 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4634 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004635 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004636 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004637 if (status == NO_ERROR) {
4638 updateInputRouting();
4639 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004640 return status;
4641}
4642
4643status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4644 device_role_t role) {
4645 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4646
4647 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004648 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004649 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004650 if (status == NO_ERROR) {
4651 updateInputRouting();
4652 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004653 return status;
4654}
4655
4656status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4657 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4658 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4659}
4660
Oscar Azucena90e77632019-11-27 17:12:28 -08004661status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004662 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004663 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004664 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4665 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004666 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004667 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4668 if (status != NO_ERROR) {
4669 ALOGE("%s() could not set device affinity for userId %d",
4670 __FUNCTION__, userId);
4671 return status;
4672 }
4673
4674 // reevaluate outputs for all devices
4675 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004676 changeOutputDevicesMuteState(devices);
4677 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4678 true /* skipDelays */);
4679 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004680
4681 return NO_ERROR;
4682}
4683
4684status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004685 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004686 AudioDeviceTypeAddrVector devices;
4687 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004688 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4689 if (status != NO_ERROR) {
4690 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4691 __FUNCTION__, userId);
4692 return status;
4693 }
4694
4695 // reevaluate outputs for all devices
4696 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004697 changeOutputDevicesMuteState(devices);
4698 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4699 true /* skipDelays */);
4700 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004701
4702 return NO_ERROR;
4703}
4704
Andy Hungc29d82b2018-10-05 12:23:17 -07004705void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004706{
Andy Hungc29d82b2018-10-05 12:23:17 -07004707 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004708 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004709 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004710 std::string stateLiteral;
4711 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004712 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004713 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4714 "communications", "media", "record", "dock", "system",
4715 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4716 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4717 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004718 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4719 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4720 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4721 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4722 dst->append(" (MANUAL: ");
4723 dumpManualSurroundFormats(dst);
4724 dst->append(")");
4725 }
4726 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004727 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004728 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4729 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004730 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004731 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004732
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004733 dst->append("\n");
4734 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4735 dst->append("\n");
4736 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004737 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004738 mOutputs.dump(dst);
4739 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004740 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004741 mAudioPatches.dump(dst);
4742 mPolicyMixes.dump(dst);
4743 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004744
Kevin Rocardb99cc752019-03-21 20:52:24 -07004745 dst->appendFormat(" AllowedCapturePolicies:\n");
4746 for (auto& policy : mAllowedCapturePolicies) {
4747 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4748 }
4749
jiabina84c3d32022-12-02 18:59:55 +00004750 dst->appendFormat(" Preferred mixer audio configuration:\n");
4751 for (const auto it : mPreferredMixerAttrInfos) {
4752 dst->appendFormat(" - device port id: %d\n", it.first);
4753 for (const auto preferredMixerInfoIt : it.second) {
4754 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4755 preferredMixerInfoIt.second->dump(dst);
4756 }
4757 }
4758
François Gaffiec005e562018-11-06 15:04:49 +01004759 dst->appendFormat("\nPolicy Engine dump:\n");
4760 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004761
4762 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4763 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4764 dst->appendFormat(" - device type: %s, driving stream %d\n",
4765 dumpDeviceTypes({it.first}).c_str(),
4766 mEngine->getVolumeGroupForAttributes(it.second));
4767 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004768
4769 // dump mmap policy by device
4770 dst->appendFormat("\nMmap policy:\n");
4771 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4772 std::stringstream ss;
4773 ss << '{';
4774 for (const auto& [deviceType, policy] : policyByDevice) {
4775 ss << deviceType.toString() << ":" << toString(policy) << " ";
4776 }
4777 ss << '}';
4778 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4779 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004780}
4781
4782status_t AudioPolicyManager::dump(int fd)
4783{
4784 String8 result;
4785 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004786 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004787 return NO_ERROR;
4788}
4789
Kevin Rocardb99cc752019-03-21 20:52:24 -07004790status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4791{
4792 mAllowedCapturePolicies[uid] = capturePolicy;
4793 return NO_ERROR;
4794}
4795
Eric Laurente552edb2014-03-10 17:42:56 -07004796// This function checks for the parameters which can be offloaded.
4797// This can be enhanced depending on the capability of the DSP and policy
4798// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004799audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004800{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004801 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004802 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004803 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004804 offloadInfo.format,
4805 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4806 offloadInfo.has_video);
4807
jiabin2b9d5a12021-12-10 01:06:29 +00004808 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004809 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004810 }
4811
4812 // See if there is a profile to support this.
4813 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004814 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004815 offloadInfo.sample_rate,
4816 offloadInfo.format,
4817 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004818 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4819 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004820 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4821 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4822 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004823 if (profile == nullptr) {
4824 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4825 }
4826 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4827 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4828 }
4829 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004830}
4831
Michael Chana94fbb22018-04-24 14:31:19 +10004832bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4833 const audio_attributes_t& attributes) {
4834 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004835 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004836 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4837 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004838 config.sample_rate,
4839 config.format,
4840 config.channel_mask,
4841 output_flags,
4842 true /* directOnly */);
4843 ALOGV("%s() profile %sfound with name: %s, "
4844 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4845 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004846 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004847 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004848
4849 // also try the MSD module if compatible profile not found
4850 if (profile == nullptr) {
4851 profile = getMsdProfileForOutput(outputDevices,
4852 config.sample_rate,
4853 config.format,
4854 config.channel_mask,
4855 output_flags,
4856 true /* directOnly */);
4857 ALOGV("%s() MSD profile %sfound with name: %s, "
4858 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4859 __FUNCTION__, profile != 0 ? "" : "NOT ",
4860 (profile != 0 ? profile->getTagName().c_str() : "null"),
4861 config.sample_rate, config.format, config.channel_mask, output_flags);
4862 }
4863 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004864}
4865
jiabin2b9d5a12021-12-10 01:06:29 +00004866bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4867 bool durationIgnored) {
4868 if (mMasterMono) {
4869 return false; // no offloading if mono is set.
4870 }
4871
4872 // Check if offload has been disabled
4873 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4874 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4875 return false;
4876 }
4877
4878 // Check if stream type is music, then only allow offload as of now.
4879 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4880 {
4881 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4882 return false;
4883 }
4884
4885 //TODO: enable audio offloading with video when ready
4886 const bool allowOffloadWithVideo =
4887 property_get_bool("audio.offload.video", false /* default_value */);
4888 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4889 ALOGV("%s: has_video == true, returning false", __func__);
4890 return false;
4891 }
4892
4893 //If duration is less than minimum value defined in property, return false
4894 const int min_duration_secs = property_get_int32(
4895 "audio.offload.min.duration.secs", -1 /* default_value */);
4896 if (!durationIgnored) {
4897 if (min_duration_secs >= 0) {
4898 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4899 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4900 __func__, min_duration_secs);
4901 return false;
4902 }
4903 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4904 ALOGV("%s: Offload denied by duration < default min(=%u)",
4905 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4906 return false;
4907 }
4908 }
4909
4910 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4911 // creating an offloaded track and tearing it down immediately after start when audioflinger
4912 // detects there is an active non offloadable effect.
4913 // FIXME: We should check the audio session here but we do not have it in this context.
4914 // This may prevent offloading in rare situations where effects are left active by apps
4915 // in the background.
4916 if (mEffects.isNonOffloadableEffectEnabled()) {
4917 return false;
4918 }
4919
4920 return true;
4921}
4922
4923audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4924 const audio_config_t *config) {
4925 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4926 offloadInfo.format = config->format;
4927 offloadInfo.sample_rate = config->sample_rate;
4928 offloadInfo.channel_mask = config->channel_mask;
4929 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4930 offloadInfo.has_video = false;
4931 offloadInfo.is_streaming = false;
4932 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4933
4934 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4935 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4936 audio_flags_to_audio_output_flags(attr->flags, &flags);
4937 // only retain flags that will drive compressed offload or passthrough
4938 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4939 if (offloadPossible) {
4940 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4941 }
4942 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4943
Dorin Drimusfae3c642022-03-17 18:36:30 +01004944 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004945 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4946 [this, attr](sp<DeviceDescriptor> device) {
4947 return getPreferredMixerAttributesInfo(
4948 device->getId(),
4949 mEngine->getProductStrategyForAttributes(*attr),
4950 true /*activeBitPerfectPreferred*/) != nullptr;
4951 })) {
4952 // Bit-perfect playback is active on one of the selected devices, direct output will
4953 // be rejected at this instant.
4954 return AUDIO_DIRECT_NOT_SUPPORTED;
4955 }
jiabin2b9d5a12021-12-10 01:06:29 +00004956 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004957 DeviceVector outputDevices = engineOutputDevices;
4958 // the MSD module checks for different conditions and output devices
4959 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4960 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4961 continue;
4962 }
4963 outputDevices = getMsdAudioOutDevices();
4964 }
jiabin2b9d5a12021-12-10 01:06:29 +00004965 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004966 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004967 config->sample_rate, nullptr /*updatedSamplingRate*/,
4968 config->format, nullptr /*updatedFormat*/,
4969 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004970 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004971 continue;
4972 }
4973 // reject profiles not corresponding to a device currently available
4974 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4975 continue;
4976 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004977 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4978 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004979 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004980 != AUDIO_DIRECT_NOT_SUPPORTED) {
4981 // Already reports offload gapless supported. No need to report offload support.
4982 continue;
4983 }
4984 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4985 != AUDIO_OUTPUT_FLAG_NONE) {
4986 // If offload gapless is reported, no need to report offload support.
4987 directMode = (audio_direct_mode_t) ((directMode &
4988 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4989 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4990 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004991 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004992 }
4993 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004994 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004995 }
4996 }
4997 }
4998 return directMode;
4999}
5000
Dorin Drimusf2196d82022-01-03 12:11:18 +01005001status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
5002 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00005003 if (mEffects.isNonOffloadableEffectEnabled()) {
5004 return OK;
5005 }
jiabinf1c73972022-04-14 16:28:52 -07005006 DeviceVector devices;
5007 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01005008 if (status != OK) {
5009 return status;
5010 }
5011 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
5012 if (devices.empty()) {
5013 return OK; // no output devices for the attributes
5014 }
jiabinf1c73972022-04-14 16:28:52 -07005015 return getProfilesForDevices(devices, audioProfilesVector,
5016 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01005017}
5018
jiabina84c3d32022-12-02 18:59:55 +00005019status_t AudioPolicyManager::getSupportedMixerAttributes(
5020 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
5021 ALOGV("%s, portId=%d", __func__, portId);
5022 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5023 if (deviceDescriptor == nullptr) {
5024 ALOGE("%s the requested device is currently unavailable", __func__);
5025 return BAD_VALUE;
5026 }
jiabin96daffc2023-05-11 17:51:55 +00005027 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5028 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
5029 deviceDescriptor->type());
5030 return BAD_VALUE;
5031 }
jiabina84c3d32022-12-02 18:59:55 +00005032 for (const auto& hwModule : mHwModules) {
5033 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5034 if (curProfile->supportsDevice(deviceDescriptor)) {
5035 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5036 }
5037 }
5038 }
5039 return NO_ERROR;
5040}
5041
5042status_t AudioPolicyManager::setPreferredMixerAttributes(
5043 const audio_attributes_t *attr,
5044 audio_port_handle_t portId,
5045 uid_t uid,
5046 const audio_mixer_attributes_t *mixerAttributes) {
5047 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5048 "mixerBehavior=%d}, uid=%d, portId=%u",
5049 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5050 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5051 mixerAttributes->mixer_behavior, uid, portId);
5052 if (attr->usage != AUDIO_USAGE_MEDIA) {
5053 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5054 return BAD_VALUE;
5055 }
5056 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5057 if (deviceDescriptor == nullptr) {
5058 ALOGE("%s the requested device is currently unavailable", __func__);
5059 return BAD_VALUE;
5060 }
5061 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5062 ALOGE("%s(%d), type=%d, is not a usb output device",
5063 __func__, portId, deviceDescriptor->type());
5064 return BAD_VALUE;
5065 }
5066
5067 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5068 audio_flags_to_audio_output_flags(attr->flags, &flags);
5069 flags = (audio_output_flags_t) (flags |
5070 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5071 sp<IOProfile> profile = nullptr;
5072 DeviceVector devices(deviceDescriptor);
5073 for (const auto& hwModule : mHwModules) {
5074 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5075 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005076 && curProfile->getCompatibilityScore(
5077 devices,
5078 mixerAttributes->config.sample_rate,
5079 nullptr /*updatedSamplingRate*/,
5080 mixerAttributes->config.format,
5081 nullptr /*updatedFormat*/,
5082 mixerAttributes->config.channel_mask,
5083 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005084 flags)
jiabin66acc432024-02-06 00:57:36 +00005085 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005086 profile = curProfile;
5087 break;
5088 }
5089 }
5090 }
5091 if (profile == nullptr) {
5092 ALOGE("%s, there is no compatible profile found", __func__);
5093 return BAD_VALUE;
5094 }
5095
5096 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5097 sp<PreferredMixerAttributesInfo>::make(
5098 uid, portId, profile, flags, *mixerAttributes);
5099 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5100 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5101
5102 // If 1) there is any client from the preferred mixer configuration owner that is currently
5103 // active and matches the strategy and 2) current output is on the preferred device and the
5104 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5105 // configuration.
5106 std::vector<audio_io_handle_t> outputsToReopen;
5107 for (size_t i = 0; i < mOutputs.size(); i++) {
5108 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005109 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5110 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005111 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005112 } else {
5113 for (const auto &client: output->getActiveClients()) {
5114 if (client->uid() == uid && client->strategy() == strategy) {
5115 client->setIsInvalid();
5116 outputsToReopen.push_back(output->mIoHandle);
5117 }
jiabina84c3d32022-12-02 18:59:55 +00005118 }
5119 }
5120 }
5121 }
5122 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5123 config.sample_rate = mixerAttributes->config.sample_rate;
5124 config.channel_mask = mixerAttributes->config.channel_mask;
5125 config.format = mixerAttributes->config.format;
5126 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005127 sp<SwAudioOutputDescriptor> desc =
5128 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5129 if (desc == nullptr) {
5130 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5131 continue;
5132 }
jiabin220eea12024-05-17 17:55:20 +00005133 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005134 }
5135
5136 return NO_ERROR;
5137}
5138
5139sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005140 audio_port_handle_t devicePortId,
5141 product_strategy_t strategy,
5142 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005143 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5144 if (it == mPreferredMixerAttrInfos.end()) {
5145 return nullptr;
5146 }
jiabind9a58d32023-06-01 17:57:30 +00005147 if (activeBitPerfectPreferred) {
5148 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005149 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005150 return info;
5151 }
5152 }
jiabina84c3d32022-12-02 18:59:55 +00005153 }
jiabind9a58d32023-06-01 17:57:30 +00005154 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5155 return strategyMatchedMixerAttrInfoIt == it->second.end()
5156 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005157}
5158
5159status_t AudioPolicyManager::getPreferredMixerAttributes(
5160 const audio_attributes_t *attr,
5161 audio_port_handle_t portId,
5162 audio_mixer_attributes_t* mixerAttributes) {
5163 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5164 portId, mEngine->getProductStrategyForAttributes(*attr));
5165 if (info == nullptr) {
5166 return NAME_NOT_FOUND;
5167 }
5168 *mixerAttributes = info->getMixerAttributes();
5169 return NO_ERROR;
5170}
5171
5172status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5173 audio_port_handle_t portId,
5174 uid_t uid) {
5175 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5176 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5177 if (preferredMixerAttrInfo == nullptr) {
5178 return NAME_NOT_FOUND;
5179 }
5180 if (preferredMixerAttrInfo->getUid() != uid) {
5181 ALOGE("%s, requested uid=%d, owned uid=%d",
5182 __func__, uid, preferredMixerAttrInfo->getUid());
5183 return PERMISSION_DENIED;
5184 }
5185 mPreferredMixerAttrInfos[portId].erase(strategy);
5186 if (mPreferredMixerAttrInfos[portId].empty()) {
5187 mPreferredMixerAttrInfos.erase(portId);
5188 }
5189
5190 // Reconfig existing output
5191 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5192 for (size_t i = 0; i < mOutputs.size(); i++) {
5193 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5194 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5195 }
5196 }
5197 for (const auto output : potentialOutputsToReopen) {
5198 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5199 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5200 preferredMixerAttrInfo->getFlags())) {
5201 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5202 }
5203 }
5204 return NO_ERROR;
5205}
5206
Eric Laurent6a94d692014-05-20 11:18:06 -07005207status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5208 audio_port_type_t type,
5209 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005210 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 unsigned int *generation)
5212{
jiabin19cdba52020-11-24 11:28:58 -08005213 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5214 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 return BAD_VALUE;
5216 }
5217 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005218 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 *num_ports = 0;
5220 }
5221
5222 size_t portsWritten = 0;
5223 size_t portsMax = *num_ports;
5224 *num_ports = 0;
5225 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005226 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5227 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005229 for (const auto& dev : mAvailableOutputDevices) {
5230 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005231 continue;
5232 }
5233 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005234 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005235 }
5236 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005238 }
5239 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005240 for (const auto& dev : mAvailableInputDevices) {
5241 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005242 continue;
5243 }
5244 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005245 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005246 }
5247 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 }
5250 }
5251 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5252 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5253 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5254 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5255 }
5256 *num_ports += mInputs.size();
5257 }
5258 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005259 size_t numOutputs = 0;
5260 for (size_t i = 0; i < mOutputs.size(); i++) {
5261 if (!mOutputs[i]->isDuplicated()) {
5262 numOutputs++;
5263 if (portsWritten < portsMax) {
5264 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5265 }
5266 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 }
Eric Laurent84c70242014-06-23 08:46:27 -07005268 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 }
5270 }
jiabina84c3d32022-12-02 18:59:55 +00005271
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005273 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 return NO_ERROR;
5275}
5276
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005277status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5278 std::vector<media::AudioPortFw>* _aidl_return) {
5279 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5280 audio_port_v7 port;
5281 dev->toAudioPort(&port);
5282 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5283 _aidl_return->push_back(std::move(aidlPort));
5284 return OK;
5285 };
5286
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005287 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005288 for (const auto& dev : module->getDeclaredDevices()) {
5289 if (role == media::AudioPortRole::NONE ||
5290 ((role == media::AudioPortRole::SOURCE)
5291 == audio_is_input_device(dev->type()))) {
5292 RETURN_STATUS_IF_ERROR(pushPort(dev));
5293 }
5294 }
5295 }
5296 return OK;
5297}
5298
jiabin19cdba52020-11-24 11:28:58 -08005299status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005300{
Eric Laurent99fcae42018-05-17 16:59:18 -07005301 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5302 return BAD_VALUE;
5303 }
5304 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5305 if (dev != 0) {
5306 dev->toAudioPort(port);
5307 return NO_ERROR;
5308 }
5309 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5310 if (dev != 0) {
5311 dev->toAudioPort(port);
5312 return NO_ERROR;
5313 }
5314 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5315 if (out != 0) {
5316 out->toAudioPort(port);
5317 return NO_ERROR;
5318 }
5319 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5320 if (in != 0) {
5321 in->toAudioPort(port);
5322 return NO_ERROR;
5323 }
5324 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005325}
5326
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005327status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5328 audio_patch_handle_t *handle,
5329 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005330{
François Gaffieafd4cea2019-11-18 15:50:22 +01005331 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 if (handle == NULL || patch == NULL) {
5333 return BAD_VALUE;
5334 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005335 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005336 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005337 return BAD_VALUE;
5338 }
5339 // only one source per audio patch supported for now
5340 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 return INVALID_OPERATION;
5342 }
Eric Laurent874c42872014-08-08 15:13:39 -07005343 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 return INVALID_OPERATION;
5345 }
Eric Laurent874c42872014-08-08 15:13:39 -07005346 for (size_t i = 0; i < patch->num_sinks; i++) {
5347 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5348 return INVALID_OPERATION;
5349 }
5350 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005351
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005352 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5353 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5354 if (srcDevice == nullptr || sinkDevice == nullptr) {
5355 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5356 return BAD_VALUE;
5357 }
5358 ALOGV("%s between source %s and sink %s", __func__,
5359 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5360 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5361 // Default attributes, default volume priority, not to infer with non raw audio patches.
5362 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5363 const struct audio_port_config *source = &patch->sources[0];
5364 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005365 new SourceClientDescriptor(
5366 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5367 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005368 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005369 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005370
5371 status_t status =
5372 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5373
5374 if (status != NO_ERROR) {
5375 return INVALID_OPERATION;
5376 }
5377 mAudioSources.add(portId, sourceDesc);
5378 return NO_ERROR;
5379}
5380
5381status_t AudioPolicyManager::connectAudioSourceToSink(
5382 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5383 const struct audio_patch *patch,
5384 audio_patch_handle_t &handle,
5385 uid_t uid, uint32_t delayMs)
5386{
5387 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5388 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5389 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5390 return INVALID_OPERATION;
5391 }
5392 sourceDesc->connect(handle, sinkDevice);
5393 if (isMsdPatch(handle)) {
5394 return NO_ERROR;
5395 }
5396 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5397 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5398 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5399 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5400 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5401 goto FailurePatchAdded;
5402 }
5403 status = swOutput->start();
5404 if (status != NO_ERROR) {
5405 goto FailureSourceAdded;
5406 }
5407 swOutput->addClient(sourceDesc);
5408 status = startSource(swOutput, sourceDesc, &delayMs);
5409 if (status != NO_ERROR) {
5410 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5411 goto FailureSourceActive;
5412 }
5413 if (delayMs != 0) {
5414 usleep(delayMs * 1000);
5415 }
5416 return NO_ERROR;
5417
5418FailureSourceActive:
5419 swOutput->stop();
5420 releaseOutput(sourceDesc->portId());
5421FailureSourceAdded:
5422 sourceDesc->setSwOutput(nullptr);
5423FailurePatchAdded:
5424 releaseAudioPatchInternal(handle);
5425 return INVALID_OPERATION;
5426}
5427
5428status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5429 audio_patch_handle_t *handle,
5430 uid_t uid, uint32_t delayMs,
5431 const sp<SourceClientDescriptor>& sourceDesc)
5432{
5433 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005434 sp<AudioPatch> patchDesc;
5435 ssize_t index = mAudioPatches.indexOfKey(*handle);
5436
François Gaffieafd4cea2019-11-18 15:50:22 +01005437 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5438 patch->sources[0].role,
5439 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005440#if LOG_NDEBUG == 0
5441 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005442 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5443 patch->sinks[i].role,
5444 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005445 }
5446#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005447
5448 if (index >= 0) {
5449 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005450 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5451 __func__, mUidCached, patchDesc->getUid(), uid);
5452 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005453 return INVALID_OPERATION;
5454 }
5455 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005456 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 }
5458
5459 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005460 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 return BAD_VALUE;
5464 }
Eric Laurent84c70242014-06-23 08:46:27 -07005465 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5466 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 if (patchDesc != 0) {
5468 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005469 ALOGV("%s source id differs for patch current id %d new id %d",
5470 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005471 return BAD_VALUE;
5472 }
5473 }
Eric Laurent874c42872014-08-08 15:13:39 -07005474 DeviceVector devices;
5475 for (size_t i = 0; i < patch->num_sinks; i++) {
5476 // Only support mix to devices connection
5477 // TODO add support for mix to mix connection
5478 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005479 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005480 return INVALID_OPERATION;
5481 }
5482 sp<DeviceDescriptor> devDesc =
5483 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5484 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005485 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005486 return BAD_VALUE;
5487 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005488
jiabin66acc432024-02-06 00:57:36 +00005489 if (outputDesc->mProfile->getCompatibilityScore(
5490 DeviceVector(devDesc),
5491 patch->sources[0].sample_rate,
5492 nullptr, // updatedSamplingRate
5493 patch->sources[0].format,
5494 nullptr, // updatedFormat
5495 patch->sources[0].channel_mask,
5496 nullptr, // updatedChannelMask
5497 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005498 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005499 return INVALID_OPERATION;
5500 }
5501 devices.add(devDesc);
5502 }
5503 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005504 return INVALID_OPERATION;
5505 }
Eric Laurent874c42872014-08-08 15:13:39 -07005506
Eric Laurent6a94d692014-05-20 11:18:06 -07005507 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005508 ALOGV("%s setting device %s on output %d",
5509 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305510 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005511 index = mAudioPatches.indexOfKey(*handle);
5512 if (index >= 0) {
5513 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005514 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 }
5516 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005517 patchDesc->setUid(uid);
5518 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005519 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005520 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005521 return INVALID_OPERATION;
5522 }
5523 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5524 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5525 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005526 // only one sink supported when connecting an input device to a mix
5527 if (patch->num_sinks > 1) {
5528 return INVALID_OPERATION;
5529 }
François Gaffie53615e22015-03-19 09:24:12 +01005530 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005531 if (inputDesc == NULL) {
5532 return BAD_VALUE;
5533 }
5534 if (patchDesc != 0) {
5535 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5536 return BAD_VALUE;
5537 }
5538 }
François Gaffie11d30102018-11-02 16:09:09 +01005539 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005541 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005542 return BAD_VALUE;
5543 }
5544
jiabin66acc432024-02-06 00:57:36 +00005545 if (inputDesc->mProfile->getCompatibilityScore(
5546 DeviceVector(device),
5547 patch->sinks[0].sample_rate,
5548 nullptr, /*updatedSampleRate*/
5549 patch->sinks[0].format,
5550 nullptr, /*updatedFormat*/
5551 patch->sinks[0].channel_mask,
5552 nullptr, /*updatedChannelMask*/
5553 // FIXME for the parameter type,
5554 // and the NONE
5555 (audio_output_flags_t)
5556 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 return INVALID_OPERATION;
5558 }
5559 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005561 device->toString().c_str(), inputDesc->mIoHandle);
5562 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005563 index = mAudioPatches.indexOfKey(*handle);
5564 if (index >= 0) {
5565 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005566 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005567 }
5568 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 patchDesc->setUid(uid);
5570 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005571 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005572 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005573 return INVALID_OPERATION;
5574 }
5575 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5576 // device to device connection
5577 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005578 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005579 return BAD_VALUE;
5580 }
5581 }
François Gaffie11d30102018-11-02 16:09:09 +01005582 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005583 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005584 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005585 return BAD_VALUE;
5586 }
Eric Laurent874c42872014-08-08 15:13:39 -07005587
Eric Laurent6a94d692014-05-20 11:18:06 -07005588 //update source and sink with our own data as the data passed in the patch may
5589 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005590 PatchBuilder patchBuilder;
5591 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005592
5593 // if first sink is to MSD, establish single MSD patch
5594 if (getMsdAudioOutDevices().contains(
5595 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5596 ALOGV("%s patching to MSD", __FUNCTION__);
5597 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5598 goto installPatch;
5599 }
5600
François Gaffieafd4cea2019-11-18 15:50:22 +01005601 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5602 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005603
Eric Laurent874c42872014-08-08 15:13:39 -07005604 for (size_t i = 0; i < patch->num_sinks; i++) {
5605 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005606 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005607 return INVALID_OPERATION;
5608 }
François Gaffie11d30102018-11-02 16:09:09 +01005609 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005610 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005611 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005612 return BAD_VALUE;
5613 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005614 audio_port_config sinkPortConfig = {};
5615 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5616 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005617
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005618 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5619 // volume management purpose (tracking activity)
5620 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5621 // in config XML to reach the sink so that is can be declared as available.
5622 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005623 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005624 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005625 // take care of dynamic routing for SwOutput selection,
5626 audio_attributes_t attributes = sourceDesc->attributes();
5627 audio_stream_type_t stream = sourceDesc->stream();
5628 audio_attributes_t resultAttr;
5629 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5630 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005631 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5632 config.channel_mask =
5633 (audio_channel_mask_get_representation(sourceMask)
5634 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5635 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005636 config.format = sourceDesc->config().format;
5637 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Robert Wufb971192024-10-30 21:54:35 +00005638 DeviceIdVector selectedDeviceIds;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005639 bool isRequestedDeviceForExclusiveUse = false;
5640 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005641 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005642 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005643 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5644 &stream, sourceDesc->uid(), &config, &flags,
Robert Wufb971192024-10-30 21:54:35 +00005645 &selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005646 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005647 if (output == AUDIO_IO_HANDLE_NONE) {
5648 ALOGV("%s no output for device %s",
5649 __FUNCTION__, sinkDevice->toString().c_str());
5650 return INVALID_OPERATION;
5651 }
5652 outputDesc = mOutputs.valueFor(output);
5653 if (outputDesc->isDuplicated()) {
5654 ALOGE("%s output is duplicated", __func__);
5655 return INVALID_OPERATION;
5656 }
François Gaffie7e39df22022-04-26 12:48:49 +02005657 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5658 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005659 } else {
5660 // Same for "raw patches" aka created from createAudioPatch API
5661 SortedVector<audio_io_handle_t> outputs =
5662 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5663 // if the sink device is reachable via an opened output stream, request to
5664 // go via this output stream by adding a second source to the patch
5665 // description
5666 output = selectOutput(outputs);
5667 if (output == AUDIO_IO_HANDLE_NONE) {
5668 ALOGE("%s no output available for internal patch sink", __func__);
5669 return INVALID_OPERATION;
5670 }
5671 outputDesc = mOutputs.valueFor(output);
5672 if (outputDesc->isDuplicated()) {
5673 ALOGV("%s output for device %s is duplicated",
5674 __func__, sinkDevice->toString().c_str());
5675 return INVALID_OPERATION;
5676 }
François Gaffie7e39df22022-04-26 12:48:49 +02005677 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005678 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005679 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005680 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005681 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005682 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005683 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5684 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005685 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5686 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005687 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005688 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005689 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005690 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005691 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005692 return INVALID_OPERATION;
5693 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005694 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005695 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005696 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005697 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005698 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005699 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005700 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005701 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5702 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005703 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005704 }
Eric Laurent83b88082014-06-20 18:31:16 -07005705 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005706 }
5707 // TODO: check from routing capabilities in config file and other conflicting patches
5708
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005709installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005710 status_t status = installPatch(
5711 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005712 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005713 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005714 return INVALID_OPERATION;
5715 }
5716 } else {
5717 return BAD_VALUE;
5718 }
5719 } else {
5720 return BAD_VALUE;
5721 }
5722 return NO_ERROR;
5723}
5724
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005725status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005726{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005727 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005728 ssize_t index = mAudioPatches.indexOfKey(handle);
5729
5730 if (index < 0) {
5731 return BAD_VALUE;
5732 }
5733 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005734 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5735 __func__, mUidCached, patchDesc->getUid(), uid);
5736 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005737 return INVALID_OPERATION;
5738 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005739 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5740 for (size_t i = 0; i < mAudioSources.size(); i++) {
5741 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5742 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5743 portId = sourceDesc->portId();
5744 break;
5745 }
5746 }
5747 return portId != AUDIO_PORT_HANDLE_NONE ?
5748 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005749}
Eric Laurent6a94d692014-05-20 11:18:06 -07005750
François Gaffieafd4cea2019-11-18 15:50:22 +01005751status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005752 uint32_t delayMs,
5753 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005754{
5755 ALOGV("%s patch %d", __func__, handle);
5756 if (mAudioPatches.indexOfKey(handle) < 0) {
5757 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5758 return BAD_VALUE;
5759 }
5760 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005761 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005762 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005763 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005764 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005765 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005766 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005767 return BAD_VALUE;
5768 }
5769
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305770 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005771 getNewOutputDevices(outputDesc, true /*fromCache*/),
5772 true,
5773 0,
5774 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005775 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5776 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005777 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005778 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005779 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005780 return BAD_VALUE;
5781 }
5782 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005783 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005784 true,
5785 NULL);
5786 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005787 status_t status =
5788 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5789 ALOGV("%s patch panel returned %d patchHandle %d",
5790 __func__, status, patchDesc->getAfHandle());
5791 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005792 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005793 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005794 // SW or HW Bridge
5795 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5796 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005797 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005798 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5799 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5800 outputDesc = sourceDesc->swOutput().promote();
5801 }
5802 if (outputDesc == nullptr) {
5803 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5804 // releaseOutput has already called closeOutput in case of direct output
5805 return NO_ERROR;
5806 }
François Gaffie7e39df22022-04-26 12:48:49 +02005807 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005808 // While using a HwBridge, force reconsidering device only if not reusing an existing
5809 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005810 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005811 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5812 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5813 // Reconsider device only for cases:
5814 // 1 / Active Output
5815 // 2 / Inactive Output previously hosting HwBridge
5816 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5817 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5818 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305819 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005820 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5821 outputDesc->devices(),
5822 force,
5823 0,
5824 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005825 } else {
5826 return BAD_VALUE;
5827 }
5828 } else {
5829 return BAD_VALUE;
5830 }
5831 return NO_ERROR;
5832}
5833
5834status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5835 struct audio_patch *patches,
5836 unsigned int *generation)
5837{
François Gaffie53615e22015-03-19 09:24:12 +01005838 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005839 return BAD_VALUE;
5840 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005841 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005842 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005843}
5844
Eric Laurente1715a42014-05-20 11:30:42 -07005845status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005846{
Eric Laurente1715a42014-05-20 11:30:42 -07005847 ALOGV("setAudioPortConfig()");
5848
5849 if (config == NULL) {
5850 return BAD_VALUE;
5851 }
5852 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5853 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005854 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5855 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005856 }
5857
Eric Laurenta121f902014-06-03 13:32:54 -07005858 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005859 if (config->type == AUDIO_PORT_TYPE_MIX) {
5860 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005861 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005862 if (outputDesc == NULL) {
5863 return BAD_VALUE;
5864 }
Eric Laurent84c70242014-06-23 08:46:27 -07005865 ALOG_ASSERT(!outputDesc->isDuplicated(),
5866 "setAudioPortConfig() called on duplicated output %d",
5867 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005868 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005869 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005870 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005871 if (inputDesc == NULL) {
5872 return BAD_VALUE;
5873 }
Eric Laurenta121f902014-06-03 13:32:54 -07005874 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005875 } else {
5876 return BAD_VALUE;
5877 }
5878 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5879 sp<DeviceDescriptor> deviceDesc;
5880 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5881 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5882 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5883 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5884 } else {
5885 return BAD_VALUE;
5886 }
5887 if (deviceDesc == NULL) {
5888 return BAD_VALUE;
5889 }
Eric Laurenta121f902014-06-03 13:32:54 -07005890 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005891 } else {
5892 return BAD_VALUE;
5893 }
5894
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005895 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005896 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5897 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005898 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005899 audioPortConfig->toAudioPortConfig(&newConfig, config);
5900 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005901 }
Eric Laurenta121f902014-06-03 13:32:54 -07005902 if (status != NO_ERROR) {
5903 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005904 }
Eric Laurente1715a42014-05-20 11:30:42 -07005905
5906 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005907}
5908
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005909void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5910{
Eric Laurentd60560a2015-04-10 11:31:20 -07005911 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005912 clearAudioPatches(uid);
5913 clearSessionRoutes(uid);
5914}
5915
Eric Laurent6a94d692014-05-20 11:18:06 -07005916void AudioPolicyManager::clearAudioPatches(uid_t uid)
5917{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005918 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005919 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005920 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005921 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005922 }
5923 }
5924}
5925
François Gaffiec005e562018-11-06 15:04:49 +01005926void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005927{
François Gaffiec005e562018-11-06 15:04:49 +01005928 // Take the first attributes following the product strategy as it is used to retrieve the routed
5929 // device. All attributes wihin a strategy follows the same "routing strategy"
5930 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5931 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005932 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005933 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005934 for (size_t j = 0; j < mOutputs.size(); j++) {
5935 if (mOutputs.keyAt(j) == ouptutToSkip) {
5936 continue;
5937 }
5938 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005939 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005940 continue;
5941 }
5942 // If the default device for this strategy is on another output mix,
5943 // invalidate all tracks in this strategy to force re connection.
5944 // Otherwise select new device on the output mix.
5945 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005946 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005947 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005948 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005949 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005950 // If the device is using preferred mixer attributes, the output need to reopen
5951 // with default configuration when the new selected devices are different from
5952 // current routing devices.
5953 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5954 continue;
5955 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305956 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005957 }
5958 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005959 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005960}
5961
5962void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5963{
5964 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005965 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005966 for (size_t i = 0; i < mOutputs.size(); i++) {
5967 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005968 for (const auto& client : outputDesc->getClientIterable()) {
5969 if (client->hasPreferredDevice() && client->uid() == uid) {
5970 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005971 auto clientStrategy = client->strategy();
5972 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5973 end(affectedStrategies)) {
5974 continue;
5975 }
5976 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005977 }
5978 }
5979 }
5980 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005981 for (const auto& strategy : affectedStrategies) {
5982 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005983 }
5984
5985 // remove input routes associated with this uid
5986 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005987 for (size_t i = 0; i < mInputs.size(); i++) {
5988 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005989 for (const auto& client : inputDesc->getClientIterable()) {
5990 if (client->hasPreferredDevice() && client->uid() == uid) {
5991 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5992 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005993 }
5994 }
5995 }
5996 // reroute inputs if necessary
5997 SortedVector<audio_io_handle_t> inputsToClose;
5998 for (size_t i = 0; i < mInputs.size(); i++) {
5999 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08006000 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006001 inputsToClose.add(inputDesc->mIoHandle);
6002 }
6003 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006004 for (const auto& input : inputsToClose) {
6005 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006006 }
6007}
6008
Eric Laurentd60560a2015-04-10 11:31:20 -07006009void AudioPolicyManager::clearAudioSources(uid_t uid)
6010{
6011 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006012 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6013 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006014 stopAudioSource(mAudioSources.keyAt(i));
6015 }
6016 }
6017}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006018
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006019status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
6020 audio_io_handle_t *ioHandle,
6021 audio_devices_t *device)
6022{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08006023 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
6024 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01006025 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00006026 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
6027 if (deviceDesc == nullptr) {
6028 return INVALID_OPERATION;
6029 }
6030 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006031
François Gaffiedf372692015-03-19 10:43:27 +01006032 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006033}
6034
Eric Laurentd60560a2015-04-10 11:31:20 -07006035status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006036 const audio_attributes_t *attributes,
6037 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00006038 uid_t uid) {
6039 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006040 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006041}
6042
6043status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6044 const audio_attributes_t *attributes,
6045 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006046 uid_t uid, bool internal, bool isCallRx,
6047 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006048{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006049 ALOGV("%s", __FUNCTION__);
6050 *portId = AUDIO_PORT_HANDLE_NONE;
6051
6052 if (source == NULL || attributes == NULL || portId == NULL) {
6053 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6054 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006055 return BAD_VALUE;
6056 }
6057
Eric Laurentd60560a2015-04-10 11:31:20 -07006058 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6059 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6061 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006062 return INVALID_OPERATION;
6063 }
6064
François Gaffie11d30102018-11-02 16:09:09 +01006065 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006066 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006067 String8(source->ext.device.address),
6068 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006069 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006070 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006071 return BAD_VALUE;
6072 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006073
jiabin4ef93452019-09-10 14:29:54 -07006074 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006075
François Gaffieaaac0fd2018-11-22 17:56:39 +01006076 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006077 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006078 mEngine->getStreamTypeForAttributes(*attributes),
6079 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006080 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006081
David Lif85c5e32024-07-01 13:14:10 +00006082 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006083 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006084 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006085 }
6086 return status;
6087}
6088
David Lif85c5e32024-07-01 13:14:10 +00006089status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6090 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006091{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006092 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006093
6094 // make sure we only have one patch per source.
6095 disconnectAudioSource(sourceDesc);
6096
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006097 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006098 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6099 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6100 sourceDesc->srcDevice()->type(),
6101 String8(sourceDesc->srcDevice()->address().c_str()),
6102 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006103 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006104 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006105 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006106 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006107 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6108 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6109 return INVALID_OPERATION;
6110 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006111 PatchBuilder patchBuilder;
6112 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6113 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006114
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006115 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006116 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006117}
6118
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006119status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006120{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006121 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6122 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006123 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006124 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006125 return BAD_VALUE;
6126 }
6127 status_t status = disconnectAudioSource(sourceDesc);
6128
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006129 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006130 return status;
6131}
6132
Andy Hung2ddee192015-12-18 17:34:44 -08006133status_t AudioPolicyManager::setMasterMono(bool mono)
6134{
6135 if (mMasterMono == mono) {
6136 return NO_ERROR;
6137 }
6138 mMasterMono = mono;
6139 // if enabling mono we close all offloaded devices, which will invalidate the
6140 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6141 // for recreating the new AudioTrack as non-offloaded PCM.
6142 //
6143 // If disabling mono, we leave all tracks as is: we don't know which clients
6144 // and tracks are able to be recreated as offloaded. The next "song" should
6145 // play back offloaded.
6146 if (mMasterMono) {
6147 Vector<audio_io_handle_t> offloaded;
6148 for (size_t i = 0; i < mOutputs.size(); ++i) {
6149 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6150 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6151 offloaded.push(desc->mIoHandle);
6152 }
6153 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006154 for (const auto& handle : offloaded) {
6155 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006156 }
6157 }
6158 // update master mono for all remaining outputs
6159 for (size_t i = 0; i < mOutputs.size(); ++i) {
6160 updateMono(mOutputs.keyAt(i));
6161 }
6162 return NO_ERROR;
6163}
6164
6165status_t AudioPolicyManager::getMasterMono(bool *mono)
6166{
6167 *mono = mMasterMono;
6168 return NO_ERROR;
6169}
6170
Eric Laurentac9cef52017-06-09 15:46:26 -07006171float AudioPolicyManager::getStreamVolumeDB(
6172 audio_stream_type_t stream, int index, audio_devices_t device)
6173{
Vlad Popa9d482762024-06-21 16:40:23 -07006174 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6175 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006176}
6177
jiabin81772902018-04-02 17:52:27 -07006178status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6179 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006180 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006181{
Kriti Dang6537def2021-03-02 13:46:59 +01006182 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6183 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006184 return BAD_VALUE;
6185 }
Kriti Dang6537def2021-03-02 13:46:59 +01006186 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6187 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006188
6189 size_t formatsWritten = 0;
6190 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006191
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006192 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006193 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6194 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006195 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006196 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006197 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006198 bool formatEnabled = true;
6199 switch (forceUse) {
6200 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006201 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006202 break;
6203 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6204 formatEnabled = false;
6205 break;
6206 default: // AUTO or ALWAYS => true
6207 break;
jiabin81772902018-04-02 17:52:27 -07006208 }
6209 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6210 }
jiabin81772902018-04-02 17:52:27 -07006211 }
6212 return NO_ERROR;
6213}
6214
Kriti Dang6537def2021-03-02 13:46:59 +01006215status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6216 audio_format_t *surroundFormats) {
6217 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6218 return BAD_VALUE;
6219 }
6220 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6221 __func__, *numSurroundFormats, surroundFormats);
6222
6223 size_t formatsWritten = 0;
6224 size_t formatsMax = *numSurroundFormats;
6225 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6226
6227 // Return formats from all device profiles that have already been resolved by
6228 // checkOutputsForDevice().
6229 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6230 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6231 audio_devices_t deviceType = device->type();
6232 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6233 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006234 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6235 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006236 continue;
6237 }
6238 // Formats reported by sink devices
6239 std::unordered_set<audio_format_t> formatset;
6240 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6241 formatset.insert(it->second.begin(), it->second.end());
6242 }
6243
6244 // Formats hard-coded in the in policy configuration file (if any).
6245 FormatVector encodedFormats = device->encodedFormats();
6246 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6247 // Filter the formats which are supported by the vendor hardware.
6248 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006249 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006250 formats.insert(*it);
6251 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006252 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006253 if (pair.second.count(*it) != 0) {
6254 formats.insert(pair.first);
6255 break;
6256 }
6257 }
6258 }
6259 }
6260 }
6261 *numSurroundFormats = formats.size();
6262 for (const auto& format: formats) {
6263 if (formatsWritten < formatsMax) {
6264 surroundFormats[formatsWritten++] = format;
6265 }
6266 }
6267 return NO_ERROR;
6268}
6269
jiabin81772902018-04-02 17:52:27 -07006270status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6271{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006272 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006273 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6274 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006275 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006276 return BAD_VALUE;
6277 }
6278
Mikhail Naganov100f0122018-11-29 11:22:16 -08006279 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6280 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006281 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006282 return INVALID_OPERATION;
6283 }
6284
Mikhail Naganov100f0122018-11-29 11:22:16 -08006285 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006286 return NO_ERROR;
6287 }
6288
Mikhail Naganov100f0122018-11-29 11:22:16 -08006289 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006290 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006291 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006292 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006293 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006294 }
6295 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006296 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006297 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006298 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006299 }
6300 }
6301
6302 sp<SwAudioOutputDescriptor> outputDesc;
6303 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006304 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6305 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006306 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6307 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006308 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006309 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006310 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006311 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6312 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006313 name.c_str(),
6314 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006315 if (status != NO_ERROR) {
6316 continue;
6317 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006318 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006319 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6320 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006321 name.c_str(),
6322 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006323 profileUpdated |= (status == NO_ERROR);
6324 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006325 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006326 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006327 AUDIO_DEVICE_IN_HDMI);
6328 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6329 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006330 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006331 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006332 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6333 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6334 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006335 name.c_str(),
6336 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006337 if (status != NO_ERROR) {
6338 continue;
6339 }
6340 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6341 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6342 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006343 name.c_str(),
6344 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006345 profileUpdated |= (status == NO_ERROR);
6346 }
6347
jiabin81772902018-04-02 17:52:27 -07006348 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006349 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006350 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006351 }
6352
6353 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6354}
6355
Eric Laurent5ada82e2019-08-29 17:53:54 -07006356void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006357{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006358 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006359 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006360 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006361 }
6362}
6363
jiabin6012f912018-11-02 17:06:30 -07006364bool AudioPolicyManager::isHapticPlaybackSupported()
6365{
6366 for (const auto& hwModule : mHwModules) {
6367 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6368 for (const auto &outProfile : outputProfiles) {
6369 struct audio_port audioPort;
6370 outProfile->toAudioPort(&audioPort);
6371 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6372 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6373 return true;
6374 }
6375 }
6376 }
6377 }
6378 return false;
6379}
6380
Carter Hsu325a8eb2022-01-19 19:56:51 +08006381bool AudioPolicyManager::isUltrasoundSupported()
6382{
6383 bool hasUltrasoundOutput = false;
6384 bool hasUltrasoundInput = false;
6385 for (const auto& hwModule : mHwModules) {
6386 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6387 if (!hasUltrasoundOutput) {
6388 for (const auto &outProfile : outputProfiles) {
6389 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6390 hasUltrasoundOutput = true;
6391 break;
6392 }
6393 }
6394 }
6395
6396 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6397 if (!hasUltrasoundInput) {
6398 for (const auto &inputProfile : inputProfiles) {
6399 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6400 hasUltrasoundInput = true;
6401 break;
6402 }
6403 }
6404 }
6405
6406 if (hasUltrasoundOutput && hasUltrasoundInput)
6407 return true;
6408 }
6409 return false;
6410}
6411
Atneya Nair698f5ef2022-12-15 16:15:09 -08006412bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6413{
6414 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6415 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6416 for (const auto& hwModule : mHwModules) {
6417 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6418 for (const auto &inputProfile : inputProfiles) {
6419 if ((inputProfile->getFlags() & mask) == mask) {
6420 return true;
6421 }
6422 }
6423 }
6424 return false;
6425}
6426
Eric Laurent8340e672019-11-06 11:01:08 -08006427bool AudioPolicyManager::isCallScreenModeSupported()
6428{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006429 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006430}
6431
6432
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006433status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006434{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006435 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006436 if (!sourceDesc->isConnected()) {
6437 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6438 return NO_ERROR;
6439 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006440 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6441 if (swOutput != 0) {
6442 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006443 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006444 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006445 }
jiabinbce0c1d2020-10-05 11:20:18 -07006446 if (releaseOutput(sourceDesc->portId())) {
6447 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6448 // no need to release audio patch here but just return NO_ERROR.
6449 return NO_ERROR;
6450 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006451 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006452 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006453 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006454 // close Hwoutput and remove from mHwOutputs
6455 } else {
6456 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6457 }
6458 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006459 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006460 sourceDesc->disconnect();
6461 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006462}
6463
François Gaffiec005e562018-11-06 15:04:49 +01006464sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6465 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006466{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006467 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006468 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006469 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006470 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006471 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6472 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006473 source = sourceDesc;
6474 break;
6475 }
6476 }
6477 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006478}
6479
Eric Laurentb4f42a92022-01-17 17:37:31 +01006480bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006481 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006482 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006483{
6484 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6485 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006486 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006487 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006488 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6489 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6490 return false;
6491 }
6492 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6493 return false;
6494 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006495 }
6496
Eric Laurentd332bc82023-08-04 11:45:23 +02006497 // The caller can have the audio config criteria ignored by either passing a null ptr or
6498 // the AUDIO_CONFIG_INITIALIZER value.
6499 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006500 // some positional channel masks and PCM format and for stereo if low latency performance
6501 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006502
6503 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006504 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006505 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6506 ? audio_channel_mask_contains_stereo(config->channel_mask)
6507 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006508 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006509 return false;
6510 }
6511 if (!audio_is_linear_pcm(config->format)) {
6512 return false;
6513 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006514 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6515 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6516 return false;
6517 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006518 }
6519
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006520 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006521 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006522 if (profile == nullptr) {
6523 return false;
6524 }
6525
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006526 return true;
6527}
6528
Shunkai Yao4c3af932024-04-26 04:12:21 +00006529// The Spatializer output is compatible with Haptic use cases if:
6530// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6531// with client if client haptic channel bits were set, or
6532// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6533// including the haptic bits or creating the HapticGenerator effect for same session.
6534bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6535 const audio_config_t* config, audio_session_t sessionId) const {
6536 const auto clientHapticChannel =
6537 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6538 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6539 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6540
6541 if (threadOutputHapticChannel) {
6542 // check format and sampleRate match if client haptic channel mask exist
6543 if (clientHapticChannel) {
6544 return mSpatializerOutput->getFormat() == config->format &&
6545 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6546 }
6547 return true;
6548 } else {
6549 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6550 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6551 // HapticGenerator effect for this session) are not supported.
6552 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006553 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006554 }
6555}
6556
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006557void AudioPolicyManager::checkVirtualizerClientRoutes() {
6558 std::set<audio_stream_type_t> streamsToInvalidate;
6559 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006560 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6561 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006562 audio_attributes_t attr = client->attributes();
6563 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6564 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6565 audio_config_base_t clientConfig = client->config();
6566 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006567 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006568 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006569 streamsToInvalidate.insert(client->stream());
6570 }
6571 }
6572 }
6573
jiabinc44b3462022-12-08 12:52:31 -08006574 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006575}
6576
Eric Laurente191d1b2022-04-15 11:59:25 +02006577
6578bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6579 const sp<SwAudioOutputDescriptor>& outputDesc) {
6580 if (outputDesc->isDuplicated()) {
6581 return false;
6582 }
6583 DeviceVector devices = outputDesc->supportedDevices();
6584 for (size_t i = 0; i < mOutputs.size(); i++) {
6585 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6586 if (desc == outputDesc || desc->isDuplicated()) {
6587 continue;
6588 }
6589 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6590 if (!sharedDevices.isEmpty()
6591 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6592 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6593 return false;
6594 }
6595 }
6596 return true;
6597}
6598
6599
Eric Laurentfa0f6742021-08-17 18:39:44 +02006600status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006601 const audio_attributes_t *attr,
6602 audio_io_handle_t *output) {
6603 *output = AUDIO_IO_HANDLE_NONE;
6604
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006605 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6606 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6607 audio_config_t *configPtr = nullptr;
6608 audio_config_t config;
6609 if (mixerConfig != nullptr) {
6610 config = audio_config_initializer(mixerConfig);
6611 configPtr = &config;
6612 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006613 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006614 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006615 return BAD_VALUE;
6616 }
6617
6618 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006619 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006620 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006621 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006622 return BAD_VALUE;
6623 }
6624
Eric Laurente191d1b2022-04-15 11:59:25 +02006625 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006626 for (size_t i = 0; i < mOutputs.size(); i++) {
6627 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006628 if (!desc->isDuplicated()
6629 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6630 spatializerOutputs.push_back(desc);
6631 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006632 }
6633 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006634 mSpatializerOutput.clear();
6635 bool outputsChanged = false;
6636 for (const auto& desc : spatializerOutputs) {
6637 if (desc->mProfile == profile
6638 && (configPtr == nullptr
6639 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6640 mSpatializerOutput = desc;
6641 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6642 } else {
6643 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6644 " and devices %s", __func__, desc->mIoHandle,
6645 configPtr != nullptr ? configPtr->channel_mask : 0,
6646 devices.toString().c_str());
6647 closeOutput(desc->mIoHandle);
6648 outputsChanged = true;
6649 }
Eric Laurent39095982021-08-24 18:29:27 +02006650 }
6651
Eric Laurente191d1b2022-04-15 11:59:25 +02006652 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006653 sp<SwAudioOutputDescriptor> desc =
6654 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006655 if (desc != nullptr) {
6656 mSpatializerOutput = desc;
6657 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006658 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006659 }
6660
6661 checkVirtualizerClientRoutes();
6662
Eric Laurente191d1b2022-04-15 11:59:25 +02006663 if (outputsChanged) {
6664 mPreviousOutputs = mOutputs;
6665 mpClientInterface->onAudioPortListUpdate();
6666 }
6667
6668 if (mSpatializerOutput == nullptr) {
6669 ALOGV("%s could not open spatializer output with requested config", __func__);
6670 return BAD_VALUE;
6671 }
Eric Laurent39095982021-08-24 18:29:27 +02006672 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006673 ALOGV("%s returning new spatializer output %d", __func__, *output);
6674 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006675}
6676
Eric Laurentfa0f6742021-08-17 18:39:44 +02006677status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6678 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006679 return INVALID_OPERATION;
6680 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006681 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006682 return BAD_VALUE;
6683 }
Eric Laurent39095982021-08-24 18:29:27 +02006684
Eric Laurente191d1b2022-04-15 11:59:25 +02006685 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6686 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6687 closeOutput(mSpatializerOutput->mIoHandle);
6688 //from now on mSpatializerOutput is null
6689 checkVirtualizerClientRoutes();
6690 }
Eric Laurent39095982021-08-24 18:29:27 +02006691
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006692 return NO_ERROR;
6693}
6694
Eric Laurente552edb2014-03-10 17:42:56 -07006695// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006696// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006697// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006698uint32_t AudioPolicyManager::nextAudioPortGeneration()
6699{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006700 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006701}
6702
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006703AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006704 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006705 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006706 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006707 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006708 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006709 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006710 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006711 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006712 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006713 mAudioPortGeneration(1),
6714 mBeaconMuteRefCount(0),
6715 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006716 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006717 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006718 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006719 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006720{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006721}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006722
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006723status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006724 if (mEngine == nullptr) {
6725 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006726 }
6727 mEngine->setObserver(this);
6728 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006729 if (status != NO_ERROR) {
6730 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6731 return status;
6732 }
François Gaffie2110e042015-03-24 08:41:51 +01006733
jiabin29230182023-04-04 21:02:36 +00006734 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6735 // at the end of this function.
6736 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006737 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6738 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6739
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006740 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006741 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006742 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006743
Eric Laurent3a4311c2014-03-17 12:00:47 -07006744 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006745 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6746 defaultOutputDevice == nullptr ||
6747 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6748 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6749 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006750 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006751 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006752 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006753
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006754 // Silence ALOGV statements
6755 property_set("log.tag." LOG_TAG, "D");
6756
Eric Laurente552edb2014-03-10 17:42:56 -07006757 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006758 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006759}
6760
Eric Laurente0720872014-03-11 09:30:41 -07006761AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006762{
Eric Laurente552edb2014-03-10 17:42:56 -07006763 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006764 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006765 }
6766 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006767 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006768 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006769 mAvailableOutputDevices.clear();
6770 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006771 mOutputs.clear();
6772 mInputs.clear();
6773 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006774 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006775 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006776}
6777
Eric Laurente0720872014-03-11 09:30:41 -07006778status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006779{
Eric Laurent87ffa392015-05-22 10:32:38 -07006780 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006781}
6782
Eric Laurente552edb2014-03-10 17:42:56 -07006783// ---
6784
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006785void AudioPolicyManager::onNewAudioModulesAvailable()
6786{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006787 DeviceVector newDevices;
6788 onNewAudioModulesAvailableInt(&newDevices);
6789 if (!newDevices.empty()) {
6790 nextAudioPortGeneration();
6791 mpClientInterface->onAudioPortListUpdate();
6792 }
6793}
6794
6795void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6796{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006797 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006798 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6799 continue;
6800 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006801 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006802 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6803 handle != AUDIO_MODULE_HANDLE_NONE) {
6804 hwModule->setHandle(handle);
6805 } else {
6806 ALOGW("could not load HW module %s", hwModule->getName());
6807 continue;
6808 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006809 }
6810 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006811 // open all output streams needed to access attached devices.
6812 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006813 // This also validates mAvailableOutputDevices list
6814 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6815 if (!outProfile->canOpenNewIo()) {
6816 ALOGE("Invalid Output profile max open count %u for profile %s",
6817 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6818 continue;
6819 }
6820 if (!outProfile->hasSupportedDevices()) {
6821 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6822 continue;
6823 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006824 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6825 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006826 mTtsOutputAvailable = true;
6827 }
6828
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006829 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006830 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006831 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006832 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6833 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006834 } else {
6835 // choose first device present in profile's SupportedDevices also part of
6836 // mAvailableOutputDevices.
6837 if (availProfileDevices.isEmpty()) {
6838 continue;
6839 }
6840 supportedDevice = availProfileDevices.itemAt(0);
6841 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006842 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006843 continue;
6844 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306845
6846 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6847 && availProfileDevices.areAllDevicesAttached()) {
6848 ALOGV("%s skip opening output for mmap profile %s", __func__,
6849 outProfile->getTagName().c_str());
6850 continue;
6851 }
6852
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006853 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6854 mpClientInterface);
6855 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006856 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006857 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006858 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6859 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006860 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006861 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006862 if (status != NO_ERROR) {
6863 ALOGW("Cannot open output stream for devices %s on hw module %s",
6864 supportedDevice->toString().c_str(), hwModule->getName());
6865 continue;
6866 }
6867 for (const auto &device : availProfileDevices) {
6868 // give a valid ID to an attached device once confirmed it is reachable
6869 if (!device->isAttached()) {
6870 device->attach(hwModule);
6871 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006872 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006873 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006874 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6875 }
6876 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006877 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006878 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6879 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006880 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006881 }
Eric Laurent39095982021-08-24 18:29:27 +02006882 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006883 outputDesc->close();
6884 } else {
6885 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306886 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006887 DeviceVector(supportedDevice),
6888 true,
6889 0,
6890 NULL);
6891 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006892 }
6893 // open input streams needed to access attached devices to validate
6894 // mAvailableInputDevices list
6895 for (const auto& inProfile : hwModule->getInputProfiles()) {
6896 if (!inProfile->canOpenNewIo()) {
6897 ALOGE("Invalid Input profile max open count %u for profile %s",
6898 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6899 continue;
6900 }
6901 if (!inProfile->hasSupportedDevices()) {
6902 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6903 continue;
6904 }
6905 // chose first device present in profile's SupportedDevices also part of
6906 // available input devices
6907 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006908 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006909 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006910 ALOGV("%s: Input device list is empty! for profile %s",
6911 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006912 continue;
6913 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306914
6915 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6916 && availProfileDevices.areAllDevicesAttached()) {
6917 ALOGV("%s skip opening input for mmap profile %s", __func__,
6918 inProfile->getTagName().c_str());
6919 continue;
6920 }
6921
Eric Laurentc71b11b2024-06-03 12:54:53 +00006922 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6923 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006924
6925 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6926 status_t status = inputDesc->open(nullptr,
6927 availProfileDevices.itemAt(0),
6928 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306929 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006930 &input);
6931 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306932 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6933 __func__, availProfileDevices.toString().c_str(),
6934 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006935 continue;
6936 }
6937 for (const auto &device : availProfileDevices) {
6938 // give a valid ID to an attached device once confirmed it is reachable
6939 if (!device->isAttached()) {
6940 device->attach(hwModule);
6941 device->importAudioPortAndPickAudioProfile(inProfile, true);
6942 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006943 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006944 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6945 }
6946 }
6947 inputDesc->close();
6948 }
6949 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006950
6951 // Check if spatializer outputs can be closed until used.
6952 // mOutputs vector never contains duplicated outputs at this point.
6953 std::vector<audio_io_handle_t> outputsClosed;
6954 for (size_t i = 0; i < mOutputs.size(); i++) {
6955 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6956 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6957 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6958 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006959 nextAudioPortGeneration();
6960 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6961 if (index >= 0) {
6962 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6963 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6964 patchDesc->getAfHandle(), 0);
6965 mAudioPatches.removeItemsAt(index);
6966 mpClientInterface->onAudioPatchListUpdate();
6967 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006968 desc->close();
6969 }
6970 }
6971 for (auto output : outputsClosed) {
6972 removeOutput(output);
6973 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006974}
6975
Eric Laurent98e38192018-02-15 18:31:53 -08006976void AudioPolicyManager::addOutput(audio_io_handle_t output,
6977 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006978{
Eric Laurent1c333e22014-05-20 10:48:17 -07006979 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006980 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006981 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006982 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006983 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006984}
6985
François Gaffie53615e22015-03-19 09:24:12 +01006986void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6987{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006988 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6989 ALOGV("%s: removing primary output", __func__);
6990 mPrimaryOutput = nullptr;
6991 }
François Gaffie53615e22015-03-19 09:24:12 +01006992 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006993 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006994}
6995
Eric Laurent98e38192018-02-15 18:31:53 -08006996void AudioPolicyManager::addInput(audio_io_handle_t input,
6997 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006998{
Eric Laurent1c333e22014-05-20 10:48:17 -07006999 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07007000 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07007001}
Eric Laurente552edb2014-03-10 17:42:56 -07007002
François Gaffie11d30102018-11-02 16:09:09 +01007003status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01007004 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01007005 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007006{
François Gaffie11d30102018-11-02 16:09:09 +01007007 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07007008 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07007009 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07007010
François Gaffie11d30102018-11-02 16:09:09 +01007011 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007012 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007013 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007014 }
Eric Laurente552edb2014-03-10 17:42:56 -07007015
Eric Laurent3b73df72014-03-11 09:06:29 -07007016 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07007017 // first call getAudioPort to get the supported attributes from the HAL
7018 struct audio_port_v7 port = {};
7019 device->toAudioPort(&port);
7020 status_t status = mpClientInterface->getAudioPort(&port);
7021 if (status == NO_ERROR) {
7022 device->importAudioPort(port);
7023 }
7024
7025 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07007026 for (size_t i = 0; i < mOutputs.size(); i++) {
7027 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007028 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07007029 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01007030 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
7031 mOutputs.keyAt(i), device->toString().c_str());
7032 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007033 }
7034 }
7035 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007036 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007037 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007038 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7039 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007040 if (profile->supportsDevice(device)) {
7041 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307042 ALOGV("%s(): adding profile %s from module %s",
7043 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007044 }
7045 }
7046 }
7047
Eric Laurent7b279bb2015-12-14 10:18:23 -08007048 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007049
Eric Laurente552edb2014-03-10 17:42:56 -07007050 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007051 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007052 return BAD_VALUE;
7053 }
7054
7055 // open outputs for matching profiles if needed. Direct outputs are also opened to
7056 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7057 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007058 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007059
7060 // nothing to do if one output is already opened for this profile
7061 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007062 for (j = 0; j < outputs.size(); j++) {
7063 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007064 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007065 // matching profile: save the sample rates, format and channel masks supported
7066 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007067 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007068 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007069 }
Eric Laurente552edb2014-03-10 17:42:56 -07007070 break;
7071 }
7072 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007073 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007074 continue;
7075 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307076 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7077 ALOGV("%s skip opening output for mmap profile %s",
7078 __func__, profile->getTagName().c_str());
7079 continue;
7080 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007081 if (!profile->canOpenNewIo()) {
7082 ALOGW("Max Output number %u already opened for this profile %s",
7083 profile->maxOpenCount, profile->getTagName().c_str());
7084 continue;
7085 }
7086
Eric Laurent83efe1c2017-07-09 16:51:08 -07007087 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007088 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007089 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7090 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007091 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007092 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007093 profiles.removeAt(profile_index);
7094 profile_index--;
7095 } else {
7096 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007097 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007098 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007099 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7100 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007101 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007102 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007103
François Gaffie11d30102018-11-02 16:09:09 +01007104 if (device_distinguishes_on_address(deviceType)) {
7105 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7106 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307107 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7108 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007109 }
Eric Laurente552edb2014-03-10 17:42:56 -07007110 ALOGV("checkOutputsForDevice(): adding output %d", output);
7111 }
7112 }
7113
7114 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007115 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007116 return BAD_VALUE;
7117 }
Eric Laurentd4692962014-05-05 18:13:44 -07007118 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007119 // check if one opened output is not needed any more after disconnecting one device
7120 for (size_t i = 0; i < mOutputs.size(); i++) {
7121 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007122 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007123 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007124 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007125 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007126 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007127 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007128 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7129 mOutputs.keyAt(i));
7130 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007131 }
Eric Laurente552edb2014-03-10 17:42:56 -07007132 }
7133 }
Eric Laurentd4692962014-05-05 18:13:44 -07007134 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007135 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007136 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7137 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007138 if (!profile->supportsDevice(device)) {
7139 continue;
7140 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307141 ALOGV("%s(): clearing direct output profile %s on module %s",
7142 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007143 profile->clearAudioProfiles();
7144 if (!profile->hasDynamicAudioProfile()) {
7145 continue;
7146 }
7147 // When a device is disconnected, if there is an IOProfile that contains dynamic
7148 // profiles and supports the disconnected device, call getAudioPort to repopulate
7149 // the capabilities of the devices that is supported by the IOProfile.
7150 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7151 if (supportedDevice == device ||
7152 !mAvailableOutputDevices.contains(supportedDevice)) {
7153 continue;
7154 }
7155 struct audio_port_v7 port;
7156 supportedDevice->toAudioPort(&port);
7157 status_t status = mpClientInterface->getAudioPort(&port);
7158 if (status == NO_ERROR) {
7159 supportedDevice->importAudioPort(port);
7160 }
Eric Laurente552edb2014-03-10 17:42:56 -07007161 }
7162 }
7163 }
7164 }
7165 return NO_ERROR;
7166}
7167
François Gaffie11d30102018-11-02 16:09:09 +01007168status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007169 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007170{
François Gaffie11d30102018-11-02 16:09:09 +01007171 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007172 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007173 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007174 }
7175
Eric Laurentd4692962014-05-05 18:13:44 -07007176 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007177 sp<AudioInputDescriptor> desc;
7178
jiabinbf5f4262023-04-12 21:48:34 +00007179 // first call getAudioPort to get the supported attributes from the HAL
7180 struct audio_port_v7 port = {};
7181 device->toAudioPort(&port);
7182 status_t status = mpClientInterface->getAudioPort(&port);
7183 if (status == NO_ERROR) {
7184 device->importAudioPort(port);
7185 }
7186
Eric Laurent0dd51852019-04-19 18:18:58 -07007187 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007188 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007189 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007190 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007191 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007192 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007193 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007194
François Gaffie11d30102018-11-02 16:09:09 +01007195 if (profile->supportsDevice(device)) {
7196 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307197 ALOGV("%s : adding profile %s from module %s", __func__,
7198 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007199 }
7200 }
7201 }
7202
Eric Laurent0dd51852019-04-19 18:18:58 -07007203 if (profiles.isEmpty()) {
7204 ALOGW("%s: No input profile available for device %s",
7205 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007206 return BAD_VALUE;
7207 }
7208
7209 // open inputs for matching profiles if needed. Direct inputs are also opened to
7210 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7211 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7212
Eric Laurent1c333e22014-05-20 10:48:17 -07007213 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007214
Eric Laurentd4692962014-05-05 18:13:44 -07007215 // nothing to do if one input is already opened for this profile
7216 size_t input_index;
7217 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7218 desc = mInputs.valueAt(input_index);
7219 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007220 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007221 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007222 }
Eric Laurentd4692962014-05-05 18:13:44 -07007223 break;
7224 }
7225 }
7226 if (input_index != mInputs.size()) {
7227 continue;
7228 }
7229
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307230 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7231 ALOGV("%s skip opening input for mmap profile %s",
7232 __func__, profile->getTagName().c_str());
7233 continue;
7234 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007235 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307236 ALOGW("%s Max Input number %u already opened for this profile %s",
7237 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007238 continue;
7239 }
7240
Eric Laurentc71b11b2024-06-03 12:54:53 +00007241 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007242 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307243 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307244 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7245 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007246
Eric Laurentcf2c0212014-07-25 16:20:43 -07007247 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007248 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007249 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007250 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007251 mpClientInterface->setParameters(input, String8(param));
7252 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007253 }
jiabin12537fc2023-10-12 17:56:08 +00007254 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007255 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307256 ALOGW("%s direct input missing param for profile %s", __func__,
7257 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007258 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007259 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007260 }
7261
Eric Laurent0dd51852019-04-19 18:18:58 -07007262 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007263 addInput(input, desc);
7264 }
7265 } // endif input != 0
7266
Eric Laurentcf2c0212014-07-25 16:20:43 -07007267 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307268 ALOGW("%s could not open input for device %s on profile %s", __func__,
7269 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007270 profiles.removeAt(profile_index);
7271 profile_index--;
7272 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007273 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007274 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007275 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307276 ALOGV("%s: adding input %d for profile %s", __func__,
7277 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007278
7279 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307280 ALOGV("%s: closing input %d for profile %s", __func__,
7281 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007282 closeInput(input);
7283 }
Eric Laurentd4692962014-05-05 18:13:44 -07007284 }
7285 } // end scan profiles
7286
7287 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007288 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007289 return BAD_VALUE;
7290 }
7291 } else {
7292 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007293 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007294 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007295 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007296 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007297 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007298 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007299 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307300 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7301 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007302 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007303 }
7304 }
7305 }
7306 } // end disconnect
7307
7308 return NO_ERROR;
7309}
7310
7311
Eric Laurente0720872014-03-11 09:30:41 -07007312void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007313{
7314 ALOGV("closeOutput(%d)", output);
7315
François Gaffie1c878552018-11-22 16:53:21 +01007316 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7317 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007318 ALOGW("closeOutput() unknown output %d", output);
7319 return;
7320 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007321 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007322 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007323
Eric Laurente552edb2014-03-10 17:42:56 -07007324 // look for duplicated outputs connected to the output being removed.
7325 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007326 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7327 if (dupOutput->isDuplicated() &&
7328 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7329 sp<SwAudioOutputDescriptor> remainingOutput =
7330 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007331 // As all active tracks on duplicated output will be deleted,
7332 // and as they were also referenced on the other output, the reference
7333 // count for their stream type must be adjusted accordingly on
7334 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007335 const bool wasActive = remainingOutput->isActive();
7336 // Note: no-op on the closing output where all clients has already been set inactive
7337 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007338 // stop() will be a no op if the output is still active but is needed in case all
7339 // active streams refcounts where cleared above
7340 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007341 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007342 }
Eric Laurente552edb2014-03-10 17:42:56 -07007343 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7344 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7345
7346 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007347 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007348 }
7349 }
7350
Eric Laurent05b90f82014-08-27 15:32:29 -07007351 nextAudioPortGeneration();
7352
François Gaffie1c878552018-11-22 16:53:21 +01007353 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007354 if (index >= 0) {
7355 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007356 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7357 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007358 mAudioPatches.removeItemsAt(index);
7359 mpClientInterface->onAudioPatchListUpdate();
7360 }
7361
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007362 if (closingOutputWasActive) {
7363 closingOutput->stop();
7364 }
François Gaffie1c878552018-11-22 16:53:21 +01007365 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007366 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007367 for (const auto device : closingOutput->devices()) {
7368 device->setPreferredConfig(nullptr);
7369 }
7370 }
Eric Laurente552edb2014-03-10 17:42:56 -07007371
François Gaffie53615e22015-03-19 09:24:12 +01007372 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007373 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007374 if (closingOutput == mSpatializerOutput) {
7375 mSpatializerOutput.clear();
7376 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007377
7378 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7379 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007380 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007381 bool directOutputOpen = false;
7382 for (size_t i = 0; i < mOutputs.size(); i++) {
7383 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7384 directOutputOpen = true;
7385 break;
7386 }
7387 }
7388 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007389 ALOGV("no direct outputs open, reset MSD patches");
7390 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7391 // how output devices for patching are resolved. Avoid by caching and reusing the
7392 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7393 // devices to patch to. This may be complicated by the fact that devices may become
7394 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007395 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007396 }
7397 }
jiabin220eea12024-05-17 17:55:20 +00007398
7399 if (closingOutput->mPreferredAttrInfo != nullptr) {
7400 closingOutput->mPreferredAttrInfo->resetActiveClient();
7401 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007402}
7403
7404void AudioPolicyManager::closeInput(audio_io_handle_t input)
7405{
7406 ALOGV("closeInput(%d)", input);
7407
7408 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7409 if (inputDesc == NULL) {
7410 ALOGW("closeInput() unknown input %d", input);
7411 return;
7412 }
7413
Eric Laurent6a94d692014-05-20 11:18:06 -07007414 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007415
François Gaffie11d30102018-11-02 16:09:09 +01007416 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007417 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007418 if (index >= 0) {
7419 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007420 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7421 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007422 mAudioPatches.removeItemsAt(index);
7423 mpClientInterface->onAudioPatchListUpdate();
7424 }
7425
François Gaffie6ebbce02023-07-19 13:27:53 +02007426 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007427 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007428 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007429
François Gaffie11d30102018-11-02 16:09:09 +01007430 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7431 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007432 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007433 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007434 }
Eric Laurente552edb2014-03-10 17:42:56 -07007435}
7436
François Gaffie11d30102018-11-02 16:09:09 +01007437SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7438 const DeviceVector &devices,
7439 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007440{
7441 SortedVector<audio_io_handle_t> outputs;
7442
François Gaffie11d30102018-11-02 16:09:09 +01007443 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007444 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007445 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007446 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007447 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007448 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007449 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007450 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007451 outputs.add(openOutputs.keyAt(i));
7452 }
7453 }
7454 return outputs;
7455}
7456
Mikhail Naganov37977152018-07-11 15:54:44 -07007457void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7458{
7459 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7460 // output is suspended before any tracks are moved to it
7461 checkA2dpSuspend();
7462 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007463 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007464 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007465 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007466 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007467 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7468 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7469 // configuration changes will ultimately be rerouted correctly. We can still avoid
7470 // unnecessary rerouting by caching and reusing the arguments to
7471 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7472 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007473 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007474 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007475 // an event that changed routing likely occurred, inform upper layers
7476 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007477}
7478
François Gaffiec005e562018-11-06 15:04:49 +01007479bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7480 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007481{
François Gaffiec005e562018-11-06 15:04:49 +01007482 return mEngine->getProductStrategyForAttributes(lAttr) ==
7483 mEngine->getProductStrategyForAttributes(rAttr);
7484}
7485
Francois Gaffieff1eb522020-05-06 18:37:04 +02007486void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7487{
7488 for (size_t i = 0; i < mAudioSources.size(); i++) {
7489 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7490 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007491 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007492 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007493 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007494 }
7495 }
7496}
7497
7498void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7499{
7500 for (size_t i = 0; i < mAudioSources.size(); i++) {
7501 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7502 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7503 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7504 disconnectAudioSource(sourceDesc);
7505 }
7506 }
7507}
7508
François Gaffiec005e562018-11-06 15:04:49 +01007509void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7510{
7511 auto psId = mEngine->getProductStrategyForAttributes(attr);
7512
7513 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7514 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007515
François Gaffie11d30102018-11-02 16:09:09 +01007516 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7517 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007518
Eric Laurentc209fe42020-06-05 18:11:23 -07007519 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007520 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007521 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007522 // take into account dynamic audio policies related changes: if a client is now associated
7523 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007524 // invalidate clients on outputs that do not support all the newly selected devices for the
7525 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007526 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007527 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007528 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007529 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007530 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007531
Eric Laurentc209fe42020-06-05 18:11:23 -07007532 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7533 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7534 continue;
7535 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007536 if (!desc->supportsAllDevices(newDevices)) {
7537 invalidatedOutputs.push_back(desc);
7538 break;
7539 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007540 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007541 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007542 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7543 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7544 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007545 if (status == OK) {
7546 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7547 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7548 maxLatency = desc->latency();
7549 }
7550 invalidatedOutputs.push_back(desc);
7551 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007552 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007553 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007554 }
7555 }
7556
Eric Laurent56ed8842022-11-15 16:04:41 +01007557 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007558 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7559 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007560 for (audio_io_handle_t srcOut : srcOutputs) {
7561 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007562 if (desc == nullptr) continue;
7563
7564 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007565 maxLatency = desc->latency();
7566 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007567
Eric Laurent56ed8842022-11-15 16:04:41 +01007568 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007569 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007570 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007571 // a client on a non direct outputs has necessarily a linear PCM format
7572 // so we can call selectOutput() safely
7573 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7574 client->flags(),
7575 client->config().format,
7576 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007577 client->config().sample_rate,
7578 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007579 if (newOutput != srcOut) {
7580 invalidate = true;
7581 break;
7582 }
7583 } else {
7584 sp<IOProfile> profile = getProfileForOutput(newDevices,
7585 client->config().sample_rate,
7586 client->config().format,
7587 client->config().channel_mask,
7588 client->flags(),
7589 true /* directOnly */);
7590 if (profile != desc->mProfile) {
7591 invalidate = true;
7592 break;
7593 }
7594 }
7595 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007596 // mute strategy while moving tracks from one output to another
7597 if (invalidate) {
7598 invalidatedOutputs.push_back(desc);
7599 if (desc->isStrategyActive(psId)) {
7600 setStrategyMute(psId, true, desc);
7601 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7602 newDevices.types());
7603 }
Eric Laurente552edb2014-03-10 17:42:56 -07007604 }
François Gaffiec005e562018-11-06 15:04:49 +01007605 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007606 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007607 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007608 }
Eric Laurente552edb2014-03-10 17:42:56 -07007609 }
7610
Eric Laurent56ed8842022-11-15 16:04:41 +01007611 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7612 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7613 std::to_string(srcOutputs[0]).c_str(),
7614 std::to_string(dstOutputs[0]).c_str());
7615
François Gaffiec005e562018-11-06 15:04:49 +01007616 // Move effects associated to this stream from previous output to new output
7617 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007618 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007619 }
François Gaffiec005e562018-11-06 15:04:49 +01007620 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007621 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007622 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007623 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007624 desc->setTracksInvalidatedStatusByStrategy(psId);
7625 }
Eric Laurente552edb2014-03-10 17:42:56 -07007626 }
7627 }
7628}
7629
Eric Laurente0720872014-03-11 09:30:41 -07007630void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007631{
François Gaffiec005e562018-11-06 15:04:49 +01007632 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7633 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7634 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007635 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007636 }
Eric Laurente552edb2014-03-10 17:42:56 -07007637}
7638
Kevin Rocard153f92d2018-12-18 18:33:28 -08007639void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007640 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007641 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007642 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007643 for (size_t i = 0; i < mOutputs.size(); i++) {
7644 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7645 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007646 sp<AudioPolicyMix> primaryMix;
7647 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007648 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007649 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7650 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7651 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007652 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7653 for (auto &secondaryMix : secondaryMixes) {
7654 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7655 if (outputDesc != nullptr &&
7656 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7657 secondaryDescs.push_back(outputDesc);
7658 }
7659 }
7660
jiabinc44b3462022-12-08 12:52:31 -08007661 if (status != OK &&
7662 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7663 // When it failed to query secondary output, only invalidate the client that is not
7664 // MMAP. The reason is that MMAP stream will not support secondary output.
7665 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007666 } else if (!std::equal(
7667 client->getSecondaryOutputs().begin(),
7668 client->getSecondaryOutputs().end(),
7669 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007670 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7671 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007672 // If the format is not PCM, the tracks should be invalidated to get correct
7673 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007674 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007675 } else {
7676 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7677 std::vector<audio_io_handle_t> secondaryOutputIds;
7678 for (const auto &secondaryDesc: secondaryDescs) {
7679 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7680 weakSecondaryDescs.push_back(secondaryDesc);
7681 }
7682 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7683 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007684 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007685 }
7686 }
7687 }
jiabin10a03f12021-05-07 23:46:28 +00007688 if (!trackSecondaryOutputs.empty()) {
7689 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7690 }
jiabinc44b3462022-12-08 12:52:31 -08007691 if (!clientsToInvalidate.empty()) {
7692 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7693 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007694 }
7695}
7696
Eric Laurent2517af32020-11-25 15:31:27 +01007697bool AudioPolicyManager::isScoRequestedForComm() const {
7698 AudioDeviceTypeAddrVector devices;
7699 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7700 for (const auto &device : devices) {
7701 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7702 return true;
7703 }
7704 }
7705 return false;
7706}
7707
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007708bool AudioPolicyManager::isHearingAidUsedForComm() const {
7709 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7710 true /*fromCache*/);
7711 for (const auto &device : devices) {
7712 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7713 return true;
7714 }
7715 }
7716 return false;
7717}
7718
7719
Eric Laurente0720872014-03-11 09:30:41 -07007720void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007721{
François Gaffie53615e22015-03-19 09:24:12 +01007722 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007723 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007724 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007725 return;
7726 }
7727
Eric Laurent3a4311c2014-03-17 12:00:47 -07007728 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007729 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7730 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007731 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007732
7733 // if suspended, restore A2DP output if:
7734 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007735 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007736 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007737 //
Eric Laurentf732e072016-08-03 19:30:28 -07007738 // if not suspended, suspend A2DP output if:
7739 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007740 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007741 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007742 //
7743 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007744 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007745 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007746 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007747 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007748
7749 mpClientInterface->restoreOutput(a2dpOutput);
7750 mA2dpSuspended = false;
7751 }
7752 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007753 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007754 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007755 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007756 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007757
7758 mpClientInterface->suspendOutput(a2dpOutput);
7759 mA2dpSuspended = true;
7760 }
7761 }
7762}
7763
François Gaffie11d30102018-11-02 16:09:09 +01007764DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7765 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007766{
François Gaffiedb1755b2023-09-01 11:50:35 +02007767 if (outputDesc == nullptr) {
7768 return DeviceVector{};
7769 }
François Gaffie11d30102018-11-02 16:09:09 +01007770
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007771 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007772 if (index >= 0) {
7773 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007774 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007775 ALOGV("%s device %s forced by patch %d", __func__,
7776 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7777 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007778 }
7779 }
7780
Dean Wheatley514b4312020-06-17 21:45:00 +10007781 // Do not retrieve engine device for outputs through MSD
7782 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7783 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7784 return outputDesc->devices();
7785 }
7786
Eric Laurent97ac8712018-07-27 18:59:02 -07007787 // Honor explicit routing requests only if no client using default routing is active on this
7788 // input: a specific app can not force routing for other apps by setting a preferred device.
7789 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007790 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007791 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007792 if (device != nullptr) {
7793 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007794 }
7795
François Gaffiea807ef92018-11-05 10:44:33 +01007796 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7797 // of setForceUse / Default Bus device here
7798 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7799 if (device != nullptr) {
7800 return DeviceVector(device);
7801 }
7802
François Gaffiedb1755b2023-09-01 11:50:35 +02007803 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007804 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7805 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307806 auto hasStreamActive = [&](auto stream) {
7807 return hasStream(streams, stream) && isStreamActive(stream, 0);
7808 };
Eric Laurent484e9272018-06-07 17:29:23 -07007809
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307810 auto doGetOutputDevicesForVoice = [&]() {
7811 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007812 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307813 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007814 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7815 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307816 };
7817
7818 // With low-latency playing on speaker, music on WFD, when the first low-latency
7819 // output is stopped, getNewOutputDevices checks for a product strategy
7820 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007821 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307822 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7823 // stream is associated to the output descriptor.
7824 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7825 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7826 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7827 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007828 // Retrieval of devices for voice DL is done on primary output profile, cannot
7829 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007830 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007831 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7832 break;
7833 }
Eric Laurente552edb2014-03-10 17:42:56 -07007834 }
François Gaffiec005e562018-11-06 15:04:49 +01007835 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007836 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007837}
7838
François Gaffie11d30102018-11-02 16:09:09 +01007839sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7840 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007841{
François Gaffie11d30102018-11-02 16:09:09 +01007842 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007843
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007844 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007845 if (index >= 0) {
7846 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007847 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007848 ALOGV("getNewInputDevice() device %s forced by patch %d",
7849 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7850 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007851 }
7852 }
7853
Eric Laurent97ac8712018-07-27 18:59:02 -07007854 // Honor explicit routing requests only if no client using default routing is active on this
Eric Laurentd8add2b2024-11-15 16:05:32 +00007855 // input or if all active clients are from the same app: a specific app can not force routing
7856 // for other apps by setting a preferred device.
Eric Laurent97ac8712018-07-27 18:59:02 -07007857 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007858 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7859 if (device != nullptr) {
7860 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007861 }
7862
Eric Laurentdc95a252018-04-12 12:46:56 -07007863 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007864 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007865 audio_attributes_t attributes;
7866 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007867 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007868 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7869 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007870 attributes = topClient->attributes();
7871 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007872 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007873 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007874 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7875 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007876 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007877 }
7878
Francois Gaffie716e1432019-01-14 16:58:59 +01007879 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7880 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007881 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007882 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007883 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007884 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007885
Eric Laurente552edb2014-03-10 17:42:56 -07007886 return device;
7887}
7888
Eric Laurent794fde22016-03-11 09:50:45 -08007889bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7890 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007891 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007892}
7893
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007894status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007895 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007896 if (devices == nullptr) {
7897 return BAD_VALUE;
7898 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007899
Andy Hung6d23c0f2022-02-16 09:37:15 -08007900 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007901 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7902 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007903 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007904 for (const auto& device : curDevices) {
7905 devices->push_back(device->getDeviceTypeAddr());
7906 }
7907 return NO_ERROR;
7908}
7909
Eric Laurente0720872014-03-11 09:30:41 -07007910void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007911 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007912 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007913 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007914 updateDevicesAndOutputs();
7915 break;
7916 default:
7917 break;
7918 }
7919}
7920
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007921uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007922
7923 // skip beacon mute management if a dedicated TTS output is available
7924 if (mTtsOutputAvailable) {
7925 return 0;
7926 }
7927
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007928 switch(event) {
7929 case STARTING_OUTPUT:
7930 mBeaconMuteRefCount++;
7931 break;
7932 case STOPPING_OUTPUT:
7933 if (mBeaconMuteRefCount > 0) {
7934 mBeaconMuteRefCount--;
7935 }
7936 break;
7937 case STARTING_BEACON:
7938 mBeaconPlayingRefCount++;
7939 break;
7940 case STOPPING_BEACON:
7941 if (mBeaconPlayingRefCount > 0) {
7942 mBeaconPlayingRefCount--;
7943 }
7944 break;
7945 }
7946
7947 if (mBeaconMuteRefCount > 0) {
7948 // any playback causes beacon to be muted
7949 return setBeaconMute(true);
7950 } else {
7951 // no other playback: unmute when beacon starts playing, mute when it stops
7952 return setBeaconMute(mBeaconPlayingRefCount == 0);
7953 }
7954}
7955
7956uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7957 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7958 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7959 // keep track of muted state to avoid repeating mute/unmute operations
7960 if (mBeaconMuted != mute) {
7961 // mute/unmute AUDIO_STREAM_TTS on all outputs
7962 ALOGV("\t muting %d", mute);
7963 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007964 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7965 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7966 ALOGV("\t no tts volume source available");
7967 return 0;
7968 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007969 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007970 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007971 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7972 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007973 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007974 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007975 maxLatency = latency;
7976 }
7977 }
7978 mBeaconMuted = mute;
7979 return maxLatency;
7980 }
7981 return 0;
7982}
7983
Eric Laurente0720872014-03-11 09:30:41 -07007984void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007985{
François Gaffiec005e562018-11-06 15:04:49 +01007986 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007987 mPreviousOutputs = mOutputs;
7988}
7989
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007990uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007991 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007992 uint32_t delayMs)
7993{
7994 // mute/unmute strategies using an incompatible device combination
7995 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7996 // if unmuting, unmute only after the specified delay
7997 if (outputDesc->isDuplicated()) {
7998 return 0;
7999 }
8000
8001 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01008002 DeviceVector devices = outputDesc->devices();
8003 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07008004
François Gaffiec005e562018-11-06 15:04:49 +01008005 auto productStrategies = mEngine->getOrderedProductStrategies();
8006 for (const auto &productStrategy : productStrategies) {
8007 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
8008 DeviceVector curDevices =
8009 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
8010 curDevices = curDevices.filter(outputDesc->supportedDevices());
8011 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07008012 bool doMute = false;
8013
François Gaffiec005e562018-11-06 15:04:49 +01008014 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07008015 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01008016 outputDesc->setStrategyMutedByDevice(productStrategy, true);
8017 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07008018 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01008019 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07008020 }
Eric Laurent99401132014-05-07 19:48:15 -07008021 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07008022 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07008023 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07008024 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01008025 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07008026 continue;
8027 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308028 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01008029 mute ? "muting" : "unmuting", curDevices.toString().c_str());
8030 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
8031 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07008032 if (mute) {
8033 // FIXME: should not need to double latency if volume could be applied
8034 // immediately by the audioflinger mixer. We must account for the delay
8035 // between now and the next time the audioflinger thread for this output
8036 // will process a buffer (which corresponds to one buffer size,
8037 // usually 1/2 or 1/4 of the latency).
8038 if (muteWaitMs < desc->latency() * 2) {
8039 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008040 }
8041 }
8042 }
8043 }
8044 }
8045 }
8046
Eric Laurent99401132014-05-07 19:48:15 -07008047 // temporary mute output if device selection changes to avoid volume bursts due to
8048 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008049 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008050 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008051
Eric Laurentdc462862016-07-19 12:29:53 -07008052 if (muteWaitMs < tempMuteWaitMs) {
8053 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008054 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008055
8056 // If recommended duration is defined, replace temporary mute duration to avoid
8057 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8058 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8059 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8060 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8061 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8062
François Gaffieaaac0fd2018-11-22 17:56:39 +01008063 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8064 // make sure that we do not start the temporary mute period too early in case of
8065 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008066 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8067 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8068 delayMs + tempMuteDurationMs,
8069 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008070 }
8071 }
8072
Eric Laurente552edb2014-03-10 17:42:56 -07008073 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8074 if (muteWaitMs > delayMs) {
8075 muteWaitMs -= delayMs;
8076 usleep(muteWaitMs * 1000);
8077 return muteWaitMs;
8078 }
8079 return 0;
8080}
8081
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308082uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8083 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008084 const DeviceVector &devices,
8085 bool force,
8086 int delayMs,
8087 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008088 bool requiresMuteCheck, bool requiresVolumeCheck,
8089 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008090{
jiabin3ff8d7d2022-12-13 06:27:44 +00008091 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308092 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8093 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8094 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008095 uint32_t muteWaitMs;
8096
8097 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308098 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008099 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308100 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008101 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008102 return muteWaitMs;
8103 }
Eric Laurente552edb2014-03-10 17:42:56 -07008104
8105 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008106 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008107 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008108 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008109
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308110 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8111 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008112
8113 if (!filteredDevices.isEmpty()) {
8114 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008115 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008116
8117 // if the outputs are not materially active, there is no need to mute.
8118 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008119 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008120 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308121 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8122 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008123 muteWaitMs = 0;
8124 }
Eric Laurente552edb2014-03-10 17:42:56 -07008125
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008126 bool outputRouted = outputDesc->isRouted();
8127
Eric Laurent79ea9582020-06-11 18:49:24 -07008128 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8129 // output profile or if new device is not supported AND previous device(s) is(are) still
8130 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008131 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308132 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8133 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008134 // restore previous device after evaluating strategy mute state
8135 outputDesc->setDevices(prevDevices);
8136 return muteWaitMs;
8137 }
8138
Eric Laurente552edb2014-03-10 17:42:56 -07008139 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008140 // the requested device is AUDIO_DEVICE_NONE
8141 // OR the requested device is the same as current device
8142 // AND force is not specified
8143 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008144 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008145 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308146 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8147 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8148 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008149 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308150 ALOGV("%s %s setting same device on routed output, force apply volumes",
8151 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008152 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8153 }
Eric Laurente552edb2014-03-10 17:42:56 -07008154 return muteWaitMs;
8155 }
8156
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308157 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8158 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008159
Eric Laurente552edb2014-03-10 17:42:56 -07008160 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008161 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008162 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008163 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008164 PatchBuilder patchBuilder;
8165 patchBuilder.addSource(outputDesc);
8166 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8167 for (const auto &filteredDevice : filteredDevices) {
8168 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008169 }
8170
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008171 // Add half reported latency to delayMs when muteWaitMs is null in order
8172 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008173 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8174 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8175 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008176 }
Eric Laurente552edb2014-03-10 17:42:56 -07008177
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008178 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8179 if (!skipMuteDelay) {
8180 // update stream volumes according to new device
8181 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8182 }
Eric Laurente552edb2014-03-10 17:42:56 -07008183
8184 return muteWaitMs;
8185}
8186
Eric Laurentc75307b2015-03-17 15:29:32 -07008187status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008188 int delayMs,
8189 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008190{
Eric Laurent6a94d692014-05-20 11:18:06 -07008191 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008192 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8193 return INVALID_OPERATION;
8194 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008195 if (patchHandle) {
8196 index = mAudioPatches.indexOfKey(*patchHandle);
8197 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008198 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008199 }
8200 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008201 return INVALID_OPERATION;
8202 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008203 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008204 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008205 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008206 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008207 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008208 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008209 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008210 return status;
8211}
8212
8213status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008214 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008215 bool force,
8216 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008217{
8218 status_t status = NO_ERROR;
8219
Eric Laurent1f2f2232014-06-02 12:01:23 -07008220 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008221 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8222 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008223
François Gaffie11d30102018-11-02 16:09:09 +01008224 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008225 PatchBuilder patchBuilder;
8226 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008227 // AUDIO_SOURCE_HOTWORD is for internal use only:
8228 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008229 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8230 auto result = usecase;
8231 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8232 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8233 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008234 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008235 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008236 if (audio_is_remote_submix_device(device->type())) {
8237 // remote submix HAL does not support audio conversion, need source device
8238 // audio config to match the sink input descriptor audio config, otherwise AIDL
8239 // HAL patching will fail
8240 audio_port_config srcDevicePortConfig = {};
8241 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8242 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8243 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8244 srcDevicePortConfig.format = inputDesc->getFormat();
8245 patchBuilder.addSource(srcDevicePortConfig);
8246 } else {
8247 patchBuilder.addSource(device);
8248 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008249 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008250 }
8251 }
8252 return status;
8253}
8254
Eric Laurent6a94d692014-05-20 11:18:06 -07008255status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8256 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008257{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008258 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008259 ssize_t index;
8260 if (patchHandle) {
8261 index = mAudioPatches.indexOfKey(*patchHandle);
8262 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008263 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008264 }
8265 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008266 return INVALID_OPERATION;
8267 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008268 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008269 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008270 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008271 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008272 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008273 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008274 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008275 return status;
8276}
8277
François Gaffie11d30102018-11-02 16:09:09 +01008278sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008279 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008280 audio_format_t& format,
8281 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008282 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008283{
8284 // Choose an input profile based on the requested capture parameters: select the first available
8285 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008286 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008287
Atneya Nair0f0a8032022-12-12 16:20:12 -08008288 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8289 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8290 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8291
8292 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008293
jiabin2fd710d2022-05-02 23:20:22 +00008294 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008295 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008296 uint32_t inexactSamplingRate = 0;
8297 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8298 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008299 uint32_t updatedSamplingRate = 0;
8300 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8301 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8302 for (const auto& hwModule : mHwModules) {
8303 for (const auto& profile : hwModule->getInputProfiles()) {
8304 // profile->log();
8305 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008306 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008307 DeviceVector(device),
8308 samplingRate,
8309 &updatedSamplingRate,
8310 format,
8311 &updatedFormat,
8312 channelMask,
8313 &updatedChannelMask,
8314 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008315 (audio_output_flags_t) flags);
8316 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008317 samplingRate = updatedSamplingRate;
8318 format = updatedFormat;
8319 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008320 return profile;
jiabin91beb492024-10-16 21:53:36 +00008321 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8322 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8323 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8324 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008325 inexactSamplingRate = updatedSamplingRate;
8326 inexactFormat = updatedFormat;
8327 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008328 }
8329 }
8330 }
8331
jiabin91beb492024-10-16 21:53:36 +00008332 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008333 samplingRate = inexactSamplingRate;
8334 format = inexactFormat;
8335 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008336 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008337 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8338 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8339 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8340 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8341 flags = AUDIO_INPUT_FLAG_NONE;
8342 } else { // fail
8343 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8344 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8345 samplingRate, format, channelMask, oriFlags);
8346 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008347 }
8348 }
jiabin2fd710d2022-05-02 23:20:22 +00008349
8350 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008351}
8352
Vlad Popa87e0e582024-05-20 18:49:20 -07008353float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8354 VolumeSource volumeSource,
8355 int index,
8356 const DeviceTypeSet &deviceTypes)
8357{
8358 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8359 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8360 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8361
8362 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008363 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8364 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8365 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008366 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8367 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8368 ALOGD("%s: no group matching with %s", __FUNCTION__,
8369 toString(attributesToDriveAbs).c_str());
8370 return volumeDb;
8371 }
8372
8373 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8374 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8375 if (vsToDriveAbs == volumeSource) {
8376 // attenuation is applied by the abs volume controller
Vlad Popa444e95e2024-11-07 18:26:20 -08008377 // do not mute LE broadcast to allow the secondary device to continue playing
8378 return (index != 0 || volumeDevice == AUDIO_DEVICE_OUT_BLE_BROADCAST) ? volumeDbMax
8379 : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008380 } else {
8381 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8382 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8383 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8384 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8385 curvesAbs.getVolumeIndexMax());
8386 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8387 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8388 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8389 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8390 return newVolumeDb;
8391 }
8392 }
8393 return volumeDb;
8394 } else {
8395 return volumeDb;
8396 }
8397}
8398
François Gaffieaaac0fd2018-11-22 17:56:39 +01008399float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8400 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008401 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008402 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008403 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008404 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008405{
Vlad Popa9d482762024-06-21 16:40:23 -07008406 float volumeDb;
8407 if (adjustAttenuation) {
8408 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8409 } else {
8410 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8411 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008412 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8413 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8414
8415 if (!computeInternalInteraction) {
8416 return volumeDb;
8417 }
8418
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008419 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8420 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8421 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8422 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008423 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8424 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8425 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8426 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8427 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008428 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008429 mOutputs.isActive(ringVolumeSrc, 0)) {
8430 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008431 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008432 adjustAttenuation,
8433 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008434 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008435 }
8436
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008437 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008438 if ((volumeSource != callVolumeSrc && (isInCall() ||
8439 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008440 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008441 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8442 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008443 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8444 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8445 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008446 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008447 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008448 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008449 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008450 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008451 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008452 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008453 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8454 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8455 // programmatically muted.
8456 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8457 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8458 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008459 bool exemptFromCapping =
8460 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8461 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008462 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8463 volumeSource, volumeDb);
8464 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008465 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8466 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8467 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008468 }
8469 }
Eric Laurente552edb2014-03-10 17:42:56 -07008470 // if a headset is connected, apply the following rules to ring tones and notifications
8471 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008472 // - always attenuate notifications volume by 6dB
8473 // - attenuate ring tones volume by 6dB unless music is not playing and
8474 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008475 // - if music is playing, always limit the volume to current music volume,
8476 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008477 if (!Intersection(deviceTypes,
8478 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8479 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008480 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8481 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008482 ((volumeSource == alarmVolumeSrc ||
8483 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008484 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8485 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8486 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008487 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8488 curves.canBeMuted()) {
8489
Eric Laurente552edb2014-03-10 17:42:56 -07008490 // when the phone is ringing we must consider that music could have been paused just before
8491 // by the music application and behave as if music was active if the last music track was
8492 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008493 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8494 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008495 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008496 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008497 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8498 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008499 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008500 float musicVolDb = computeVolume(musicCurves,
8501 musicVolumeSrc,
8502 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008503 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008504 adjustAttenuation,
8505 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008506 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8507 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8508 if (volumeDb > minVolDb) {
8509 volumeDb = minVolDb;
8510 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008511 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008512 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8513 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008514 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8515 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8516 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8517 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008518 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008519 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008520 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8521 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008522 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8523 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008524 }
8525 }
jiabin9a3361e2019-10-01 09:38:30 -07008526 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008527 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008528 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008529 }
8530 }
8531
François Gaffie43c73442018-11-08 08:21:55 +01008532 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008533}
8534
Eric Laurent3839bc02018-07-10 18:33:34 -07008535int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008536 VolumeSource fromVolumeSource,
8537 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008538{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008539 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008540 return srcIndex;
8541 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008542 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8543 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008544 float minSrc = (float)srcCurves.getVolumeIndexMin();
8545 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8546 float minDst = (float)dstCurves.getVolumeIndexMin();
8547 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008548
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008549 // preserve mute request or correct range
8550 if (srcIndex < minSrc) {
8551 if (srcIndex == 0) {
8552 return 0;
8553 }
8554 srcIndex = minSrc;
8555 } else if (srcIndex > maxSrc) {
8556 srcIndex = maxSrc;
8557 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008558 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8559}
8560
François Gaffieaaac0fd2018-11-22 17:56:39 +01008561status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8562 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008563 int index,
8564 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008565 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008566 int delayMs,
8567 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008568{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008569 // APM is single threaded, and single instance.
8570 static std::set<IVolumeCurves*> invalidCurvesReported;
8571
François Gaffieaaac0fd2018-11-22 17:56:39 +01008572 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008573 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008574 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8575 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008576 return NO_ERROR;
8577 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008578
Eric Laurentae6e88c2024-01-10 14:42:57 +01008579 bool isVoiceVolSrc;
8580 bool isBtScoVolSrc;
8581 if (!isVolumeConsistentForCalls(
8582 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008583 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008584 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008585 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008586 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008587
jiabin9a3361e2019-10-01 09:38:30 -07008588 if (deviceTypes.empty()) {
8589 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008590 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008591 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008592 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008593 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008594
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008595 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008596 if (!invalidCurvesReported.count(&curves)) {
8597 invalidCurvesReported.insert(&curves);
8598 String8 dump;
8599 curves.dump(&dump);
8600 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8601 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008602 return BAD_VALUE;
8603 }
8604
jiabin9a3361e2019-10-01 09:38:30 -07008605 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008606 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008607 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008608 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008609 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8610 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008611 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8612 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008613 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008614 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008615
8616 bool muted;
8617 if (!com_android_media_audio_ring_my_car()) {
8618 muted = (index == 0) && (volumeDb != 0.0f);
8619 } else {
8620 muted = curves.isMuted();
8621 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008622 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8623 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008624
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008625 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08008626 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08008627 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8628 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008629 }
Eric Laurente552edb2014-03-10 17:42:56 -07008630 return NO_ERROR;
8631}
8632
Eric Laurentae6e88c2024-01-10 14:42:57 +01008633void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008634 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008635 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008636
8637 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8638 index = 0;
8639 }
8640
chenxin2095559032024-06-15 13:59:29 +08008641 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008642 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008643 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008644 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8645 } else {
8646 voiceVolume = index == 0 ? 0.0 : 1.0;
8647 }
8648 if (voiceVolume != mLastVoiceVolume) {
8649 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8650 mLastVoiceVolume = voiceVolume;
8651 }
8652}
8653
8654bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8655 const DeviceTypeSet& deviceTypes,
8656 bool& isVoiceVolSrc,
8657 bool& isBtScoVolSrc,
8658 const char* caller) {
8659 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008660 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8661
Eric Laurentae6e88c2024-01-10 14:42:57 +01008662 const bool isScoRequested = isScoRequestedForComm();
8663 const bool isHAUsed = isHearingAidUsedForComm();
8664
Vlad Popa695b76b2024-06-14 16:49:25 -07008665 if (com_android_media_audio_replace_stream_bt_sco()) {
Vlad Popa695b76b2024-06-14 16:49:25 -07008666 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8667 (isScoRequested || isHAUsed);
8668 return true;
8669 }
8670
8671 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008672 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8673
8674 if ((callVolSrc != btScoVolSrc) &&
8675 ((isVoiceVolSrc && isScoRequested) ||
8676 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8677 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8678 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8679 volumeSource, isScoRequested ? " " : " not ");
8680 return false;
8681 }
8682 return true;
8683}
8684
Eric Laurentc75307b2015-03-17 15:29:32 -07008685void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008686 const DeviceTypeSet& deviceTypes,
8687 int delayMs,
8688 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008689{
jiabincd510522020-01-22 09:40:55 -08008690 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008691 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8692 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008693 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008694 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008695 }
8696}
8697
François Gaffiec005e562018-11-06 15:04:49 +01008698void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8699 bool on,
8700 const sp<AudioOutputDescriptor>& outputDesc,
8701 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008702 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008703{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008704 std::vector<VolumeSource> sourcesToMute;
8705 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8706 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8707 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008708 VolumeSource source = toVolumeSource(attributes, false);
8709 if ((source != VOLUME_SOURCE_NONE) &&
8710 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8711 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008712 sourcesToMute.push_back(source);
8713 }
Eric Laurente552edb2014-03-10 17:42:56 -07008714 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008715 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008716 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008717 }
8718
Eric Laurente552edb2014-03-10 17:42:56 -07008719}
8720
Vlad Popa1e865e62024-08-15 19:11:42 -07008721void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8722 bool on,
8723 const sp<AudioOutputDescriptor>& outputDesc,
8724 int delayMs,
8725 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008726{
jiabin9a3361e2019-10-01 09:38:30 -07008727 if (deviceTypes.empty()) {
8728 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008729 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008730 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008731 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008732 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008733 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008734 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008735 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8736 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008737 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008738 }
8739 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008740 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8741 // ignored
8742 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008743 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008744 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008745 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008746 return;
8747 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008748 if (outputDesc->decMuteCount(volumeSource) == 0) {
8749 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008750 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008751 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008752 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008753 delayMs);
8754 }
8755 }
8756}
8757
François Gaffie53615e22015-03-19 09:24:12 +01008758bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8759{
Vlad Popa7f1823b2024-11-05 15:37:52 -08008760 if ((paa->flags & AUDIO_FLAG_SCO) != 0) {
8761 ALOGW("%s: deprecated use of AUDIO_FLAG_SCO in attributes flags %d", __func__, paa->flags);
8762 }
8763
François Gaffiec005e562018-11-06 15:04:49 +01008764 // has flags that map to a stream type?
Vlad Popa7f1823b2024-11-05 15:37:52 -08008765 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_BEACON)) != 0) {
Eric Laurente83b55d2014-11-14 10:06:21 -08008766 return true;
8767 }
8768
8769 // has known usage?
8770 switch (paa->usage) {
8771 case AUDIO_USAGE_UNKNOWN:
8772 case AUDIO_USAGE_MEDIA:
8773 case AUDIO_USAGE_VOICE_COMMUNICATION:
8774 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8775 case AUDIO_USAGE_ALARM:
8776 case AUDIO_USAGE_NOTIFICATION:
8777 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8778 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8779 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8780 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8781 case AUDIO_USAGE_NOTIFICATION_EVENT:
8782 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8783 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8784 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8785 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008786 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008787 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008788 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008789 case AUDIO_USAGE_EMERGENCY:
8790 case AUDIO_USAGE_SAFETY:
8791 case AUDIO_USAGE_VEHICLE_STATUS:
8792 case AUDIO_USAGE_ANNOUNCEMENT:
Jean-Michel Trivid9add572024-11-05 14:48:40 -08008793 case AUDIO_USAGE_SPEAKER_CLEANUP:
Eric Laurente83b55d2014-11-14 10:06:21 -08008794 break;
8795 default:
8796 return false;
8797 }
8798 return true;
8799}
8800
François Gaffie2110e042015-03-24 08:41:51 +01008801audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8802{
8803 return mEngine->getForceUse(usage);
8804}
8805
Eric Laurent96d1dda2022-03-14 17:14:19 +01008806bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008807 return isStateInCall(mEngine->getPhoneState());
8808}
8809
Eric Laurent96d1dda2022-03-14 17:14:19 +01008810bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008811 return is_state_in_call(state);
8812}
8813
Eric Laurentf9cccec2022-11-16 19:12:00 +01008814bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008815 audio_mode_t mode = mEngine->getPhoneState();
8816 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008817 || (mode == AUDIO_MODE_CALL_SCREEN)
8818 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008819}
8820
Eric Laurentf9cccec2022-11-16 19:12:00 +01008821bool AudioPolicyManager::isInCallOrScreening() const {
8822 audio_mode_t mode = mEngine->getPhoneState();
8823 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8824}
8825
Eric Laurentd60560a2015-04-10 11:31:20 -07008826void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8827{
8828 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008829 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008830 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008831 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008832 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008833 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008834 }
8835 }
8836
8837 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8838 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8839 bool release = false;
8840 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8841 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8842 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8843 source->ext.device.type == deviceDesc->type()) {
8844 release = true;
8845 }
8846 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008847 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008848 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8849 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8850 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008851 sink->ext.device.type == deviceDesc->type() &&
8852 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8853 || strncmp(sink->ext.device.address, address,
8854 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008855 release = true;
8856 }
8857 }
8858 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008859 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8860 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008861 }
8862 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008863
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008864 mInputs.clearSessionRoutesForDevice(deviceDesc);
8865
Francois Gaffie716e1432019-01-14 16:58:59 +01008866 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008867}
8868
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008869void AudioPolicyManager::modifySurroundFormats(
8870 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008871 std::unordered_set<audio_format_t> enforcedSurround(
8872 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008873 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008874 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008875 allSurround.insert(pair.first);
8876 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8877 }
Phil Burk09bc4612016-02-24 15:58:15 -08008878
8879 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8880 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008881 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008882 // This is the resulting set of formats depending on the surround mode:
8883 // 'all surround' = allSurround
8884 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8885 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8886 // 'manual surround' = mManualSurroundFormats
8887 // AUTO: formats v 'enforced surround'
8888 // ALWAYS: formats v 'all surround' v 'enforced surround'
8889 // NEVER: formats ^ 'non-surround'
8890 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008891
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008892 std::unordered_set<audio_format_t> formatSet;
8893 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8894 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008895 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008896 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008897 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008898 formatSet.insert(*formatIter);
8899 }
8900 }
8901 } else {
8902 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8903 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008904 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008905
jiabin81772902018-04-02 17:52:27 -07008906 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008907 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008908 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8909 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8910 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008911 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008912 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8913 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8914 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008915 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008916 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008917 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008918 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008919 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008920 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008921}
8922
jiabin06e4bab2019-07-29 10:13:34 -07008923void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8924 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008925 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8926 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8927
8928 // If NEVER, then remove support for channelMasks > stereo.
8929 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008930 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8931 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008932 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008933 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008934 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008935 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008936 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008937 }
8938 }
jiabin81772902018-04-02 17:52:27 -07008939 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8940 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8941 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008942 bool supports5dot1 = false;
8943 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008944 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008945 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8946 supports5dot1 = true;
8947 break;
8948 }
8949 }
8950 // If not then add 5.1 support.
8951 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008952 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008953 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008954 }
Phil Burk09bc4612016-02-24 15:58:15 -08008955 }
8956}
8957
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008958void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008959 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008960 const sp<IOProfile>& profile) {
8961 if (!profile->hasDynamicAudioProfile()) {
8962 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008963 }
François Gaffie112b0af2015-11-19 16:13:25 +01008964
jiabin12537fc2023-10-12 17:56:08 +00008965 audio_port_v7 devicePort;
8966 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008967
jiabin12537fc2023-10-12 17:56:08 +00008968 audio_port_v7 mixPort;
8969 profile->toAudioPort(&mixPort);
8970 mixPort.ext.mix.handle = ioHandle;
8971
8972 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8973 if (status != NO_ERROR) {
8974 ALOGE("%s failed to query the attributes of the mix port", __func__);
8975 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008976 }
jiabin12537fc2023-10-12 17:56:08 +00008977
8978 std::set<audio_format_t> supportedFormats;
8979 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8980 supportedFormats.insert(mixPort.audio_profiles[i].format);
8981 }
8982 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8983 mReportedFormatsMap[devDesc] = formats;
8984
8985 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008986 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8987 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008988 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8989 modifySurroundFormats(devDesc, &formats);
8990 size_t modifiedNumProfiles = 0;
8991 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8992 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8993 formats.end()) {
8994 // Skip the format that is not present after modifying surround formats.
8995 continue;
8996 }
8997 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8998 sizeof(struct audio_profile));
8999 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
9000 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
9001 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
9002 modifySurroundChannelMasks(&channels);
9003 std::copy(channels.begin(), channels.end(),
9004 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
9005 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
9006 }
9007 mixPort.num_audio_profiles = modifiedNumProfiles;
9008 }
9009 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01009010}
Eric Laurentd60560a2015-04-10 11:31:20 -07009011
Mikhail Naganovdc769682018-05-04 15:34:08 -07009012status_t AudioPolicyManager::installPatch(const char *caller,
9013 audio_patch_handle_t *patchHandle,
9014 AudioIODescriptorInterface *ioDescriptor,
9015 const struct audio_patch *patch,
9016 int delayMs)
9017{
9018 ssize_t index = mAudioPatches.indexOfKey(
9019 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
9020 *patchHandle : ioDescriptor->getPatchHandle());
9021 sp<AudioPatch> patchDesc;
9022 status_t status = installPatch(
9023 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
9024 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009025 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07009026 }
9027 return status;
9028}
9029
9030status_t AudioPolicyManager::installPatch(const char *caller,
9031 ssize_t index,
9032 audio_patch_handle_t *patchHandle,
9033 const struct audio_patch *patch,
9034 int delayMs,
9035 uid_t uid,
9036 sp<AudioPatch> *patchDescPtr)
9037{
9038 sp<AudioPatch> patchDesc;
9039 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9040 if (index >= 0) {
9041 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01009042 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009043 }
9044
9045 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9046 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9047 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9048 if (status == NO_ERROR) {
9049 if (index < 0) {
9050 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009051 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009052 } else {
9053 patchDesc->mPatch = *patch;
9054 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009055 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009056 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009057 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009058 }
9059 nextAudioPortGeneration();
9060 mpClientInterface->onAudioPatchListUpdate();
9061 }
9062 if (patchDescPtr) *patchDescPtr = patchDesc;
9063 return status;
9064}
9065
jiabinbce0c1d2020-10-05 11:20:18 -07009066bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9067{
9068 const TrackClientVector activeClients = output->getActiveClients();
9069 if (activeClients.empty()) {
9070 return true;
9071 }
9072 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9073 if (index < 0) {
9074 ALOGE("%s, no audio patch found while there are active clients on output %d",
9075 __func__, output->getId());
9076 return false;
9077 }
9078 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9079 DeviceVector routedDevices;
9080 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9081 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9082 patchDesc->mPatch.sinks[i].id);
9083 if (device == nullptr) {
9084 ALOGE("%s, no audio device found with id(%d)",
9085 __func__, patchDesc->mPatch.sinks[i].id);
9086 return false;
9087 }
9088 routedDevices.add(device);
9089 }
9090 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009091 if (client->isInvalid()) {
9092 // No need to take care about invalidated clients.
9093 continue;
9094 }
jiabinbce0c1d2020-10-05 11:20:18 -07009095 sp<DeviceDescriptor> preferredDevice =
9096 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9097 if (mEngine->getOutputDevicesForAttributes(
9098 client->attributes(), preferredDevice, false) == routedDevices) {
9099 return false;
9100 }
9101 }
9102 return true;
9103}
9104
9105sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009106 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009107 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9108 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009109{
9110 for (const auto& device : devices) {
9111 // TODO: This should be checking if the profile supports the device combo.
9112 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009113 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9114 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009115 return nullptr;
9116 }
9117 }
9118 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9119 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009120 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009121 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009122 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009123 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009124 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009125 return nullptr;
9126 }
jiabin14b50cc2023-12-13 19:01:52 +00009127 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9128 auto portConfig = desc->getConfig();
9129 for (const auto& device : devices) {
9130 device->setPreferredConfig(&portConfig);
9131 }
9132 }
jiabinbce0c1d2020-10-05 11:20:18 -07009133
9134 // Here is where the out_set_parameters() for card & device gets called
9135 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9136 const audio_devices_t deviceType = device->type();
9137 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009138 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009139 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9140 mpClientInterface->setParameters(output, String8(param));
9141 free(param);
9142 }
jiabin12537fc2023-10-12 17:56:08 +00009143 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009144 if (!profile->hasValidAudioProfile()) {
9145 ALOGW("%s() missing param", __func__);
9146 desc->close();
9147 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009148 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9149 // Reopen the output with the best audio profile picked by APM when the profile supports
9150 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009151 desc->close();
9152 output = AUDIO_IO_HANDLE_NONE;
9153 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9154 profile->pickAudioProfile(
9155 config.sample_rate, config.channel_mask, config.format);
9156 config.offload_info.sample_rate = config.sample_rate;
9157 config.offload_info.channel_mask = config.channel_mask;
9158 config.offload_info.format = config.format;
9159
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009160 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009161 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009162 if (status != NO_ERROR) {
9163 return nullptr;
9164 }
9165 }
9166
9167 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009168 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9169 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9170 hwModule->getHalVersionMajor() >= 3) {
9171 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9172 }
baek.kim -61c20122022-07-27 10:05:32 +00009173 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9174 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9175
jiabinbce0c1d2020-10-05 11:20:18 -07009176 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9177 sp<AudioPolicyMix> policyMix;
9178 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9179 policyMix->setOutput(desc);
9180 desc->mPolicyMix = policyMix;
9181 } else {
9182 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009183 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009184 }
9185
baek.kim -61c20122022-07-27 10:05:32 +00009186 } else if (hasPrimaryOutput() && speaker != nullptr
9187 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009188 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9189 // no duplicated output for:
9190 // - direct outputs
9191 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009192 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009193 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9194
9195 //TODO: configure audio effect output stage here
9196
9197 // open a duplicating output thread for the new output and the primary output
9198 sp<SwAudioOutputDescriptor> dupOutputDesc =
9199 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9200 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9201 if (status == NO_ERROR) {
9202 // add duplicated output descriptor
9203 addOutput(duplicatedOutput, dupOutputDesc);
9204 } else {
9205 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9206 mPrimaryOutput->mIoHandle, output);
9207 desc->close();
9208 removeOutput(output);
9209 nextAudioPortGeneration();
9210 return nullptr;
9211 }
9212 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009213 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9214 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9215 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009216 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009217 }
jiabinbce0c1d2020-10-05 11:20:18 -07009218 return desc;
9219}
9220
jiabinf1c73972022-04-14 16:28:52 -07009221status_t AudioPolicyManager::getDevicesForAttributes(
9222 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009223 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9224 // over any usage or content type also present in attr.
9225 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9226 attr.source != AUDIO_SOURCE_INVALID) {
9227 return getInputDevicesForAttributes(attr, devices);
9228 }
9229
jiabinf1c73972022-04-14 16:28:52 -07009230 // Devices are determined in the following precedence:
9231 //
9232 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9233 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9234 //
9235 // If no such dynamic policy then
9236 // 2) Devices containing an active client using setPreferredDevice
9237 // with same strategy as the attributes.
9238 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9239 //
9240 // If no corresponding active client with setPreferredDevice then
9241 // 3) Devices associated with the strategy determined by the attributes
9242 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9243 //
9244 // See related getOutputForAttrInt().
9245
9246 // check dynamic policies but only for primary descriptors (secondary not used for audible
9247 // audio routing, only used for duplication for playback capture)
9248 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009249 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009250 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009251 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9252 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9253 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009254 if (status != OK) {
9255 return status;
9256 }
9257
9258 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9259 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9260 // as they are unaffected by device/stream volume
9261 // (per SwAudioOutputDescriptor::isFixedVolume()).
9262 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9263 ) {
9264 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9265 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9266 devices.add(deviceDesc);
9267 } else {
9268 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9269 // which selects setPreferredDevice if active. This means forVolume call
9270 // will take an active setPreferredDevice, if such exists.
9271
9272 devices = mEngine->getOutputDevicesForAttributes(
9273 attr, nullptr /* preferredDevice */, false /* fromCache */);
9274 }
9275
9276 if (forVolume) {
9277 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9278 // for single volume control in AudioService (such relationship should exist if
9279 // SPEAKER_SAFE is present).
9280 //
9281 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9282 DeviceVector speakerSafeDevices =
9283 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9284 if (!speakerSafeDevices.isEmpty()) {
9285 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9286 devices.remove(speakerSafeDevices);
9287 }
9288 }
9289
9290 return NO_ERROR;
9291}
9292
wenyu zhang8558a332024-09-09 15:12:48 +00009293status_t AudioPolicyManager::getInputDevicesForAttributes(
9294 const audio_attributes_t &attr, DeviceVector &devices) {
9295 devices = DeviceVector(
9296 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9297 AUDIO_SESSION_NONE,
9298 nullptr /* mix */));
9299 return NO_ERROR;
9300}
9301
jiabinf1c73972022-04-14 16:28:52 -07009302status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9303 AudioProfileVector& audioProfiles,
9304 uint32_t flags,
9305 bool isInput) {
9306 for (const auto& hwModule : mHwModules) {
9307 // the MSD module checks for different conditions
9308 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9309 continue;
9310 }
9311 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9312 : hwModule->getOutputProfiles();
9313 for (const auto& profile : ioProfiles) {
9314 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009315 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009316 continue;
9317 }
9318 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9319 }
9320 }
9321
9322 if (!isInput) {
9323 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9324 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9325 if (msdModule != nullptr) {
9326 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9327 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9328 for (const auto &profile: msdModule->getOutputProfiles()) {
9329 if (!profile->asAudioPort()->isDirectOutput()) {
9330 continue;
9331 }
9332 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9333 }
9334 } else {
9335 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9336 }
9337 }
9338 }
9339
9340 return NO_ERROR;
9341}
9342
jiabin3ff8d7d2022-12-13 06:27:44 +00009343sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9344 const audio_config_t *config,
9345 audio_output_flags_t flags,
9346 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009347 closeOutput(outputDesc->mIoHandle);
9348 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9349 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9350 if (preferredOutput == nullptr) {
9351 ALOGE("%s failed to reopen output device=%d, caller=%s",
9352 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009353 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009354 return preferredOutput;
9355}
9356
9357void AudioPolicyManager::reopenOutputsWithDevices(
9358 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9359 for (const auto& [output, devices] : outputsToReopen) {
9360 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9361 closeOutput(output);
9362 openOutputWithProfileAndDevice(desc->mProfile, devices);
9363 }
jiabina84c3d32022-12-02 18:59:55 +00009364}
9365
jiabinc44b3462022-12-08 12:52:31 -08009366PortHandleVector AudioPolicyManager::getClientsForStream(
9367 audio_stream_type_t streamType) const {
9368 PortHandleVector clients;
9369 for (size_t i = 0; i < mOutputs.size(); ++i) {
9370 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9371 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9372 }
9373 return clients;
9374}
9375
9376void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9377 PortHandleVector clients;
9378 for (auto stream : streams) {
9379 PortHandleVector clientsForStream = getClientsForStream(stream);
9380 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9381 }
9382 mpClientInterface->invalidateTracks(clients);
9383}
9384
jiabin220eea12024-05-17 17:55:20 +00009385void AudioPolicyManager::updateClientsInternalMute(
9386 const sp<android::SwAudioOutputDescriptor> &desc) {
9387 if (!desc->isBitPerfect() ||
9388 !com::android::media::audioserver::
9389 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9390 // This is only used for bit perfect output now.
9391 return;
9392 }
9393 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9394 bool bitPerfectClientInternalMute = false;
9395 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9396 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9397 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9398 bitPerfectClient = client;
9399 continue;
9400 }
9401 bool muted = false;
9402 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9403 // System sound is muted.
9404 muted = true;
9405 } else {
9406 bitPerfectClientInternalMute = true;
9407 }
9408 if (client->setInternalMute(muted)) {
9409 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9410 if (!result.ok()) {
9411 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9412 continue;
9413 }
9414 media::TrackInternalMuteInfo info;
9415 info.portId = result.value();
9416 info.muted = client->getInternalMute();
9417 clientsInternalMute.push_back(std::move(info));
9418 }
9419 }
9420 if (bitPerfectClient != nullptr &&
9421 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9422 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9423 if (result.ok()) {
9424 media::TrackInternalMuteInfo info;
9425 info.portId = result.value();
9426 info.muted = bitPerfectClient->getInternalMute();
9427 clientsInternalMute.push_back(std::move(info));
9428 } else {
9429 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9430 __func__, bitPerfectClient->portId());
9431 }
9432 }
9433 if (!clientsInternalMute.empty()) {
9434 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9435 status != NO_ERROR) {
9436 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9437 }
9438 }
9439}
9440
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009441status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9442 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9443 if (policyType != AudioMMapPolicyType::DEFAULT &&
9444 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9445 return BAD_VALUE;
9446 }
9447 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9448 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9449 return status;
9450 }
9451 }
9452 *policyInfos = mMmapPolicyInfos[policyType];
9453 return NO_ERROR;
9454}
9455
9456status_t AudioPolicyManager::getMmapPolicyForDevice(
9457 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9458 if (policyType != AudioMMapPolicyType::DEFAULT &&
9459 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9460 return BAD_VALUE;
9461 }
9462 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9463 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9464 return status;
9465 }
9466 }
9467 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9468 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9469 ? AudioMMapPolicy::NEVER : it->second;
9470 return NO_ERROR;
9471}
9472
9473status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9474 std::vector<AudioMMapPolicyInfo> policyInfos;
9475 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9476 status != NO_ERROR) {
9477 ALOGE("%s, failed, error = %d", __func__, status);
9478 return status;
9479 }
9480 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9481 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9482 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9483 // it indicates the mmap policy is reported via system property. In that case, use the
9484 // routing information to fill details for how mmap is supported for a particular device.
9485 for (const auto &hwModule: mHwModules) {
9486 for (const auto &profile: hwModule->getInputProfiles()) {
9487 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9488 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9489 continue;
9490 }
9491 for (const auto &device: profile->getSupportedDevices()) {
9492 auto deviceDesc =
9493 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9494 if (deviceDesc.ok()) {
9495 mmapPolicyByDeviceType.emplace(
9496 deviceDesc.value(), policyInfos[0].mmapPolicy);
9497 }
9498 }
9499 }
9500 for (const auto &profile: hwModule->getOutputProfiles()) {
9501 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9502 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9503 continue;
9504 }
9505 for (const auto &device: profile->getSupportedDevices()) {
9506 auto deviceDesc =
9507 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9508 if (deviceDesc.ok()) {
9509 mmapPolicyByDeviceType.emplace(
9510 deviceDesc.value(), policyInfos[0].mmapPolicy);
9511 }
9512 }
9513 }
9514 }
9515 } else {
9516 for (const auto &info: policyInfos) {
9517 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9518 }
9519 }
9520 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9521 mMmapPolicyInfos.emplace(policyType, policyInfos);
9522 return NO_ERROR;
9523}
9524
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009525} // namespace android