blob: bff0a377744d669c4931f4384fd6fe6156ed28ee [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070050#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070052#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070053#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070054#include <utils/Log.h>
55
Eric Laurentd4692962014-05-05 18:13:44 -070056#include "AudioPolicyManager.h"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000057#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000069using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000070using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070071
Eric Laurentdc462862016-07-19 12:29:53 -070072//FIXME: workaround for truncated touch sounds
73// to be removed when the problem is handled by system UI
74#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070075
76// Largest difference in dB on earpiece in call between the voice volume and another
77// media / notification / system volume.
78constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
79
jiabin06e4bab2019-07-29 10:13:34 -070080template <typename T>
81bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
82{
83 if (left.size() != right.size()) {
84 return false;
85 }
86 for (size_t index = 0; index < right.size(); index++) {
87 if (left[index] != right[index]) {
88 return false;
89 }
90 }
91 return true;
92}
93
94template <typename T>
95bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
96{
97 return !(left == right);
98}
99
Eric Laurente552edb2014-03-10 17:42:56 -0700100// ----------------------------------------------------------------------------
101// AudioPolicyInterface implementation
102// ----------------------------------------------------------------------------
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
105 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
106 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800107 nextAudioPortGeneration();
108 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109}
110
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100111status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
112 audio_policy_dev_state_t state,
113 const char* device_address,
114 const char* device_name,
115 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800116 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100117 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
118 status == OK) {
119 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
120 } else {
121 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
122 return status;
123 }
124}
125
Ping Tsai2a5a5242024-08-16 13:39:10 +0800126status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000127 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200128{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 audio_port_v7 devicePort;
130 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800131 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
132 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
133 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
134
135 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800216 if (broadcastDeviceConnectionState(
217 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
218 mAvailableOutputDevices.remove(device);
219 mHwModules.cleanUpForDevice(device);
220 ALOGE("%s() device %s format %x connection failed", __func__,
221 device->toString().c_str(), device->getEncodedFormat());
222 return INVALID_OPERATION;
223 }
François Gaffie44481e72016-04-20 07:49:57 +0200224
François Gaffie11d30102018-11-02 16:09:09 +0100225 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
226 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200227
jiabinc0048632023-04-27 22:04:31 +0000228 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700229
230 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700231 return INVALID_OPERATION;
232 }
François Gaffie2110e042015-03-24 08:41:51 +0100233
jiabin1c4794b2020-05-05 10:08:05 -0700234 // Populate encapsulation information when a output device is connected.
235 device->setEncapsulationInfoFromHal(mpClientInterface);
236
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700237 // outputs should never be empty here
238 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
239 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100240 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800241
Eric Laurent3ae5f312015-02-03 17:12:08 -0800242 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700244 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100246 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700247 return INVALID_OPERATION;
248 }
249
François Gaffie11d30102018-11-02 16:09:09 +0100250 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700251
jiabinc0048632023-04-27 22:04:31 +0000252 // Notify the HAL to prepare to disconnect device
253 broadcastDeviceConnectionState(
254 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100257 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700258
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100259 mOutputs.clearSessionRoutesForDevice(device);
260
François Gaffie11d30102018-11-02 16:09:09 +0100261 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100262
jiabinc0048632023-04-27 22:04:31 +0000263 // Send Disconnect to HALs
264 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
265
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800266 // Reset active device codec
267 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
268
Kriti Dangef6be8f2020-11-05 11:58:19 +0100269 // remove device from mReportedFormatsMap cache
270 mReportedFormatsMap.erase(device);
271
jiabina84c3d32022-12-02 18:59:55 +0000272 // remove preferred mixer configurations
273 mPreferredMixerAttrInfos.erase(device->getId());
274
Eric Laurente552edb2014-03-10 17:42:56 -0700275 } break;
276
277 default:
François Gaffie11d30102018-11-02 16:09:09 +0100278 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700279 return BAD_VALUE;
280 }
281
Eric Laurent736a1022019-03-27 18:28:46 -0700282 // Propagate device availability to Engine
283 setEngineDeviceConnectionState(device, state);
284
Eric Laurentae970022019-01-29 14:25:04 -0800285 // No need to evaluate playback routing when connecting a remote submix
286 // output device used by a dynamic policy of type recorder as no
287 // playback use case is affected.
288 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700289 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800290 for (audio_io_handle_t output : outputs) {
291 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800292 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
293 if (policyMix != nullptr
294 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000295 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800296 doCheckForDeviceAndOutputChanges = false;
297 break;
298 }
299 }
300 }
301
302 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 // outputs must be closed after checkOutputForAllStrategies() is executed
304 if (!outputs.isEmpty()) {
305 for (audio_io_handle_t output : outputs) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100307 // close unused outputs after device disconnection or direct outputs that have
308 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200309 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200310 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
311 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200312 (desc->mDirectOpenCount == 0))
313 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
314 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200315 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700316 closeOutput(output);
317 }
Eric Laurente552edb2014-03-10 17:42:56 -0700318 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700319 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
320 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700321 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700322 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800323 };
324
325 if (doCheckForDeviceAndOutputChanges) {
326 checkForDeviceAndOutputChanges(checkCloseOutputs);
327 } else {
328 checkCloseOutputs();
329 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100330 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100331 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700332 const DeviceVector activeMediaDevices =
333 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000334 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700335 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700336 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530337 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
338 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100339 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 // do not force device change on duplicated output because if device is 0, it will
341 // also force a device 0 for the two outputs it is duplicated to which may override
342 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100343 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100344 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700345 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700346 // always force when disconnecting (a non-duplicated device)
347 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000348 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000349 // If the device is using preferred mixer attributes, the output need to reopen
350 // with default configuration when the new selected devices are different from
351 // current routing devices
352 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
353 continue;
354 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530355 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700356 }
jiabinbce0c1d2020-10-05 11:20:18 -0700357 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000358 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700359 desc->supportsDevicesForPlayback(activeMediaDevices)) {
360 // Reopen the output to query the dynamic profiles when there is not active
361 // clients or all active clients will be rerouted. Otherwise, set the flag
362 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
363 // can be reopened to query dynamic profiles when all clients are inactive.
364 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000365 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700366 } else {
367 desc->mPendingReopenToQueryProfiles = true;
368 }
369 }
370 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
371 // Clear the flag that previously set for re-querying profiles.
372 desc->mPendingReopenToQueryProfiles = false;
373 }
374 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000375 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700376
Eric Laurentd60560a2015-04-10 11:31:20 -0700377 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100378 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700379 }
380
Eric Laurent96d1dda2022-03-14 17:14:19 +0100381 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
382
Eric Laurent72aa32f2014-05-30 18:51:48 -0700383 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530384 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700385 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700386 } // end if is output device
387
Eric Laurente552edb2014-03-10 17:42:56 -0700388 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700389 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700391 switch (state)
392 {
393 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700394 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700395 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100396 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700397 return INVALID_OPERATION;
398 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700399
Jaideep Sharma33173202024-06-18 17:46:45 +0530400 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
401
Eric Laurent0dd51852019-04-19 18:18:58 -0700402 if (mAvailableInputDevices.add(device) < 0) {
403 return NO_MEMORY;
404 }
405
François Gaffie44481e72016-04-20 07:49:57 +0200406 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
407 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800408 if (broadcastDeviceConnectionState(
409 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
410 mAvailableInputDevices.remove(device);
411 mHwModules.cleanUpForDevice(device);
412 ALOGE("%s() device %s format %x connection failed", __func__,
413 device->toString().c_str(), device->getEncodedFormat());
414 return INVALID_OPERATION;
415 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700416 // Propagate device availability to Engine
417 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200418
Eric Laurent0dd51852019-04-19 18:18:58 -0700419 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700420 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
421
Eric Laurent0dd51852019-04-19 18:18:58 -0700422 mAvailableInputDevices.remove(device);
423
jiabinc0048632023-04-27 22:04:31 +0000424 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100425
426 mHwModules.cleanUpForDevice(device);
427
Eric Laurentd4692962014-05-05 18:13:44 -0700428 return INVALID_OPERATION;
429 }
430
Eric Laurentd4692962014-05-05 18:13:44 -0700431 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700432
433 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700434 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100436 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700437 return INVALID_OPERATION;
438 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700439
François Gaffie11d30102018-11-02 16:09:09 +0100440 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700441
jiabinc0048632023-04-27 22:04:31 +0000442 // Notify the HAL to prepare to disconnect device
443 broadcastDeviceConnectionState(
444 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700445
François Gaffie11d30102018-11-02 16:09:09 +0100446 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700447
448 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100449
jiabinc0048632023-04-27 22:04:31 +0000450 // Set Disconnect to HALs
451 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
452
Kriti Dangef6be8f2020-11-05 11:58:19 +0100453 // remove device from mReportedFormatsMap cache
454 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700455
456 // Propagate device availability to Engine
457 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700458 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700459
460 default:
François Gaffie11d30102018-11-02 16:09:09 +0100461 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700462 return BAD_VALUE;
463 }
464
Eric Laurent0dd51852019-04-19 18:18:58 -0700465 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700466 // As the input device list can impact the output device selection, update
467 // getDeviceForStrategy() cache
468 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700469
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100470 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200471 // Reconnect Audio Source
472 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
473 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
474 checkAudioSourceForAttributes(attributes);
475 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700476 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100477 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700478 }
479
Eric Laurentb52c1522014-05-20 11:27:36 -0700480 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530481 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700482 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700483 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700484
François Gaffie11d30102018-11-02 16:09:09 +0100485 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700486 return BAD_VALUE;
487}
488
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100489status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
490 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800491 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700492 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
493 devDescr->setName(device_name);
494 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100495}
496
Eric Laurent736a1022019-03-27 18:28:46 -0700497void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
498 audio_policy_dev_state_t state) {
499
500 // the Engine does not have to know about remote submix devices used by dynamic audio policies
501 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
502 return;
503 }
504 mEngine->setDeviceConnectionState(device, state);
505}
506
507
Eric Laurente0720872014-03-11 09:30:41 -0700508audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100509 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700510{
Eric Laurent634b7142016-04-20 13:48:02 -0700511 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
513 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700514 (strlen(device_address) != 0)/*matchAddress*/);
515
516 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100517 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700518 device, device_address);
519 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
520 }
François Gaffie53615e22015-03-19 09:24:12 +0100521
Eric Laurent3a4311c2014-03-17 12:00:47 -0700522 DeviceVector *deviceVector;
523
Eric Laurente552edb2014-03-10 17:42:56 -0700524 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700525 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700526 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700527 deviceVector = &mAvailableInputDevices;
528 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100529 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700530 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700531 }
Eric Laurent634b7142016-04-20 13:48:02 -0700532
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 return (deviceVector->getDevice(
534 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700535 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800536}
537
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
539 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 const char *device_name,
541 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800543 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
544 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800545
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800546 // connect/disconnect only 1 device at a time
547 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
548
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800549 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700550 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800552 // Nothing to do: device is not connected
553 return NO_ERROR;
554 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800555 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800556
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700557 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 // configure codecs.
559 // Handle two specific cases by sending a set parameter to
560 // configure A2DP codecs. No need to toggle device state.
561 // Case 1: A2DP active device switches from primary to primary
562 // module
563 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100564 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700565 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
567 if (availablePrimaryOutputDevices().contains(devDesc) &&
568 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100569 bool isA2dp = audio_is_a2dp_out_device(device);
570 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
571 : String8(AudioParameter::keyReconfigLeSupported);
572 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100574 int isReconfigSupported;
575 repliedParameters.getInt(supportKey, isReconfigSupported);
576 if (isReconfigSupported) {
577 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
578 : String8(AudioParameter::keyReconfigLe);
579 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800580 param.add(key, String8("true"));
581 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
582 devDesc->setEncodedFormat(encodedFormat);
583 return NO_ERROR;
584 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700585 }
586 }
cnx421bd2dcc42020-07-11 14:58:44 +0800587 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000588 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800589 for (size_t i = 0; i < mOutputs.size(); i++) {
590 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000591 // mute media strategies to avoid sending the music tail into
592 // the earpiece or headset.
593 if (desc->isStrategyActive(musicStrategy)) {
594 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
595 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
596 tempRecommendedMuteDuration : desc->latency() * 4;
597 if (muteWaitMs < tempMuteDurationMs) {
598 muteWaitMs = tempMuteDurationMs;
599 }
600 }
cnx421bd2dcc42020-07-11 14:58:44 +0800601 setStrategyMute(musicStrategy, true, desc);
602 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
603 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
604 nullptr, true /*fromCache*/).types());
605 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000606 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
607 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
608 // happens after the actual device switch.
609 if (muteWaitMs > 0) {
610 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
611 usleep(muteWaitMs * 1000);
612 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800613 // Toggle the device state: UNAVAILABLE -> AVAILABLE
614 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100615 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800616 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800617 device_address, device_name,
618 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800619 if (status != NO_ERROR) {
620 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
621 status);
622 return status;
623 }
624
625 status = setDeviceConnectionState(device,
626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800627 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800628 if (status != NO_ERROR) {
629 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
630 status);
631 return status;
632 }
633
634 return NO_ERROR;
635}
636
Pattydd807582021-11-04 21:01:03 +0800637status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
638 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800639{
Pattydd807582021-11-04 21:01:03 +0800640 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800641 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800642 std::unordered_set<audio_format_t> formatSet;
643 sp<HwModule> primaryModule =
644 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700645 if (primaryModule == nullptr) {
646 ALOGE("%s() unable to get primary module", __func__);
647 return NO_INIT;
648 }
Pattydd807582021-11-04 21:01:03 +0800649
650 DeviceTypeSet audioDeviceSet;
651
652 switch(device) {
653 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
654 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
655 break;
656 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800657 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
658 break;
659 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
660 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800661 break;
662 default:
663 ALOGE("%s() device type 0x%08x not supported", __func__, device);
664 return BAD_VALUE;
665 }
666
jiabin9a3361e2019-10-01 09:38:30 -0700667 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800668 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800669 for (const auto& device : declaredDevices) {
670 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800671 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800672 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800673 return status;
674}
675
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
677{
678 DeviceVector rxSinkdevices{};
679 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
680 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
681 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
682 auto rxSinkDevice = rxSinkdevices.itemAt(0);
683 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
684 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
685 // retrieve Rx Source device descriptor
686 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
687 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
688
689 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
690 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
691 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
692 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
693 return DeviceVector(rxSinkDevice);
694 }
695 }
696 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
697 // the device returned is not necessarily reachable via this output
698 // (filter later by setOutputDevices())
699 return getNewOutputDevices(mPrimaryOutput, fromCache);
700}
701
702status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
703{
François Gaffiedb1755b2023-09-01 11:50:35 +0200704 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100705 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
706 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
707 }
708 return INVALID_OPERATION;
709}
710
711status_t AudioPolicyManager::updateCallRoutingInternal(
712 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700713{
714 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100715 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700716 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200717 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700718 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100719 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700720 }
François Gaffie11d30102018-11-02 16:09:09 +0100721
Francois Gaffie716e1432019-01-14 16:58:59 +0100722 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100723 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200724
Eric Laurentb2fb4102024-06-21 12:25:26 +0000725 if (!fix_call_audio_patch()) {
726 disconnectTelephonyAudioSource(mCallRxSourceClient);
727 disconnectTelephonyAudioSource(mCallTxSourceClient);
728 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200729
730 if (rxDevices.isEmpty()) {
731 ALOGW("%s() no selected output device", __func__);
732 return INVALID_OPERATION;
733 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000734 if (txSourceDevice == nullptr) {
735 ALOGE("%s() selected input device not available", __func__);
736 return INVALID_OPERATION;
737 }
François Gaffiec005e562018-11-06 15:04:49 +0100738
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100739 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100740 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
François Gaffie9eb18552018-11-05 10:33:26 +0100742 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700743 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100744 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700745 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100746 // retrieve Rx Source and Tx Sink device descriptors
747 sp<DeviceDescriptor> rxSourceDevice =
748 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
749 String8(),
750 AUDIO_FORMAT_DEFAULT);
751 sp<DeviceDescriptor> txSinkDevice =
752 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
753 String8(),
754 AUDIO_FORMAT_DEFAULT);
755
756 // RX and TX Telephony device are declared by Primary Audio HAL
757 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
758 (telephonyRxModule->getHalVersionMajor() >= 3)) {
759 if (rxSourceDevice == 0 || txSinkDevice == 0) {
760 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100761 ALOGE("%s() no telephony Tx and/or RX device", __func__);
762 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100763 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100764 // createAudioPatchInternal now supports both HW / SW bridging
765 createRxPatch = true;
766 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100767 } else {
768 // If the RX device is on the primary HW module, then use legacy routing method for
769 // voice calls via setOutputDevice() on primary output.
770 // Otherwise, create two audio patches for TX and RX path.
771 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
772 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700773 // If the TX device is also on the primary HW module, setOutputDevice() will take care
774 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100775 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
776 (txSinkDevice != 0);
777 }
778 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
779 // Otherwise, create two audio patches for TX and RX path.
780 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000781 if (fix_call_audio_patch()) {
782 disconnectTelephonyAudioSource(mCallRxSourceClient);
783 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200784 if (!hasPrimaryOutput()) {
785 ALOGW("%s() no primary output available", __func__);
786 return INVALID_OPERATION;
787 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530788 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700789 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000790 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800791 // If the TX device is on the primary HW module but RX device is
792 // on other HW module, SinkMetaData of telephony input should handle it
793 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700794 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700795 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100796 // terminate active capture if on the same HW module as the call TX source device
797 // FIXME: would be better to refine to only inputs whose profile connects to the
798 // call TX device but this information is not in the audio patch and logic here must be
799 // symmetric to the one in startInput()
800 for (const auto& activeDesc : mInputs.getActiveInputs()) {
801 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
802 closeActiveClients(activeDesc);
803 }
804 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000806 } else if (fix_call_audio_patch()) {
807 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800808 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100809 if (waitMs != nullptr) {
810 *waitMs = muteWaitMs;
811 }
812 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800813}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700814
Mikhail Naganov100f0122018-11-29 11:22:16 -0800815bool AudioPolicyManager::isDeviceOfModule(
816 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
817 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
818 if (module != 0) {
819 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
820 .indexOf(devDesc) != NAME_NOT_FOUND
821 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
822 .indexOf(devDesc) != NAME_NOT_FOUND;
823 }
824 return false;
825}
826
David Lif85c5e32024-07-01 13:14:10 +0000827void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200828{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000829 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
830
831 if (fix_call_audio_patch()) {
832 if (mCallRxSourceClient != nullptr) {
833 DeviceVector rxDevices =
834 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
835 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
836 "connectTelephonyRxAudioSource(): no device found for call RX source");
837 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
838 if (mCallRxSourceClient->isConnected()
839 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
840 return;
841 }
842 disconnectTelephonyAudioSource(mCallRxSourceClient);
843 }
844 } else {
845 disconnectTelephonyAudioSource(mCallRxSourceClient);
846 }
847
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200848 const struct audio_port_config source = {
849 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
850 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
851 };
Eric Laurent541a2002024-01-15 18:11:42 +0100852 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000853
Eric Laurentccbd7872024-06-20 12:34:15 +0000854 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000855 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100856 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
857 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000858 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
859 mCallRxSourceClient->srcDevice()->toString().c_str(),
860 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200861 ALOGE_IF(mCallRxSourceClient == nullptr,
862 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200863}
864
Francois Gaffie601801d2021-06-22 13:27:39 +0200865void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200866{
Francois Gaffie601801d2021-06-22 13:27:39 +0200867 if (clientDesc == nullptr) {
868 return;
869 }
870 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
871 "%s error stopping audio source", __func__);
872 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200873}
874
875void AudioPolicyManager::connectTelephonyTxAudioSource(
876 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
877 uint32_t delayMs)
878{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200879 if (srcDevice == nullptr || sinkDevice == nullptr) {
880 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
881 return;
882 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000883
884 if (fix_call_audio_patch()) {
885 if (mCallTxSourceClient != nullptr) {
886 if (mCallTxSourceClient->isConnected()
887 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
888 return;
889 }
890 disconnectTelephonyAudioSource(mCallTxSourceClient);
891 }
892 } else {
893 disconnectTelephonyAudioSource(mCallTxSourceClient);
894 }
895
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200896 PatchBuilder patchBuilder;
897 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000898
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200900 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
901
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200902 struct audio_port_config source = {};
903 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100904 mCallTxSourceClient = new SourceClientDescriptor(
905 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000906 mCommunnicationStrategy, toVolumeSource(aa), true,
907 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100908 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
909
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200910 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
911 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200912 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
913 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200914 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000915 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
916 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200917 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200918 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200919 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200920}
921
Eric Laurente0720872014-03-11 09:30:41 -0700922void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700923{
924 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100925 // store previous phone state for management of sonification strategy below
926 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100927 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100928
929 if (mEngine->setPhoneState(state) != NO_ERROR) {
930 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700931 return;
932 }
François Gaffie2110e042015-03-24 08:41:51 +0100933 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700934 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700935 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700936 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800937 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700938 }
939
François Gaffie2110e042015-03-24 08:41:51 +0100940 /**
941 * Switching to or from incall state or switching between telephony and VoIP lead to force
942 * routing command.
943 */
Eric Laurent74b71512019-11-06 17:21:57 -0800944 bool force = ((isStateInCall(oldState) != isStateInCall(state))
945 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700946
947 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700948 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700949
Eric Laurente552edb2014-03-10 17:42:56 -0700950 int delayMs = 0;
951 if (isStateInCall(state)) {
952 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100953 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
954 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700955 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700957 // mute media and sonification strategies and delay device switch by the largest
958 // latency of any output where either strategy is active.
959 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100960 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
961 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
962 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700963 (delayMs < (int)desc->latency()*2)) {
964 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700965 }
François Gaffiec005e562018-11-06 15:04:49 +0100966 setStrategyMute(musicStrategy, true, desc);
967 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
968 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
969 nullptr, true /*fromCache*/).types());
970 setStrategyMute(sonificationStrategy, true, desc);
971 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
972 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
973 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
975 }
976
François Gaffiedb1755b2023-09-01 11:50:35 +0200977 if (state == AUDIO_MODE_IN_CALL) {
978 (void)updateCallRouting(false /*fromCache*/, delayMs);
979 } else {
980 if (oldState == AUDIO_MODE_IN_CALL) {
981 disconnectTelephonyAudioSource(mCallRxSourceClient);
982 disconnectTelephonyAudioSource(mCallTxSourceClient);
983 }
984 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100985 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
986 // force routing command to audio hardware when ending call
987 // even if no device change is needed
988 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
989 rxDevices = mPrimaryOutput->devices();
990 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530991 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700992 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700993 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700994
jiabin3ff8d7d2022-12-13 06:27:44 +0000995 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700996 // reevaluate routing on all outputs in case tracks have been started during the call
997 for (size_t i = 0; i < mOutputs.size(); i++) {
998 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100999 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001000 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1001 && desc->mPreferredAttrInfo != nullptr) {
1002 // If the output is using preferred mixer attributes and the audio mode is not normal,
1003 // the output need to reopen with default configuration.
1004 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1005 continue;
1006 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001007 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1008 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301009 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001010 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001011 }
1012 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001013 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001014
Eric Laurent96d1dda2022-03-14 17:14:19 +01001015 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1016
Eric Laurente552edb2014-03-10 17:42:56 -07001017 if (isStateInCall(state)) {
1018 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001019 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001020 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001021 }
1022
1023 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001024 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1025 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001026}
1027
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001028audio_mode_t AudioPolicyManager::getPhoneState() {
1029 return mEngine->getPhoneState();
1030}
1031
Eric Laurente0720872014-03-11 09:30:41 -07001032void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001033 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001034{
François Gaffie2110e042015-03-24 08:41:51 +01001035 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001036 if (config == mEngine->getForceUse(usage)) {
1037 return;
1038 }
Eric Laurente552edb2014-03-10 17:42:56 -07001039
François Gaffie2110e042015-03-24 08:41:51 +01001040 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1041 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1042 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001043 }
François Gaffie2110e042015-03-24 08:41:51 +01001044 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1045 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1046 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001047
1048 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001049 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001050
Eric Laurent22fcda22019-05-17 16:28:47 -07001051 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1052 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001053 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001054 }
1055
Eric Laurentdc462862016-07-19 12:29:53 -07001056 //FIXME: workaround for truncated touch sounds
1057 // to be removed when the problem is handled by system UI
1058 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001059 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1060 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1061 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001062
1063 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001064 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001065}
1066
Eric Laurente0720872014-03-11 09:30:41 -07001067void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001068{
1069 ALOGV("setSystemProperty() property %s, value %s", property, value);
1070}
1071
Dorin Drimusecc9f422022-03-09 17:57:40 +01001072// Find an MSD output profile compatible with the parameters passed.
1073// When "directOnly" is set, restrict search to profiles for direct outputs.
1074sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1075 const DeviceVector& devices,
1076 uint32_t samplingRate,
1077 audio_format_t format,
1078 audio_channel_mask_t channelMask,
1079 audio_output_flags_t flags,
1080 bool directOnly)
1081{
1082 flags = getRelevantFlags(flags, directOnly);
1083
1084 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1085 if (msdModule != nullptr) {
1086 // for the msd module check if there are patches to the output devices
1087 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1088 HwModuleCollection modules;
1089 modules.add(msdModule);
1090 return searchCompatibleProfileHwModules(
1091 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1092 flags, directOnly);
1093 }
1094 }
1095 return nullptr;
1096}
1097
Michael Chana94fbb22018-04-24 14:31:19 +10001098// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1099// search to profiles for direct outputs.
1100sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001101 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001102 uint32_t samplingRate,
1103 audio_format_t format,
1104 audio_channel_mask_t channelMask,
1105 audio_output_flags_t flags,
1106 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001107{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 flags = getRelevantFlags(flags, directOnly);
1109
1110 return searchCompatibleProfileHwModules(
1111 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1112}
1113
1114audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1115 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001116 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001117 // only retain flags that will drive the direct output profile selection
1118 // if explicitly requested
1119 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001120 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001121 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1122 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001123 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001124 return flags;
1125}
Eric Laurent861a6282015-05-18 15:40:16 -07001126
Dorin Drimusecc9f422022-03-09 17:57:40 +01001127sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1128 const HwModuleCollection& hwModules,
1129 const DeviceVector& devices,
1130 uint32_t samplingRate,
1131 audio_format_t format,
1132 audio_channel_mask_t channelMask,
1133 audio_output_flags_t flags,
1134 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001135 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001136 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001137 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001138 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001139 samplingRate, NULL /*updatedSamplingRate*/,
1140 format, NULL /*updatedFormat*/,
1141 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001142 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001143 continue;
1144 }
1145 // reject profiles not corresponding to a device currently available
1146 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1147 continue;
1148 }
1149 // reject profiles if connected device does not support codec
1150 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1151 continue;
1152 }
1153 if (!directOnly) {
1154 return curProfile;
1155 }
1156
1157 // when searching for direct outputs, if several profiles are compatible, give priority
1158 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001159 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001160 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001161 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001162 }
1163 profile = curProfile;
1164 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1165 break;
1166 }
Eric Laurente552edb2014-03-10 17:42:56 -07001167 }
1168 }
Eric Laurent861a6282015-05-18 15:40:16 -07001169 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001170}
1171
Eric Laurentfa0f6742021-08-17 18:39:44 +02001172sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001173 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001174{
1175 for (const auto& hwModule : mHwModules) {
1176 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001177 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001178 continue;
1179 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001180 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001181 // reject profiles not corresponding to a device currently available
1182 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1183 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1184 continue;
1185 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001186 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1187 != devices.size()) {
1188 continue;
1189 }
1190 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001191 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1192 return curProfile;
1193 }
1194 }
1195 return nullptr;
1196}
1197
Eric Laurentf4e63452017-11-06 19:31:46 +00001198audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001199{
François Gaffiec005e562018-11-06 15:04:49 +01001200 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001201
1202 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1203 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1204 // format, flags, etc. This may result in some discrepancy for functions that utilize
1205 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1206 // and AudioSystem::getOutputSamplingRate().
1207
François Gaffie11d30102018-11-02 16:09:09 +01001208 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001209 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001210 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001211 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1212 }
1213 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001214
François Gaffie11d30102018-11-02 16:09:09 +01001215 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1216 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001217 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001218}
1219
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001220status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1221 const audio_attributes_t *srcAttr,
1222 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001223{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001224 if (srcAttr != NULL) {
1225 if (!isValidAttributes(srcAttr)) {
1226 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1227 __func__,
1228 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1229 srcAttr->tags);
1230 return BAD_VALUE;
1231 }
1232 *dstAttr = *srcAttr;
1233 } else {
1234 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1235 ALOGE("%s: invalid stream type", __func__);
1236 return BAD_VALUE;
1237 }
François Gaffiec005e562018-11-06 15:04:49 +01001238 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001239 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001240
1241 // Only honor audibility enforced when required. The client will be
1242 // forced to reconnect if the forced usage changes.
1243 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001244 dstAttr->flags = static_cast<audio_flags_mask_t>(
1245 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001246 }
1247
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001248 return NO_ERROR;
1249}
1250
Kevin Rocard153f92d2018-12-18 18:33:28 -08001251status_t AudioPolicyManager::getOutputForAttrInt(
1252 audio_attributes_t *resultAttr,
1253 audio_io_handle_t *output,
1254 audio_session_t session,
1255 const audio_attributes_t *attr,
1256 audio_stream_type_t *stream,
1257 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001258 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001259 audio_output_flags_t *flags,
1260 audio_port_handle_t *selectedDeviceId,
1261 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001262 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001263 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001264 bool *isSpatialized,
1265 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001266{
François Gaffiec005e562018-11-06 15:04:49 +01001267 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001268 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001269 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001270 const sp<DeviceDescriptor> requestedDevice =
1271 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1272
Eric Laurent8a1095a2019-11-08 14:44:16 -08001273 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001274 *isSpatialized = false;
1275
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001276 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1277 if (status != NO_ERROR) {
1278 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001279 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001280 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001281 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001282 }
François Gaffiec005e562018-11-06 15:04:49 +01001283 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001284
François Gaffiec005e562018-11-06 15:04:49 +01001285 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1286 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287
Oscar Azucena873d10f2023-01-12 18:34:42 -08001288 bool usePrimaryOutputFromPolicyMixes = false;
1289
Kevin Rocard153f92d2018-12-18 18:33:28 -08001290 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1291 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1292 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001293 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001294 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1295 .channel_mask = config->channel_mask,
1296 .format = config->format,
1297 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001298 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001299 mAvailableOutputDevices, requestedDevice, primaryMix,
1300 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001301 if (status != OK) {
1302 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001303 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001304
Kevin Rocard153f92d2018-12-18 18:33:28 -08001305 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001306 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001307 && (!audio_is_linear_pcm(config->format) ||
1308 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001309 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001310 return BAD_VALUE;
1311 }
1312 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001313 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001314 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1315 primaryMix->mDeviceAddress,
1316 AUDIO_FORMAT_DEFAULT);
1317 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001318 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001319 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1320 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001321 // if a direct output can be opened to deliver the track's multi-channel content to the
1322 // output rather than being downmixed by the primary output, then use this direct
1323 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1324 // mix.
1325 bool tryDirectForChannelMask = policyDesc != nullptr
1326 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1327 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001328 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001329 audio_io_handle_t newOutput;
1330 status = openDirectOutput(
1331 *stream, session, config,
1332 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001333 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001334 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001335 policyDesc = mOutputs.valueFor(newOutput);
1336 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001337 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001338 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001339 policyDesc = nullptr;
1340 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001341 }
1342 if (policyDesc != nullptr) {
1343 policyDesc->mPolicyMix = primaryMix;
1344 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001345 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1346 : AUDIO_PORT_HANDLE_NONE;
1347 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1348 // Remove direct flag as it is not on a direct output.
1349 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1350 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001351
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001352 ALOGV("getOutputForAttr() returns output %d", *output);
1353 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1354 *outputType = API_OUT_MIX_PLAYBACK;
1355 } else {
1356 *outputType = API_OUTPUT_LEGACY;
1357 }
1358 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001359 } else {
1360 if (policyMixDevice != nullptr) {
1361 ALOGE("%s, try to use primary mix but no output found", __func__);
1362 return INVALID_OPERATION;
1363 }
1364 // Fallback to default engine selection as the selected primary mix device is not
1365 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001366 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001367 }
François Gaffiec005e562018-11-06 15:04:49 +01001368 // Virtual sources must always be dynamicaly or explicitly routed
1369 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1370 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1371 return BAD_VALUE;
1372 }
1373 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1374 // in order to let the choice of the order to future vendor engine
1375 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001376
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001377 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001378 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001379 }
1380
Nadav Barb2f18162018-07-18 13:01:53 +03001381 // Set incall music only if device was explicitly set, and fallback to the device which is
1382 // chosen by the engine if not.
1383 // FIXME: provide a more generic approach which is not device specific and move this back
1384 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001385 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001386 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001387 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001388 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001389 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001390 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001391 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001392 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001393 }
1394 }
1395
François Gaffiec005e562018-11-06 15:04:49 +01001396 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1397 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1398 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001399
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001400 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001401 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001402 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001403 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001404 ALOGV("%s() Using MSD devices %s instead of devices %s",
1405 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001406 } else {
1407 *output = AUDIO_IO_HANDLE_NONE;
1408 }
1409 }
1410 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001411 sp<PreferredMixerAttributesInfo> info = nullptr;
1412 if (outputDevices.size() == 1) {
1413 info = getPreferredMixerAttributesInfo(
1414 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001415 mEngine->getProductStrategyForAttributes(*resultAttr),
1416 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001417 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1418 // and it is currently active.
1419 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001420 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001421 info = nullptr;
1422 }
jiabin8a096672024-09-18 18:20:24 +00001423
1424 if (info != nullptr && info->isBitPerfect() &&
1425 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1426 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1427 // Reject direct request if a preferred mixer config in use is bit-perfect.
1428 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1429 __func__);
1430 return BAD_VALUE;
1431 }
1432
jiabin220eea12024-05-17 17:55:20 +00001433 if (com::android::media::audioserver::
1434 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1435 if (info != nullptr && info->getUid() == uid &&
1436 info->configMatches(*config) &&
1437 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1438 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1439 [this, &outputDevices](audio_usage_t usage) {
1440 return mOutputs.isUsageActiveOnDevice(
1441 usage, outputDevices[0]); }))) {
1442 // Bit-perfect request is not allowed when the phone mode is not normal or
1443 // there is any higher priority user case active.
1444 return INVALID_OPERATION;
1445 }
1446 }
jiabina84c3d32022-12-02 18:59:55 +00001447 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001448 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001449 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001450 // The client will be active if the client is currently preferred mixer owner and the
1451 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001452 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001453 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001454 && info->getUid() == uid
1455 && *output != AUDIO_IO_HANDLE_NONE
1456 // When bit-perfect output is selected for the preferred mixer attributes owner,
1457 // only need to consider the config matches.
1458 && mOutputs.valueFor(*output)->isConfigurationMatched(
1459 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001460
1461 if (*isBitPerfect) {
1462 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1463 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001465 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001466 AudioProfileVector profiles;
1467 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1468 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001469 const auto channels = profiles[0]->getChannels();
1470 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1471 config->channel_mask = *channels.begin();
1472 }
1473 const auto sampleRates = profiles[0]->getSampleRates();
1474 if (!sampleRates.empty() &&
1475 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1476 config->sample_rate = *sampleRates.begin();
1477 }
jiabinf1c73972022-04-14 16:28:52 -07001478 config->format = profiles[0]->getFormat();
1479 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001480 return INVALID_OPERATION;
1481 }
Paul McLeanaa981192015-03-21 09:55:15 -07001482
François Gaffiec005e562018-11-06 15:04:49 +01001483 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001484 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001485 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001486 *selectedDeviceId = outputDevice->getId();
1487 break;
1488 }
1489 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001490
Eric Laurent8a1095a2019-11-08 14:44:16 -08001491 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1492 *outputType = API_OUTPUT_TELEPHONY_TX;
1493 } else {
1494 *outputType = API_OUTPUT_LEGACY;
1495 }
1496
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001497 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1498
1499 return NO_ERROR;
1500}
1501
1502status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1503 audio_io_handle_t *output,
1504 audio_session_t session,
1505 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001506 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001507 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001508 audio_output_flags_t *flags,
1509 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001510 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001511 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001512 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001513 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001514 bool *isBitPerfect,
1515 float *volume)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001516{
1517 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1518 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1519 return INVALID_OPERATION;
1520 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001521 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001522 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001523 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001524 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001525 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001526 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001527 const sp<DeviceDescriptor> requestedDevice =
1528 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1529
1530 // Prevent from storing invalid requested device id in clients
1531 const audio_port_handle_t sanitizedRequestedPortId =
1532 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1533 *selectedDeviceId = sanitizedRequestedPortId;
1534
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001535 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001536 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001537 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1538 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001539 if (status != NO_ERROR) {
1540 return status;
1541 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001542 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001543 if (secondaryOutputs != nullptr) {
1544 for (auto &secondaryMix : secondaryMixes) {
1545 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1546 if (outputDesc != nullptr &&
1547 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1548 secondaryOutputs->push_back(outputDesc->mIoHandle);
1549 weakSecondaryOutputDescs.push_back(outputDesc);
1550 }
1551 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001552 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001553
Eric Laurent8fc147b2018-07-22 19:13:55 -07001554 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001555 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001556 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001557 };
jiabin4ef93452019-09-10 14:29:54 -07001558 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001559
Eric Laurentc209fe42020-06-05 18:11:23 -07001560 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001561 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001562 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001563 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001564 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001565 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001566 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001567 std::move(weakSecondaryOutputDescs),
1568 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001569 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001570
Andy Hung6b137d12024-08-27 22:35:17 +00001571 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
1572
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001573 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1574 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001575
Eric Laurente83b55d2014-11-14 10:06:21 -08001576 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001577}
1578
Eric Laurentc529cf62020-04-17 18:19:10 -07001579status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1580 audio_session_t session,
1581 const audio_config_t *config,
1582 audio_output_flags_t flags,
1583 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001584 audio_io_handle_t *output,
1585 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001586
1587 *output = AUDIO_IO_HANDLE_NONE;
1588
1589 // skip direct output selection if the request can obviously be attached to a mixed output
1590 // and not explicitly requested
1591 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1592 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1593 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1594 return NAME_NOT_FOUND;
1595 }
1596
Mikhail Naganov806170e2024-09-05 17:26:50 -07001597 // Reject flag combinations that do not make sense. Note that the requested flags might not
1598 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1599 // combine the requested flags with its own flags, yielding an unsupported combination.
1600 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1601 return NAME_NOT_FOUND;
1602 }
1603
Eric Laurentc529cf62020-04-17 18:19:10 -07001604 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1605 // This prevents creating an offloaded track and tearing it down immediately after start
1606 // when audioflinger detects there is an active non offloadable effect.
1607 // FIXME: We should check the audio session here but we do not have it in this context.
1608 // This may prevent offloading in rare situations where effects are left active by apps
1609 // in the background.
1610 sp<IOProfile> profile;
1611 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1612 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1613 profile = getProfileForOutput(
1614 devices, config->sample_rate, config->format, config->channel_mask,
1615 flags, true /* directOnly */);
1616 }
1617
1618 if (profile == nullptr) {
1619 return NAME_NOT_FOUND;
1620 }
1621
1622 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1623 for (size_t i = 0; i < mOutputs.size(); i++) {
1624 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1625 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1626 // reuse direct output if currently open by the same client
1627 // and configured with same parameters
1628 if ((config->sample_rate == desc->getSamplingRate()) &&
1629 (config->format == desc->getFormat()) &&
1630 (config->channel_mask == desc->getChannelMask()) &&
1631 (session == desc->mDirectClientSession)) {
1632 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301633 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001634 mOutputs.keyAt(i), session);
1635 *output = mOutputs.keyAt(i);
1636 return NO_ERROR;
1637 }
1638 }
1639 }
1640
1641 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001642 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301643 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1644 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001645 return NAME_NOT_FOUND;
1646 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1647 // MMAP gracefully handles lack of an exclusive track resource by mixing
1648 // above the audio framework. For AAudio to know that the limit is reached,
1649 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301650 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1651 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001652 return NAME_NOT_FOUND;
1653 } else {
1654 // Close outputs on this profile, if available, to free resources for this request
1655 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1656 const auto desc = mOutputs.valueAt(i);
1657 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301658 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1659 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001660 closeOutput(desc->mIoHandle);
1661 }
1662 }
1663 }
1664 }
1665
1666 // Unable to close streams to find free resources for this request
1667 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301668 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1669 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001670 return NAME_NOT_FOUND;
1671 }
1672
Atneya Nairb16666a2023-12-11 20:18:33 -08001673 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001674
Michael Chan6fb34492020-12-08 15:44:49 +11001675 // An MSD patch may be using the only output stream that can service this request. Release
1676 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001677 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001678
Eric Laurentf1f22e72021-07-13 14:04:14 +02001679 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001680 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001681 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001682
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001683 // only accept an output with the requested parameters, unless the format can be IEC61937
1684 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1685 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1686 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1687 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001688 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001689 (!ignoreRequestedParametersCheck &&
1690 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1691 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1692 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001693 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1694 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1695 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1696 config->channel_mask, outputDesc->getChannelMask());
1697 if (*output != AUDIO_IO_HANDLE_NONE) {
1698 outputDesc->close();
1699 }
1700 // fall back to mixer output if possible when the direct output could not be open
1701 if (audio_is_linear_pcm(config->format) &&
1702 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1703 return NAME_NOT_FOUND;
1704 }
1705 *output = AUDIO_IO_HANDLE_NONE;
1706 return BAD_VALUE;
1707 }
1708 outputDesc->mDirectOpenCount = 1;
1709 outputDesc->mDirectClientSession = session;
1710
1711 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001712 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1713 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1714 hwModule->getHalVersionMajor() >= 3) {
1715 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1716 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001717 mPreviousOutputs = mOutputs;
1718 ALOGV("%s returns new direct output %d", __func__, *output);
1719 mpClientInterface->onAudioPortListUpdate();
1720 return NO_ERROR;
1721}
1722
François Gaffie11d30102018-11-02 16:09:09 +01001723audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1724 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001725 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001726 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001727 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001728 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001729 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001730 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001731 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001732{
Andy Hungc88b0642018-04-27 15:42:35 -07001733 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001734
jiabine375d412019-02-26 12:54:53 -08001735 // Discard haptic channel mask when forcing muting haptic channels.
1736 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001737 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1738 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001739
Eric Laurente552edb2014-03-10 17:42:56 -07001740 // open a direct output if required by specified parameters
1741 //force direct flag if offload flag is set: offloading implies a direct output stream
1742 // and all common behaviors are driven by checking only the direct flag
1743 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001744 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1745 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001746 }
Nadav Bar766fb022018-01-07 12:18:03 +02001747 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1748 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001749 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001750
1751 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1752
Eric Laurente83b55d2014-11-14 10:06:21 -08001753 // only allow deep buffering for music stream type
1754 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001755 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001756 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001757 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001758 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001759 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001760 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001761 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001762 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001763 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001764 audio_is_linear_pcm(config->format) &&
1765 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001766 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001767 AUDIO_OUTPUT_FLAG_DIRECT);
1768 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001769 }
Eric Laurente552edb2014-03-10 17:42:56 -07001770
Carter Hsua3abb402021-10-26 11:11:20 +08001771 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1772 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1773 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1774 }
1775
Eric Laurentf9230d52024-01-26 18:49:09 +01001776 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001777 // was specified and offload or direct playback is not explicitly requested, and there is no
1778 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001779 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001780 if (mSpatializerOutput != nullptr &&
1781 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1782 prefMixerConfigInfo == nullptr &&
1783 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1784 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001785 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001786 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001787 }
1788
Eric Laurentc529cf62020-04-17 18:19:10 -07001789 audio_config_t directConfig = *config;
1790 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001791
1792 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1793 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001794 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001795 return output;
1796 }
1797
Eric Laurent14cbfca2016-03-17 09:42:16 -07001798 // A request for HW A/V sync cannot fallback to a mixed output because time
1799 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001800 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001801 return AUDIO_IO_HANDLE_NONE;
1802 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001803 // A request for Tuner cannot fallback to a mixed output
1804 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1805 return AUDIO_IO_HANDLE_NONE;
1806 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001807
Eric Laurente552edb2014-03-10 17:42:56 -07001808 // ignoring channel mask due to downmix capability in mixer
1809
1810 // open a non direct output
1811
1812 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001813 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001814 // get which output is suitable for the specified stream. The actual
1815 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001816 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001817 if (prefMixerConfigInfo != nullptr) {
1818 for (audio_io_handle_t outputHandle : outputs) {
1819 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1820 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1821 output = outputHandle;
1822 break;
1823 }
1824 }
1825 if (output == AUDIO_IO_HANDLE_NONE) {
1826 // No output open with the preferred profile. Open a new one.
1827 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1828 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1829 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1830 config.format = prefMixerConfigInfo->getConfigBase().format;
1831 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1832 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1833 &config, prefMixerConfigInfo->getFlags());
1834 if (preferredOutput == nullptr) {
1835 ALOGE("%s failed to open output with preferred mixer config", __func__);
1836 } else {
1837 output = preferredOutput->mIoHandle;
1838 }
1839 }
1840 } else {
1841 // at this stage we should ignore the DIRECT flag as no direct output could be
1842 // found earlier
1843 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001844 if (com::android::media::audioserver::
1845 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1846 // If the preferred mixer attributes is null, do not select the bit-perfect output
1847 // unless the bit-perfect output is the only output.
1848 // The bit-perfect output can exist while the passed in preferred mixer attributes
1849 // info is null when it is a high priority client. The high priority clients are
1850 // ringtone or alarm, which is not a bit-perfect use case.
1851 size_t i = 0;
1852 while (i < outputs.size() && outputs.size() > 1) {
1853 auto desc = mOutputs.valueFor(outputs[i]);
1854 // The output descriptor must not be null here.
1855 if (desc->isBitPerfect()) {
1856 outputs.removeItemsAt(i);
1857 } else {
1858 i += 1;
1859 }
1860 }
1861 }
jiabina84c3d32022-12-02 18:59:55 +00001862 output = selectOutput(
1863 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1864 }
Eric Laurente552edb2014-03-10 17:42:56 -07001865 }
François Gaffie11d30102018-11-02 16:09:09 +01001866 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001867 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001868 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001869
Eric Laurente552edb2014-03-10 17:42:56 -07001870 return output;
1871}
1872
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001873sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001874 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1875 mAvailableInputDevices);
1876 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1877}
1878
1879DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1880 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1881 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882}
1883
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001884const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001886 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1887 if (msdModule != 0) {
1888 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1889 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1890 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1891 const struct audio_port_config *source = &patch->mPatch.sources[j];
1892 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1893 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001894 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001895 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001896 }
1897 }
1898 }
1899 return msdPatches;
1900}
1901
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001902bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1903 ssize_t index = mAudioPatches.indexOfKey(handle);
1904 if (index < 0) {
1905 return false;
1906 }
1907 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1908 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1909 if (msdModule == nullptr) {
1910 return false;
1911 }
1912 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1913 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1914 return true;
1915 }
1916 index = getMsdOutputPatches().indexOfKey(handle);
1917 if (index < 0) {
1918 return false;
1919 }
1920 return true;
1921}
1922
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001923status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1924 const InputProfileCollection &inputProfiles,
1925 const OutputProfileCollection &outputProfiles,
1926 const sp<DeviceDescriptor> &sourceDevice,
1927 const sp<DeviceDescriptor> &sinkDevice,
1928 AudioProfileVector& sourceProfiles,
1929 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001931 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 return NO_INIT;
1933 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001935 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001936 return NO_INIT;
1937 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001938 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001939 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1940 inProfile->supportsDevice(sourceDevice)) {
1941 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001942 }
1943 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001944 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001945 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001946 outProfile->supportsDevice(sinkDevice)) {
1947 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 }
1949 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001950 return NO_ERROR;
1951}
1952
1953status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1954 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1955 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1956{
Dean Wheatley16809da2022-12-09 14:55:46 +11001957 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1958 static const std::vector<audio_format_t> formatsOrder = {{
1959 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001960 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1961 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001962 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1963 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1964 // preferred).
1965 std::vector<audio_channel_mask_t> masks = {{
1966 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1967 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1968 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1969 // insert index masks (higher counts most preferred) as preferred over position masks
1970 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1971 masks.insert(
1972 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1973 }
1974 return masks;
1975 }();
1976
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001977 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001978 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1979 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001980 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001981 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1982 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001983 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001984 }
1985 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1986 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1987 sinkConfig->format = bestSinkConfig.format;
1988 // For encoded streams force direct flag to prevent downstream mixing.
1989 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1990 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001991 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1992 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001993 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001994 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1995 // raw and IEC61937 framed streams.
1996 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1997 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1998 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001999 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2000 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002001 sourceConfig->channel_mask =
2002 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2003 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2004 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002005 sourceConfig->format = bestSinkConfig.format;
2006 // Copy input stream directly without any processing (e.g. resampling).
2007 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2008 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2009 if (hwAvSync) {
2010 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2011 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2012 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2013 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2014 }
2015 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2016 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2017 sinkConfig->config_mask |= config_mask;
2018 sourceConfig->config_mask |= config_mask;
2019 return NO_ERROR;
2020}
2021
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002022PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2023 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002024{
2025 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002026 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2027 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2028 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2029 if (deviceModule == nullptr) {
2030 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2031 return patchBuilder;
2032 }
2033 const InputProfileCollection inputProfiles = msdIsSource ?
2034 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2035 const OutputProfileCollection outputProfiles = msdIsSource ?
2036 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2037
2038 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2039 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2040 device : getMsdAudioOutDevices().itemAt(0);
2041 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2042
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002043 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2044 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002045 AudioProfileVector sourceProfiles;
2046 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002047 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2048 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002049 for (auto hwAvSync : { true, false }) {
2050 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2051 sourceProfiles, sinkProfiles) != NO_ERROR) {
2052 continue;
2053 }
2054 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2055 &sinkConfig) == NO_ERROR) {
2056 // Found a matching config. Re-create PatchBuilder with this config.
2057 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2058 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002059 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002060 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002061 " supporting PCM format conversion.", __func__);
2062 return patchBuilder;
2063}
2064
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002065status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002066 DeviceVector devices;
2067 if (outputDevices != nullptr && outputDevices->size() > 0) {
2068 devices.add(*outputDevices);
2069 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002070 // Use media strategy for unspecified output device. This should only
2071 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2072 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002073 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002074 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002075 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002076 }
Michael Chan6fb34492020-12-08 15:44:49 +11002077 std::vector<PatchBuilder> patchesToCreate;
2078 for (auto i = 0u; i < devices.size(); ++i) {
2079 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002080 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002081 }
2082 // Retain only the MSD patches associated with outputDevices request.
2083 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002084 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002085 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2086 auto retainedPatch = false;
2087 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2088 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2089 patchesToRemove.removeItemsAt(i);
2090 retainedPatch = true;
2091 break;
2092 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002093 }
Michael Chan6fb34492020-12-08 15:44:49 +11002094 if (retainedPatch) {
2095 it = patchesToCreate.erase(it);
2096 continue;
2097 }
2098 ++it;
2099 }
2100 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2101 return NO_ERROR;
2102 }
2103 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2104 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002105 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002106 }
Michael Chan6fb34492020-12-08 15:44:49 +11002107 status_t status = NO_ERROR;
2108 for (const auto &p : patchesToCreate) {
2109 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2110 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2111 char message[256];
2112 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2113 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2114 currStatus == NO_ERROR ? "Success" : "Error",
2115 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2116 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2117 if (currStatus == NO_ERROR) {
2118 ALOGD("%s", message);
2119 } else {
2120 ALOGE("%s", message);
2121 if (status == NO_ERROR) {
2122 status = currStatus;
2123 }
2124 }
2125 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002126 return status;
2127}
2128
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002129void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2130 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002131 for (size_t i = 0; i < msdPatches.size(); i++) {
2132 const auto& patch = msdPatches[i];
2133 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2134 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2135 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2136 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2137 releaseAudioPatch(patch->getHandle(), mUidCached);
2138 break;
2139 }
2140 }
2141 }
2142}
2143
Dorin Drimus94d94412022-02-02 09:05:02 +01002144bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002145 DeviceVector devicesToCheck =
2146 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002147 AudioPatchCollection msdPatches = getMsdOutputPatches();
2148 for (size_t i = 0; i < msdPatches.size(); i++) {
2149 const auto& patch = msdPatches[i];
2150 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2151 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2152 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2153 const auto& foundDevice = devicesToCheck.getDevice(
2154 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2155 if (foundDevice != nullptr) {
2156 devicesToCheck.remove(foundDevice);
2157 if (devicesToCheck.isEmpty()) {
2158 return true;
2159 }
2160 }
2161 }
2162 }
2163 }
2164 return false;
2165}
2166
Eric Laurente0720872014-03-11 09:30:41 -07002167audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002168 audio_output_flags_t flags,
2169 audio_format_t format,
2170 audio_channel_mask_t channelMask,
2171 uint32_t samplingRate,
2172 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002173{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2175 "%s called with format %#x", __func__, format);
2176
jiabinebb6af42020-06-09 17:31:17 -07002177 // Return the output that haptic-generating attached to when 1) session id is specified,
2178 // 2) haptic-generating effect exists for given session id and 3) the output that
2179 // haptic-generating effect attached to is in given outputs.
2180 if (sessionId != AUDIO_SESSION_NONE) {
2181 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2182 sessionId, FX_IID_HAPTICGENERATOR);
2183 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2184 return hapticGeneratingOutput;
2185 }
2186 }
2187
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 // Flags disqualifying an output: the match must happen before calling selectOutput()
2189 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2190 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2191
2192 // Flags expressing a functional request: must be honored in priority over
2193 // other criteria
2194 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2195 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002196 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2197 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002198 // Flags expressing a performance request: have lower priority than serving
2199 // requested sampling rate or channel mask
2200 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2201 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2202 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2203
2204 const audio_output_flags_t functionalFlags =
2205 (audio_output_flags_t)(flags & kFunctionalFlags);
2206 const audio_output_flags_t performanceFlags =
2207 (audio_output_flags_t)(flags & kPerformanceFlags);
2208
2209 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2210
Eric Laurente552edb2014-03-10 17:42:56 -07002211 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002212 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002213 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002214 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002215 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002216 // with tiebreak preferring the minimum number of extra functional flags
2217 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002218 // 3: the output supporting the exact channel mask
2219 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002220 // 5: the output with the highest sampling rate if the requested sample rate is
2221 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002222 // 6: the output with the highest number of requested performance flags
2223 // 7: the output with the bit depth the closest to the requested one
2224 // 8: the primary output
2225 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002226
Eric Laurent16c66dd2019-05-01 17:54:10 -07002227 // matching criteria values in priority order for best matching output so far
2228 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002229
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002230 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2232 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2233 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002234
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002235 for (audio_io_handle_t output : outputs) {
2236 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002237 // matching criteria values in priority order for current output
2238 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002239
Eric Laurent16c66dd2019-05-01 17:54:10 -07002240 if (outputDesc->isDuplicated()) {
2241 continue;
2242 }
2243 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2244 continue;
2245 }
Eric Laurent8838a382014-09-08 16:44:28 -07002246
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 // If haptic channel is specified, use the haptic output if present.
2248 // When using haptic output, same audio format and sample rate are required.
2249 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002250 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002251 // skip if haptic channel specified but output does not support it, or output support haptic
2252 // but there is no haptic channel requested AND no orphan haptic effect exist
2253 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2254 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002255 continue;
2256 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002257 // In the case of audio-coupled-haptic playback, there is no format conversion and
2258 // resampling in the framework, same format/channel/sampleRate for client and the output
2259 // thread is required. In the case of HapticGenerator effect, do not require format
2260 // matching.
2261 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2262 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002263 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002264 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002265 }
2266
2267 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002268 const int matchingFunctionalFlags =
2269 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2270 const int totalFunctionalFlags =
2271 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2272 // Prefer matching functional flags, but subtract unnecessary functional flags.
2273 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002274
2275 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002276 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2277 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002278 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2279 channelCount <= outputChannelCount) {
2280 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002281 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2282 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002283 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002285 currentMatchCriteria[3] = outputChannelCount;
2286 }
2287
2288 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002289 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002290 int diff; // avoid unsigned integer overflow.
2291 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2292
2293 // prefer the closest output sampling rate greater than or equal to target
2294 // if none exists, prefer the closest output sampling rate less than target.
2295 //
2296 // criteria is offset to make non-negative.
2297 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002298 }
2299
2300 // performance flags match
2301 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2302
2303 // format match
2304 if (format != AUDIO_FORMAT_INVALID) {
2305 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002306 PolicyAudioPort::kFormatDistanceMax -
2307 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002308 }
2309
2310 // primary output match
2311 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2312
2313 // compare match criteria by priority then value
2314 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2315 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2316 bestMatchCriteria = currentMatchCriteria;
2317 bestOutput = output;
2318
2319 std::stringstream result;
2320 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2321 std::ostream_iterator<int>(result, " "));
2322 ALOGV("%s new bestOutput %d criteria %s",
2323 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002324 }
2325 }
2326
Eric Laurent16c66dd2019-05-01 17:54:10 -07002327 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002328}
2329
Eric Laurent8fc147b2018-07-22 19:13:55 -07002330status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002331{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002332 ALOGV("%s portId %d", __FUNCTION__, portId);
2333
2334 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2335 if (outputDesc == 0) {
2336 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002337 return BAD_VALUE;
2338 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002339 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002340
Eric Laurent8fc147b2018-07-22 19:13:55 -07002341 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002342 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002343
jiabin220eea12024-05-17 17:55:20 +00002344 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2345 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2346 && outputDesc->isBitPerfect()) {
2347 // Usually, APM selects bit-perfect output for high priority use cases only when
2348 // bit-perfect output is the only output that can be routed to the selected device.
2349 // However, here is no need to play high priority use cases such as ringtone and alarm
2350 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2351 // can attach to new output.
2352 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2353 __func__, client->stream());
2354 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2355 return DEAD_OBJECT;
2356 }
2357
Eric Laurent733ce942017-12-07 12:18:25 -08002358 status_t status = outputDesc->start();
2359 if (status != NO_ERROR) {
2360 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002361 }
2362
Eric Laurent97ac8712018-07-27 18:59:02 -07002363 uint32_t delayMs;
2364 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002365
2366 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002367 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002368 if (status == DEAD_OBJECT) {
2369 sp<SwAudioOutputDescriptor> desc =
2370 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2371 if (desc == nullptr) {
2372 // This is not common, it may indicate something wrong with the HAL.
2373 ALOGE("%s unable to open output with default config", __func__);
2374 return status;
2375 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002376 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002377 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002378 }
jiabina84c3d32022-12-02 18:59:55 +00002379
2380 // If the client is the first one active on preferred mixer parameters, reopen the output
2381 // if the current mixer parameters doesn't match the preferred one.
2382 if (outputDesc->devices().size() == 1) {
2383 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2384 outputDesc->devices()[0]->getId(), client->strategy());
2385 if (info != nullptr && info->getUid() == client->uid()) {
2386 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2387 info->getConfigBase(), info->getFlags())) {
2388 stopSource(outputDesc, client);
2389 outputDesc->stop();
2390 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2391 config.channel_mask = info->getConfigBase().channel_mask;
2392 config.sample_rate = info->getConfigBase().sample_rate;
2393 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002394 sp<SwAudioOutputDescriptor> desc =
2395 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2396 if (desc == nullptr) {
2397 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002398 }
jiabin220eea12024-05-17 17:55:20 +00002399 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002400 // Intentionally return error to let the client side resending request for
2401 // creating and starting.
2402 return DEAD_OBJECT;
2403 }
2404 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002405 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002406 // If it is first bit-perfect client, reroute all clients that will be routed to
2407 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2408 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002409 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002410 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002411 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2412 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002413 continue;
2414 }
jiabine6b87492024-09-18 23:36:14 +00002415 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2416 outputsToResetDevice.push_back(mOutputs[i]);
2417 }
jiabine3d1f552023-06-14 17:42:17 +00002418 for (const auto& c : mOutputs[i]->getClientIterable()) {
2419 clientsToInvalidate.push_back(c->portId());
2420 }
2421 }
2422 if (!clientsToInvalidate.empty()) {
2423 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2424 __func__);
2425 mpClientInterface->invalidateTracks(clientsToInvalidate);
2426 }
jiabine6b87492024-09-18 23:36:14 +00002427 for (const auto& output : outputsToResetDevice) {
2428 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2429 }
jiabine3d1f552023-06-14 17:42:17 +00002430 }
jiabina84c3d32022-12-02 18:59:55 +00002431 }
2432 }
2433
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002434 if (client->hasPreferredDevice()) {
2435 // playback activity with preferred device impacts routing occurred, inform upper layers
2436 mpClientInterface->onRoutingUpdated();
2437 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002438 if (delayMs != 0) {
2439 usleep(delayMs * 1000);
2440 }
2441
jiabin220eea12024-05-17 17:55:20 +00002442 if (status == NO_ERROR &&
2443 outputDesc->mPreferredAttrInfo != nullptr &&
2444 outputDesc->isBitPerfect() &&
2445 com::android::media::audioserver::
2446 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2447 // A new client is started on bit-perfect output, update all clients internal mute.
2448 updateClientsInternalMute(outputDesc);
2449 }
2450
Eric Laurentc75307b2015-03-17 15:29:32 -07002451 return status;
2452}
2453
Eric Laurent96d1dda2022-03-14 17:14:19 +01002454bool AudioPolicyManager::isLeUnicastActive() const {
2455 if (isInCall()) {
2456 return true;
2457 }
2458 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2459}
2460
2461bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2462 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2463 return false;
2464 }
2465 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2466 ALOGV("%s active %d", __func__, active);
2467 return active;
2468}
2469
Eric Laurent97ac8712018-07-27 18:59:02 -07002470status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2471 const sp<TrackClientDescriptor>& client,
2472 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002473{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002474 // cannot start playback of STREAM_TTS if any other output is being used
2475 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002476
2477 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002478 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002479 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002480 auto clientStrategy = client->strategy();
2481 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002482 if (stream == AUDIO_STREAM_TTS) {
2483 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002484 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002485 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002486 return INVALID_OPERATION;
2487 } else {
2488 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2489 }
2490 } else {
2491 // some playback other than beacon starts
2492 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2493 }
2494
Eric Laurent77305a62016-07-25 16:39:22 -07002495 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002496 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002497 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002498
François Gaffie11d30102018-11-02 16:09:09 +01002499 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002500 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002501 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002502 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002503 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002504 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002505 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002506 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002507 } else {
2508 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002509 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002510 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2511 AUDIO_FORMAT_DEFAULT);
2512 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2513 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002514 }
2515
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002516 // requiresMuteCheck is false when we can bypass mute strategy.
2517 // It covers a common case when there is no materially active audio
2518 // and muting would result in unnecessary delay and dropped audio.
2519 const uint32_t outputLatencyMs = outputDesc->latency();
2520 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002521 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002522
Eric Laurente552edb2014-03-10 17:42:56 -07002523 // increment usage count for this stream on the requested output:
2524 // NOTE that the usage count is the same for duplicated output and hardware output which is
2525 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002526 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002527
2528 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002529 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002530 // Preferred device may be exclusive, use only if no other active clients on this output
2531 devices = DeviceVector(
2532 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2533 } else {
2534 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2535 }
François Gaffie11d30102018-11-02 16:09:09 +01002536 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002537 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 }
2539 }
Eric Laurente552edb2014-03-10 17:42:56 -07002540
François Gaffiec005e562018-11-06 15:04:49 +01002541 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002542 selectOutputForMusicEffects();
2543 }
2544
François Gaffie1c878552018-11-22 16:53:21 +01002545 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002546 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002547 if (devices.isEmpty()) {
2548 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002549 }
François Gaffiec005e562018-11-06 15:04:49 +01002550 bool shouldWait =
2551 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2552 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2553 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002554 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002555 const bool needToCloseBitPerfectOutput =
2556 (com::android::media::audioserver::
2557 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2558 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2559 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002560 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002561 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002562 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002563 // An output has a shared device if
2564 // - managed by the same hw module
2565 // - supports the currently selected device
2566 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002567 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002568
Eric Laurent77305a62016-07-25 16:39:22 -07002569 // force a device change if any other output is:
2570 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002571 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002572 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002573 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002574 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002575 // change the device currently selected by the other output.
2576 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002577 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002578 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002579 force = true;
2580 }
2581 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002582 // a notification so that audio focus effect can propagate, or that a mute/unmute
2583 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002584 const uint32_t latencyMs = desc->latency();
2585 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2586
2587 if (shouldWait && isActive && (waitMs < latencyMs)) {
2588 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002589 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002590
2591 // Require mute check if another output is on a shared device
2592 // and currently active to have proper drain and avoid pops.
2593 // Note restoring AudioTracks onto this output needs to invoke
2594 // a volume ramp if there is no mute.
2595 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002596
2597 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2598 outputsToReopen.push_back(desc);
2599 }
Eric Laurente552edb2014-03-10 17:42:56 -07002600 }
2601 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002602
jiabin220eea12024-05-17 17:55:20 +00002603 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002604 // If the output is open with preferred mixer attributes, but the routed device is
2605 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2606 // changed.
2607 return DEAD_OBJECT;
2608 }
jiabin220eea12024-05-17 17:55:20 +00002609 for (auto& outputToReopen : outputsToReopen) {
2610 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2611 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002612 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302613 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2614 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002615
Eric Laurente552edb2014-03-10 17:42:56 -07002616 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002617 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002618 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002619 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002620 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002621 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002622 outputDesc->useHwGain() /*force*/)) {
2623 // request AudioService to reinitialize the volume curves asynchronously
2624 ALOGE("checkAndSetVolume failed, requesting volume range init");
2625 mpClientInterface->onVolumeRangeInitRequest();
2626 };
Eric Laurente552edb2014-03-10 17:42:56 -07002627
2628 // update the outputs if starting an output with a stream that can affect notification
2629 // routing
2630 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002631
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002632 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002633 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002634 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002635 }
Eric Laurentdc462862016-07-19 12:29:53 -07002636
2637 if (waitMs > muteWaitMs) {
2638 *delayMs = waitMs - muteWaitMs;
2639 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002640
2641 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2642 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2643 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2644 // change occurs after the MixerThread starts and causes a stream volume
2645 // glitch.
2646 //
2647 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002648 }
Eric Laurentdc462862016-07-19 12:29:53 -07002649
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002650 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002651 mEngine->getForceUse(
2652 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002653 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002654 }
2655
Eric Laurent97ac8712018-07-27 18:59:02 -07002656 // Automatically enable the remote submix input when output is started on a re routing mix
2657 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002658 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2659 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002660 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2661 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2662 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002663 "remote-submix",
2664 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002665 }
2666
Eric Laurent96d1dda2022-03-14 17:14:19 +01002667 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2668
Eric Laurente552edb2014-03-10 17:42:56 -07002669 return NO_ERROR;
2670}
2671
Eric Laurent96d1dda2022-03-14 17:14:19 +01002672void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2673 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2674 bool isUnicastActive = isLeUnicastActive();
2675
2676 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002677 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002678 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2679 for (size_t i = 0; i < mOutputs.size(); i++) {
2680 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2681 if (desc != ignoredOutput && desc->isActive()
2682 && ((isUnicastActive &&
2683 !desc->devices().
2684 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2685 || (wasUnicastActive &&
2686 !desc->devices().getDevicesFromTypes(
2687 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2688 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2689 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002690 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002691 // If the device is using preferred mixer attributes, the output need to reopen
2692 // with default configuration when the new selected devices are different from
2693 // current routing devices.
2694 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2695 continue;
2696 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302697 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002698 // re-apply device specific volume if not done by setOutputDevice()
2699 if (!force) {
2700 applyStreamVolumes(desc, newDevices.types(), delayMs);
2701 }
2702 }
2703 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002704 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002705 }
2706}
2707
Eric Laurent8fc147b2018-07-22 19:13:55 -07002708status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002709{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002710 ALOGV("%s portId %d", __FUNCTION__, portId);
2711
2712 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2713 if (outputDesc == 0) {
2714 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002715 return BAD_VALUE;
2716 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002717 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002718
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002719 if (client->hasPreferredDevice(true)) {
2720 // playback activity with preferred device impacts routing occurred, inform upper layers
2721 mpClientInterface->onRoutingUpdated();
2722 }
2723
Eric Laurent97ac8712018-07-27 18:59:02 -07002724 ALOGV("stopOutput() output %d, stream %d, session %d",
2725 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002726
Eric Laurent97ac8712018-07-27 18:59:02 -07002727 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002728
Eric Laurent733ce942017-12-07 12:18:25 -08002729 if (status == NO_ERROR ) {
2730 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002731 } else {
2732 return status;
2733 }
2734
2735 if (outputDesc->devices().size() == 1) {
2736 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2737 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002738 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002739 if (info != nullptr && info->getUid() == client->uid()) {
2740 info->decreaseActiveClient();
2741 if (info->getActiveClientCount() == 0) {
2742 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002743 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002744 }
2745 }
jiabin220eea12024-05-17 17:55:20 +00002746 if (com::android::media::audioserver::
2747 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2748 !outputReopened && outputDesc->isBitPerfect()) {
2749 // Only need to update the clients' internal mute when the output is bit-perfect and it
2750 // is not reopened.
2751 updateClientsInternalMute(outputDesc);
2752 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002753 }
2754 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002755}
2756
Eric Laurent97ac8712018-07-27 18:59:02 -07002757status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2758 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002759{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002760 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002761 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002762 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002763 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002764
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002765 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2766
François Gaffie1c878552018-11-22 16:53:21 +01002767 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2768 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002769 // Automatically disable the remote submix input when output is stopped on a
2770 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002771 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002772 if (isSingleDeviceType(
2773 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002774 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002775 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002776 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2777 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002778 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002779 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002780 }
2781 }
2782 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002783 if (client->hasPreferredDevice(true) &&
2784 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002785 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002786 forceDeviceUpdate = true;
2787 }
2788
Eric Laurente552edb2014-03-10 17:42:56 -07002789 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002790 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002791
Eric Laurente552edb2014-03-10 17:42:56 -07002792 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002793 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002794 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002795 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002796
2797 // If the routing does not change, if an output is routed on a device using HwGain
2798 // (aka setAudioPortConfig) and there are still active clients following different
2799 // volume group(s), force reapply volume
2800 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2801 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2802
Eric Laurente552edb2014-03-10 17:42:56 -07002803 // delay the device switch by twice the latency because stopOutput() is executed when
2804 // the track stop() command is received and at that time the audio track buffer can
2805 // still contain data that needs to be drained. The latency only covers the audio HAL
2806 // and kernel buffers. Also the latency does not always include additional delay in the
2807 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302808 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002809 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002810
2811 // force restoring the device selection on other active outputs if it differs from the
2812 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002813 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002814 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002815 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002816 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002817 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002818 desc->isActive() &&
2819 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002820 (newDevices != desc->devices())) {
2821 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2822 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002823
jiabin220eea12024-05-17 17:55:20 +00002824 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002825 // If the device is using preferred mixer attributes, the output need to
2826 // reopen with default configuration when the new selected devices are
2827 // different from current routing devices.
2828 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2829 continue;
2830 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302831 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002832
Eric Laurent57de36c2016-09-28 16:59:11 -07002833 // re-apply device specific volume if not done by setOutputDevice()
2834 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002835 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002836 }
Eric Laurente552edb2014-03-10 17:42:56 -07002837 }
2838 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002839 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002840 // update the outputs if stopping one with a stream that can affect notification routing
2841 handleNotificationRoutingForStream(stream);
2842 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002843
2844 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2845 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002846 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002847 }
2848
François Gaffiec005e562018-11-06 15:04:49 +01002849 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002850 selectOutputForMusicEffects();
2851 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002852
2853 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2854
Eric Laurente552edb2014-03-10 17:42:56 -07002855 return NO_ERROR;
2856 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002857 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002858 return INVALID_OPERATION;
2859 }
2860}
2861
jiabinbce0c1d2020-10-05 11:20:18 -07002862bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002863{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002864 ALOGV("%s portId %d", __FUNCTION__, portId);
2865
2866 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2867 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002868 // If an output descriptor is closed due to a device routing change,
2869 // then there are race conditions with releaseOutput from tracks
2870 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2871 // destroyed shortly thereafter.
2872 //
2873 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002874 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002875 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002876 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002877
2878 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002879
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302880 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2881 if (outputDesc->isClientActive(client)) {
2882 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2883 stopOutput(portId);
2884 }
2885
Eric Laurent8fc147b2018-07-22 19:13:55 -07002886 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2887 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002888 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002890 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002891 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892 if (--outputDesc->mDirectOpenCount == 0) {
2893 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002894 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002895 }
2896 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302897
Andy Hung39efb7a2018-09-26 15:39:28 -07002898 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002899 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2900 // The output is pending reopened to query dynamic profiles and
2901 // there is no active clients
2902 closeOutput(outputDesc->mIoHandle);
2903 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2904 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2905 if (newOutputDesc == nullptr) {
2906 ALOGE("%s failed to open output", __func__);
2907 }
2908 return true;
2909 }
2910 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002911}
2912
Eric Laurentcaf7f482014-11-25 17:50:47 -08002913status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2914 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002915 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002916 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002917 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002918 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002919 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002920 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002921 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002922 audio_port_handle_t *portId,
2923 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002924{
François Gaffiec005e562018-11-06 15:04:49 +01002925 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002926 "flags %#x attributes=%s requested device ID %d",
2927 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2928 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002929
Eric Laurentad2e7b92017-09-14 20:06:42 -07002930 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002931 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002932 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002933 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002934 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002935 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002936 sp<RecordClientDescriptor> clientDesc;
2937 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002938 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002939 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940
2941 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2942 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2943 return INVALID_OPERATION;
2944 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002945
Francois Gaffie716e1432019-01-14 16:58:59 +01002946 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2947 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002948 }
2949
Paul McLean466dc8e2015-04-17 13:15:36 -06002950 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002951 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002952 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002953
Eric Laurentad2e7b92017-09-14 20:06:42 -07002954 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2955 // possible
2956 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2957 *input != AUDIO_IO_HANDLE_NONE) {
2958 ssize_t index = mInputs.indexOfKey(*input);
2959 if (index < 0) {
2960 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2961 status = BAD_VALUE;
2962 goto error;
2963 }
2964 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002965 RecordClientVector clients = inputDesc->getClientsForSession(session);
2966 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002967 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2968 status = BAD_VALUE;
2969 goto error;
2970 }
2971 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2972 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002973 // corresponds to a new client and is only permitted from the same UID.
2974 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002975 if (clients.size() > 1) {
2976 for (const auto& client : clients) {
2977 // The client map is ordered by key values (portId) and portIds are allocated
2978 // incrementaly. So the first client in this list is the one opened by audio flinger
2979 // when the mmap stream is created and should be ignored as it does not correspond
2980 // to an actual client
2981 if (client == *clients.cbegin()) {
2982 continue;
2983 }
2984 if (uid != client->uid() && !client->isSilenced()) {
2985 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2986 uid, client->portId(), client->uid());
2987 status = INVALID_OPERATION;
2988 goto error;
2989 }
Eric Laurent331679c2018-04-16 17:03:16 -07002990 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002991 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002992 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002993 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002994
Eric Laurentfecbceb2021-02-09 14:46:43 +01002995 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002996 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002997 }
2998
2999 *input = AUDIO_IO_HANDLE_NONE;
3000 *inputType = API_INPUT_INVALID;
3001
Francois Gaffie716e1432019-01-14 16:58:59 +01003002 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003003 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003004 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003005 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003006 ALOGW("%s could not find input mix for attr %s",
3007 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003008 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003009 }
jiabinc1de2df2019-05-07 14:26:40 -07003010 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3011 String8(attr->tags + strlen("addr=")),
3012 AUDIO_FORMAT_DEFAULT);
3013 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003014 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003015 __func__, attributes.source, attributes.tags);
3016 status = BAD_VALUE;
3017 goto error;
3018 }
3019
Kevin Rocard25f9b052019-02-27 15:08:54 -08003020 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3021 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3022 } else {
3023 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3024 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003025 if (virtualDeviceId) {
3026 *virtualDeviceId = policyMix->mVirtualDeviceId;
3027 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003028 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003029 if (explicitRoutingDevice != nullptr) {
3030 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003031 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003032 // Prevent from storing invalid requested device id in clients
3033 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003034 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003035 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3036 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003037 }
François Gaffie11d30102018-11-02 16:09:09 +01003038 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003039 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003040 status = BAD_VALUE;
3041 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003042 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003043 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3044 *inputType = API_INPUT_MIX_CAPTURE;
3045 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003046 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3047 // there is an external policy, but this input is attached to a mix of recorders,
3048 // meaning it receives audio injected into the framework, so the recorder doesn't
3049 // know about it and is therefore considered "legacy"
3050 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003051
3052 if (virtualDeviceId) {
3053 *virtualDeviceId = policyMix->mVirtualDeviceId;
3054 }
François Gaffie11d30102018-11-02 16:09:09 +01003055 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003056 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003057 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003058 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003059 } else {
3060 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003061 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003062
Eric Laurent599c7582015-12-07 18:05:55 -08003063 }
3064
François Gaffiec005e562018-11-06 15:04:49 +01003065 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003066 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003067 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003068 AudioProfileVector profiles;
3069 status_t ret = getProfilesForDevices(
3070 DeviceVector(device), profiles, flags, true /*isInput*/);
3071 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003072 const auto channels = profiles[0]->getChannels();
3073 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3074 config->channel_mask = *channels.begin();
3075 }
3076 const auto sampleRates = profiles[0]->getSampleRates();
3077 if (!sampleRates.empty() &&
3078 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3079 config->sample_rate = *sampleRates.begin();
3080 }
jiabinf1c73972022-04-14 16:28:52 -07003081 config->format = profiles[0]->getFormat();
3082 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003083 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003084 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003085
Marvin Ramine5a122d2023-12-07 13:57:59 +01003086
3087 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3088 *virtualDeviceId = policyMix->mVirtualDeviceId;
3089 }
3090
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091exit:
3092
François Gaffiec005e562018-11-06 15:04:49 +01003093 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3094 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003095
Francois Gaffie716e1432019-01-14 16:58:59 +01003096 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003097 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003098 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099
Mikhail Naganov2996f672019-04-18 12:29:59 -07003100 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003101 requestedDeviceId, attributes.source, flags,
3102 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003103 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003104 // Move (if found) effect for the client session to its input
3105 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003106 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003107
3108 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3109 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003110
Eric Laurent599c7582015-12-07 18:05:55 -08003111 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003112
3113error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003114 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003115}
3116
3117
François Gaffie11d30102018-11-02 16:09:09 +01003118audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003119 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003120 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003121 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003122 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003123 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003124{
3125 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003126 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003127 bool isSoundTrigger = false;
3128
François Gaffiec005e562018-11-06 15:04:49 +01003129 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003130 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3131 if (index >= 0) {
3132 input = mSoundTriggerSessions.valueFor(session);
3133 isSoundTrigger = true;
3134 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3135 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3136 } else {
3137 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003138 }
François Gaffiec005e562018-11-06 15:04:49 +01003139 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003140 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003141 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003142 }
3143
Carter Hsua3abb402021-10-26 11:11:20 +08003144 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3145 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3146 }
3147
Eric Laurentfe231122017-11-17 17:48:06 -08003148 // sampling rate and flags may be updated by getInputProfile
3149 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3150 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003151 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003152 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003153 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003154 // find a compatible input profile (not necessarily identical in parameters)
3155 sp<IOProfile> profile = getInputProfile(
3156 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3157 if (profile == nullptr) {
3158 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003159 }
jiabin2fd710d2022-05-02 23:20:22 +00003160
Glenn Kasten05ddca52016-02-11 08:17:12 -08003161 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003162 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003163 if (samplingRate == 0) {
3164 samplingRate = profileSamplingRate;
3165 }
Eric Laurente552edb2014-03-10 17:42:56 -07003166
Eric Laurent322b4d22015-04-03 15:57:54 -07003167 if (profile->getModuleHandle() == 0) {
3168 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003169 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003170 }
3171
Eric Laurentec376dc2021-04-08 20:41:22 +02003172 // Reuse an already opened input if a client with the same session ID already exists
3173 // on that input
3174 for (size_t i = 0; i < mInputs.size(); i++) {
3175 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3176 if (desc->mProfile != profile) {
3177 continue;
3178 }
3179 RecordClientVector clients = desc->clientsList();
3180 for (const auto &client : clients) {
3181 if (session == client->session()) {
3182 return desc->mIoHandle;
3183 }
3184 }
3185 }
3186
Eric Laurentc71b11b2024-06-03 12:54:53 +00003187 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003188 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003189 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3190 // First pick best candidate for preemption (there may not be any):
3191 // - Preempt and input if:
3192 // - It has only strictly lower priority use cases than the new client
3193 // - It has equal priority use cases than the new client, was not
3194 // opened thanks to preemption or has been active since opened.
3195 // - Order the preemption candidates by inactive first and priority second
3196 sp<AudioInputDescriptor> closeCandidate;
3197 int leastCloseRank = INT_MAX;
3198 static const int sCloseActive = 0x100;
3199
3200 for (size_t i = 0; i < mInputs.size(); i++) {
3201 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3202 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003203 continue;
3204 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003205 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3206 if (topPrioClient == nullptr) {
3207 continue;
3208 }
3209 int topPrio = source_priority(topPrioClient->source());
3210 if (topPrio < source_priority(attributes.source)
3211 || (topPrio == source_priority(attributes.source)
3212 && !desc->isPreemptor())) {
3213 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3214 if (closeRank < leastCloseRank) {
3215 leastCloseRank = closeRank;
3216 closeCandidate = desc;
3217 }
3218 }
3219 }
3220
3221 if (closeCandidate != nullptr) {
3222 closeInput(closeCandidate->mIoHandle);
3223 // Mark the new input as being issued from a preemption
3224 // so that is will not be preempted later
3225 isPreemptor = true;
3226 } else {
3227 // Then pick the best reusable input (There is always one)
3228 // The order of preference is:
3229 // 1) active inputs with same use case as the new client
3230 // 2) inactive inputs with same use case
3231 // 3) active inputs with different use cases
3232 // 4) inactive inputs with different use cases
3233 sp<AudioInputDescriptor> reuseCandidate;
3234 int leastReuseRank = INT_MAX;
3235 static const int sReuseDifferentUseCase = 0x100;
3236
3237 for (size_t i = 0; i < mInputs.size(); i++) {
3238 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3239 if (desc->mProfile != profile) {
3240 continue;
3241 }
3242 int reuseRank = sReuseDifferentUseCase;
3243 for (const auto& client: desc->getClientIterable()) {
3244 if (client->source() == attributes.source) {
3245 reuseRank = 0;
3246 break;
3247 }
3248 }
3249 reuseRank += desc->isActive() ? 0 : 1;
3250 if (reuseRank < leastReuseRank) {
3251 leastReuseRank = reuseRank;
3252 reuseCandidate = desc;
3253 }
3254 }
3255 return reuseCandidate->mIoHandle;
3256 }
3257 } else { // fix_input_sharing_logic()
3258 for (size_t i = 0; i < mInputs.size(); ) {
3259 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3260 if (desc->mProfile != profile) {
3261 i++;
3262 continue;
3263 }
3264 // if sound trigger, reuse input if used by other sound trigger on same session
3265 // else
3266 // reuse input if active client app is not in IDLE state
3267 //
3268 RecordClientVector clients = desc->clientsList();
3269 bool doClose = false;
3270 for (const auto& client : clients) {
3271 if (isSoundTrigger != client->isSoundTrigger()) {
3272 continue;
3273 }
3274 if (client->isSoundTrigger()) {
3275 if (session == client->session()) {
3276 return desc->mIoHandle;
3277 }
3278 continue;
3279 }
3280 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003281 return desc->mIoHandle;
3282 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003283 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003284 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003285 if (doClose) {
3286 closeInput(desc->mIoHandle);
3287 } else {
3288 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003289 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003290 }
3291 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003292 }
3293
Eric Laurentc71b11b2024-06-03 12:54:53 +00003294 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3295 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003296
Eric Laurentfe231122017-11-17 17:48:06 -08003297 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3298 lConfig.sample_rate = profileSamplingRate;
3299 lConfig.channel_mask = profileChannelMask;
3300 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003301
François Gaffie11d30102018-11-02 16:09:09 +01003302 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003303
3304 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003305 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003306 (profileSamplingRate != lConfig.sample_rate) ||
3307 !audio_formats_match(profileFormat, lConfig.format) ||
3308 (profileChannelMask != lConfig.channel_mask)) {
3309 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003310 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003311 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003312 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003313 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003314 }
Eric Laurent599c7582015-12-07 18:05:55 -08003315 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003316 }
3317
Eric Laurentc722f302014-12-10 11:21:49 -08003318 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003319
Eric Laurent599c7582015-12-07 18:05:55 -08003320 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003321 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003322
Eric Laurent599c7582015-12-07 18:05:55 -08003323 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003324}
3325
Eric Laurent4eb58f12018-12-07 16:41:02 -08003326status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003327{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003328 ALOGV("%s portId %d", __FUNCTION__, portId);
3329
3330 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3331 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003333 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003334 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003335 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003336 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003337 if (client->active()) {
3338 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3339 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003340 }
3341
Eric Laurent8f42ea12018-08-08 09:08:25 -07003342 audio_session_t session = client->session();
3343
Eric Laurent4eb58f12018-12-07 16:41:02 -08003344 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003345
Eric Laurent4eb58f12018-12-07 16:41:02 -08003346 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003347
Eric Laurent4eb58f12018-12-07 16:41:02 -08003348 status_t status = inputDesc->start();
3349 if (status != NO_ERROR) {
3350 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003351 }
Eric Laurente552edb2014-03-10 17:42:56 -07003352
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003353 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003354 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003355 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003356
Eric Laurent8f42ea12018-08-08 09:08:25 -07003357 // indicate active capture to sound trigger service if starting capture from a mic on
3358 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003359 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003360 if (device != nullptr) {
3361 status = setInputDevice(input, device, true /* force */);
3362 } else {
3363 ALOGW("%s no new input device can be found for descriptor %d",
3364 __FUNCTION__, inputDesc->getId());
3365 status = BAD_VALUE;
3366 }
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003368 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003369 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003371 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003372 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3373 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003374 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003375 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003376
François Gaffie11d30102018-11-02 16:09:09 +01003377 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3378 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003380 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003381 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003382
Eric Laurent8f42ea12018-08-08 09:08:25 -07003383 // automatically enable the remote submix output when input is started if not
3384 // used by a policy mix of type MIX_TYPE_RECORDERS
3385 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003386 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003388 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003390 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3391 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003392 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003393 if (address != "") {
3394 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3395 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003396 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003397 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003398 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003399 } else if (status != NO_ERROR) {
3400 // Restore client activity state.
3401 inputDesc->setClientActive(client, false);
3402 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003403 }
3404
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003405 ALOGV("%s input %d source = %d status = %d exit",
3406 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003407
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003408 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003409}
3410
Eric Laurent8fc147b2018-07-22 19:13:55 -07003411status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003412{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003413 ALOGV("%s portId %d", __FUNCTION__, portId);
3414
3415 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3416 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003417 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003418 return BAD_VALUE;
3419 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003420 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003421 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003422 if (!client->active()) {
3423 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003424 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003425 }
Carter Hsue6139d52021-07-08 10:30:20 +08003426 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003427 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003428
Eric Laurent8f42ea12018-08-08 09:08:25 -07003429 inputDesc->stop();
3430 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003431 auto current_source = inputDesc->source();
3432 setInputDevice(input, getNewInputDevice(inputDesc),
3433 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003434 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003435 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003436 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003437 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003438 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3439 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003440 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003441 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003442
3443 // automatically disable the remote submix output when input is stopped if not
3444 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003445 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003446 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003447 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003448 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003449 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3450 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003451 }
3452 if (address != "") {
3453 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3454 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003455 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003456 }
3457 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003458 resetInputDevice(input);
3459
3460 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3461 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003462 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3463 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003464 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003465 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003466 }
3467 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003468 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003469 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003470}
3471
Eric Laurent8fc147b2018-07-22 19:13:55 -07003472void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003473{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003474 ALOGV("%s portId %d", __FUNCTION__, portId);
3475
3476 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3477 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003478 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003479 return;
3480 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003481 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003482 audio_io_handle_t input = inputDesc->mIoHandle;
3483
Eric Laurent8f42ea12018-08-08 09:08:25 -07003484 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003485
Andy Hung39efb7a2018-09-26 15:39:28 -07003486 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003487
3488 // If no more clients are present in this session, park effects to an orphan chain
3489 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3490 if (clientsOnSession.size() == 0) {
3491 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3492 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003493 if (inputDesc->getClientCount() > 0) {
3494 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003495 return;
3496 }
3497
Eric Laurent05b90f82014-08-27 15:32:29 -07003498 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003499 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003500 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003501}
3502
Eric Laurent8f42ea12018-08-08 09:08:25 -07003503void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003504{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003505 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003506
3507 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003508 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003509 }
3510}
3511
Eric Laurent8f42ea12018-08-08 09:08:25 -07003512void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3513{
3514 stopInput(portId);
3515 releaseInput(portId);
3516}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003517
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003518bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3519 if (input->clientsList().size() == 0
3520 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3521 return true;
3522 }
3523 for (const auto& client : input->clientsList()) {
3524 sp<DeviceDescriptor> device =
3525 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3526 client->session());
3527 if (!input->supportedDevices().contains(device)) {
3528 return true;
3529 }
3530 }
3531 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3532 return false;
3533}
3534
Eric Laurent0dd51852019-04-19 18:18:58 -07003535void AudioPolicyManager::checkCloseInputs() {
3536 // After connecting or disconnecting an input device, close input if:
3537 // - it has no client (was just opened to check profile) OR
3538 // - none of its supported devices are connected anymore OR
3539 // - one of its clients cannot be routed to one of its supported
3540 // devices anymore. Otherwise update device selection
3541 std::vector<audio_io_handle_t> inputsToClose;
3542 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003543 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003544 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003545 }
3546 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003547 for (const audio_io_handle_t handle : inputsToClose) {
3548 ALOGV("%s closing input %d", __func__, handle);
3549 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003550 }
Eric Laurentd4692962014-05-05 18:13:44 -07003551}
3552
Vlad Popa87e0e582024-05-20 18:49:20 -07003553status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3554 const char *address __unused,
3555 bool enabled,
3556 audio_stream_type_t streamToDriveAbs)
3557{
Vlad Popaa536eb32024-07-18 16:00:35 -07003558 if (!enabled) {
3559 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3560 return NO_ERROR;
3561 }
3562
Vlad Popa87e0e582024-05-20 18:49:20 -07003563 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3564 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3565 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3566 toString(streamToDriveAbs).c_str());
3567 return BAD_VALUE;
3568 }
3569
Vlad Popaa536eb32024-07-18 16:00:35 -07003570 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003571 return NO_ERROR;
3572}
3573
François Gaffie251c7f02018-11-07 10:41:08 +01003574void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003575{
3576 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003577 if (indexMin < 0 || indexMax < 0) {
3578 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3579 return;
3580 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003581 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003582
3583 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003584 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3585 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003586 continue;
3587 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003588 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003589 }
Eric Laurente552edb2014-03-10 17:42:56 -07003590}
3591
Eric Laurente0720872014-03-11 09:30:41 -07003592status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003593 int index,
3594 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003595{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003596 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003597 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3598 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3599 return NO_ERROR;
3600 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303601 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3602 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003603 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003604}
3605
Eric Laurente0720872014-03-11 09:30:41 -07003606status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003607 int *index,
3608 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003609{
François Gaffiec005e562018-11-06 15:04:49 +01003610 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3611 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003612 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003613 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003614 deviceTypes = mEngine->getOutputDevicesForStream(
3615 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003616 }
jiabin9a3361e2019-10-01 09:38:30 -07003617 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003618}
3619
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003620status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003621 int index,
3622 audio_devices_t device)
3623{
3624 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003625 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3626 if (group == VOLUME_GROUP_NONE) {
3627 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003628 return BAD_VALUE;
3629 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003630 ALOGV("%s: group %d matching with %s index %d",
3631 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003632 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003633 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003634 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003635 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3636 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3637 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3638 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3640
3641 status = setVolumeCurveIndex(index, device, curves);
3642 if (status != NO_ERROR) {
3643 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3644 return status;
3645 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003646
jiabin9a3361e2019-10-01 09:38:30 -07003647 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003648 auto curCurvAttrs = curves.getAttributes();
3649 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3650 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003651 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003652 } else if (!curves.getStreamTypes().empty()) {
3653 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003654 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003655 } else {
3656 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3657 return BAD_VALUE;
3658 }
jiabin9a3361e2019-10-01 09:38:30 -07003659 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3660 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003661
François Gaffiecfe17322018-11-07 13:41:29 +01003662 // update volume on all outputs and streams matching the following:
3663 // - The requested stream (or a stream matching for volume control) is active on the output
3664 // - The device (or devices) selected by the engine for this stream includes
3665 // the requested device
3666 // - For non default requested device, currently selected device on the output is either the
3667 // requested device or one of the devices selected by the engine for this stream
3668 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3669 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003670 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003671 for (size_t i = 0; i < mOutputs.size(); i++) {
3672 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003673 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003674
jiabin9a3361e2019-10-01 09:38:30 -07003675 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3676 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003677 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003678
3679 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003680 continue;
3681 }
3682 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3683 curDevices.find(device) == curDevices.end()) {
3684 continue;
3685 }
3686 bool applyVolume = false;
3687 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3688 curSrcDevices.insert(device);
3689 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003690 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3691 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003692 } else {
3693 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3694 }
3695 if (!applyVolume) {
3696 continue; // next output
3697 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003698 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3699 // If a higher priority strategy is active, and the output is routed to a device with a
3700 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003701 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003702 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003703 // If the volume source is active with higher priority source, ensure at least Sw Muted
3704 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003705 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3706 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3707 false /*preferredDevice*/);
3708 if (activeClients.empty()) {
3709 continue;
3710 }
3711 bool isPreempted = false;
3712 bool isHigherPriority = productStrategy < strategy;
3713 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003714 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003715 ALOGV("%s: Strategy=%d (\nrequester:\n"
3716 " group %d, volumeGroup=%d attributes=%s)\n"
3717 " higher priority source active:\n"
3718 " volumeGroup=%d attributes=%s) \n"
3719 " on output %zu, bailing out", __func__, productStrategy,
3720 group, group, toString(attributes).c_str(),
3721 client->volumeSource(), toString(client->attributes()).c_str(), i);
3722 applyVolume = false;
3723 isPreempted = true;
3724 break;
3725 }
3726 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003727 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003728 applyVolume = true;
3729 }
3730 }
3731 if (isPreempted || applyVolume) {
3732 break;
3733 }
3734 }
3735 if (!applyVolume) {
3736 continue; // next output
3737 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003738 }
François Gaffieed91f582020-01-31 10:35:37 +01003739 //FIXME: workaround for truncated touch sounds
3740 // delayed volume change for system stream to be removed when the problem is
3741 // handled by system UI
3742 status_t volStatus = checkAndSetVolume(
3743 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003744 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003745 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3746 if (volStatus != NO_ERROR) {
3747 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003748 }
3749 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003750
3751 // update voice volume if the an active call route exists
3752 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3753 && (curSrcDevices.find(
3754 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3755 != curSrcDevices.end())) {
3756 bool isVoiceVolSrc;
3757 bool isBtScoVolSrc;
3758 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3759 isVoiceVolSrc, isBtScoVolSrc, __func__)
3760 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003761 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3762 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3763 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003764 }
3765 }
3766
François Gaffiecfe17322018-11-07 13:41:29 +01003767 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3768 return status;
3769}
3770
François Gaffieaaac0fd2018-11-22 17:56:39 +01003771status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003772 audio_devices_t device,
3773 IVolumeCurves &volumeCurves)
3774{
3775 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3776 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003777 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3778 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003779 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303780 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3781 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003782 return BAD_VALUE;
3783 }
3784 if (!audio_is_output_device(device)) {
3785 return BAD_VALUE;
3786 }
3787
3788 // Force max volume if stream cannot be muted
3789 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3790
François Gaffieaaac0fd2018-11-22 17:56:39 +01003791 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003792 volumeCurves.addCurrentVolumeIndex(device, index);
3793 return NO_ERROR;
3794}
3795
3796status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3797 int &index,
3798 audio_devices_t device)
3799{
3800 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3801 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003802 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003803 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003804 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003805 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003806 }
jiabin9a3361e2019-10-01 09:38:30 -07003807 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003808}
3809
3810status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3811 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003812 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003813{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003814 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003815 return BAD_VALUE;
3816 }
jiabin9a3361e2019-10-01 09:38:30 -07003817 index = curves.getVolumeIndex(deviceTypes);
3818 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003819 return NO_ERROR;
3820}
3821
3822status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3823 int &index)
3824{
3825 index = getVolumeCurves(attr).getVolumeIndexMin();
3826 return NO_ERROR;
3827}
3828
3829status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3830 int &index)
3831{
3832 index = getVolumeCurves(attr).getVolumeIndexMax();
3833 return NO_ERROR;
3834}
3835
Eric Laurent36829f92017-04-07 19:04:42 -07003836audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003837{
3838 // select one output among several suitable for global effects.
3839 // The priority is as follows:
3840 // 1: An offloaded output. If the effect ends up not being offloadable,
3841 // AudioFlinger will invalidate the track and the offloaded output
3842 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003843 // 2: Spatializer output if the stereo spatializer feature enabled
3844 // 3: A deep buffer output
3845 // 4: The primary output
3846 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003847
François Gaffiec005e562018-11-06 15:04:49 +01003848 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3849 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003850 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003851
Eric Laurent36829f92017-04-07 19:04:42 -07003852 if (outputs.size() == 0) {
3853 return AUDIO_IO_HANDLE_NONE;
3854 }
Eric Laurente552edb2014-03-10 17:42:56 -07003855
Eric Laurent36829f92017-04-07 19:04:42 -07003856 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3857 bool activeOnly = true;
3858
3859 while (output == AUDIO_IO_HANDLE_NONE) {
3860 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003861 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003862 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3863 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3864
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003865 for (audio_io_handle_t outputLoop : outputs) {
3866 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003867 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003868 continue;
3869 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003870 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003871 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003872 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003873 outputOffloaded = outputLoop;
3874 }
3875 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3876 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3877 outputSpatializer = outputLoop;
3878 }
Eric Laurent36829f92017-04-07 19:04:42 -07003879 }
3880 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003881 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003882 }
3883 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003884 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003885 }
3886 }
3887 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3888 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003889 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3890 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003891 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3892 output = outputDeepBuffer;
3893 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3894 output = outputPrimary;
3895 } else {
3896 output = outputs[0];
3897 }
3898 activeOnly = false;
3899 }
3900
3901 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003902 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3903 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003904 mMusicEffectOutput = output;
3905 }
3906
3907 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003908 return output;
3909}
3910
Eric Laurent36829f92017-04-07 19:04:42 -07003911audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3912{
3913 return selectOutputForMusicEffects();
3914}
3915
Eric Laurente0720872014-03-11 09:30:41 -07003916status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003917 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003918 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003919 int session,
3920 int id)
3921{
Shunkai Yao29d10572024-03-19 04:31:47 +00003922 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003923 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003924 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003925 index = mInputs.indexOfKey(io);
3926 if (index < 0) {
3927 ALOGW("registerEffect() unknown io %d", io);
3928 return INVALID_OPERATION;
3929 }
Eric Laurente552edb2014-03-10 17:42:56 -07003930 }
3931 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003932 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3933 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3934 || strategy == PRODUCT_STRATEGY_NONE));
3935 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003936}
3937
Eric Laurentc241b0d2018-11-28 09:08:49 -08003938status_t AudioPolicyManager::unregisterEffect(int id)
3939{
3940 if (mEffects.getEffect(id) == nullptr) {
3941 return INVALID_OPERATION;
3942 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003943 if (mEffects.isEffectEnabled(id)) {
3944 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3945 setEffectEnabled(id, false);
3946 }
3947 return mEffects.unregisterEffect(id);
3948}
3949
3950status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3951{
3952 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3953 if (effect == nullptr) {
3954 return INVALID_OPERATION;
3955 }
3956
3957 status_t status = mEffects.setEffectEnabled(id, enabled);
3958 if (status == NO_ERROR) {
3959 mInputs.trackEffectEnabled(effect, enabled);
3960 }
3961 return status;
3962}
3963
Eric Laurent6c796322019-04-09 14:13:17 -07003964
3965status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3966{
3967 mEffects.moveEffects(ids, io);
3968 return NO_ERROR;
3969}
3970
Eric Laurentc75307b2015-03-17 15:29:32 -07003971bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3972{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003973 auto vs = toVolumeSource(stream, false);
3974 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003975}
3976
3977bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3978{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003979 auto vs = toVolumeSource(stream, false);
3980 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003981}
3982
Eric Laurente0720872014-03-11 09:30:41 -07003983bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003984{
3985 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003986 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003987 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003988 return true;
3989 }
3990 }
3991 return false;
3992}
3993
Eric Laurent275e8e92014-11-30 15:14:47 -08003994// Register a list of custom mixes with their attributes and format.
3995// When a mix is registered, corresponding input and output profiles are
3996// added to the remote submix hw module. The profile contains only the
3997// parameters (sampling rate, format...) specified by the mix.
3998// The corresponding input remote submix device is also connected.
3999//
4000// When a remote submix device is connected, the address is checked to select the
4001// appropriate profile and the corresponding input or output stream is opened.
4002//
4003// When capture starts, getInputForAttr() will:
4004// - 1 look for a mix matching the address passed in attribtutes tags if any
4005// - 2 if none found, getDeviceForInputSource() will:
4006// - 2.1 look for a mix matching the attributes source
4007// - 2.2 if none found, default to device selection by policy rules
4008// At this time, the corresponding output remote submix device is also connected
4009// and active playback use cases can be transferred to this mix if needed when reconnecting
4010// after AudioTracks are invalidated
4011//
4012// When playback starts, getOutputForAttr() will:
4013// - 1 look for a mix matching the address passed in attribtutes tags if any
4014// - 2 if none found, look for a mix matching the attributes usage
4015// - 3 if none found, default to device and output selection by policy rules.
4016
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004017status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004018{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004019 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4020 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004021 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004022 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004023 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004024 // examine each mix's route type
4025 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004026 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004027 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4028 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4029 ALOGE("Unsupported Policy Mix %zu of %zu: "
4030 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4031 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004032 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004033 break;
4034 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004035 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4036 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004037 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004038 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4039 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004040 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004041 rSubmixModule = mHwModules.getModuleFromName(
4042 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4043 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004044 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004045 i);
4046 res = INVALID_OPERATION;
4047 break;
4048 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004049 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004050
Eric Laurent97ac8712018-07-27 18:59:02 -07004051 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004052 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004053 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004054 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004055 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4056 } else {
4057 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4058 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004059 }
François Gaffie036e1e92015-03-19 10:16:24 +01004060
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004061 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004062 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004063 res = INVALID_OPERATION;
4064 break;
4065 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004066 audio_config_t outputConfig = mix.mFormat;
4067 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004068 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4069 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004070 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4071 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004072 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004073 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4074 audio_is_linear_pcm(outputConfig.format)
4075 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004076 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004077 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4078 audio_is_linear_pcm(inputConfig.format)
4079 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004080
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004081 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004082 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004083 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004084 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004085 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004086 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004087 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004088 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4089 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004090 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004091 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004092 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004093
4094 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4095 mix.mDeviceType, mix.mDeviceAddress,
4096 String8(), AUDIO_FORMAT_DEFAULT);
4097 if (device == nullptr) {
4098 res = INVALID_OPERATION;
4099 break;
4100 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004101
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004102 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004103 // First try to find an already opened output supporting the device
4104 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004105 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004106
Eric Laurentc529cf62020-04-17 18:19:10 -07004107 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004108 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004109 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004110 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004111 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004112 } else {
4113 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004114 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004115 }
4116 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004117 // If no output found, try to find a direct output profile supporting the device
4118 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4119 sp<HwModule> module = mHwModules[i];
4120 for (size_t j = 0;
4121 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4122 j++) {
4123 sp<IOProfile> profile = module->getOutputProfiles()[j];
4124 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4125 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4126 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004127 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004128 res = INVALID_OPERATION;
4129 } else {
4130 foundOutput = true;
4131 }
4132 }
4133 }
4134 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004135 if (res != NO_ERROR) {
4136 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004137 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004138 res = INVALID_OPERATION;
4139 break;
4140 } else if (!foundOutput) {
4141 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004142 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004143 res = INVALID_OPERATION;
4144 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004145 } else {
4146 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004147 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004148 }
Eric Laurentc722f302014-12-10 11:21:49 -08004149 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004150 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004151 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004152 if (audio_flags::audio_mix_ownership()) {
4153 // Only unregister mixes that were actually registered to not accidentally unregister
4154 // mixes that already existed previously.
4155 unregisterPolicyMixes(registeredMixes);
4156 registeredMixes.clear();
4157 } else {
4158 unregisterPolicyMixes(mixes);
4159 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004160 } else if (checkOutputs) {
4161 checkForDeviceAndOutputChanges();
4162 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004163 }
4164 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004165}
4166
4167status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4168{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004169 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004170 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004171 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004172 sp<HwModule> rSubmixModule;
4173 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004174 for (const auto& mix : mixes) {
4175 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004176
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004177 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004178 rSubmixModule = mHwModules.getModuleFromName(
4179 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4180 if (rSubmixModule == 0) {
4181 res = INVALID_OPERATION;
4182 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004183 }
4184 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004185
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004186 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004187
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004188 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004189 res = INVALID_OPERATION;
4190 continue;
4191 }
4192
Marvin Ramin0783e202024-03-05 12:45:50 +01004193 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004194 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004195 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4196 status_t currentRes =
4197 setDeviceConnectionStateInt(device,
4198 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4199 address.c_str(),
4200 "remote-submix",
4201 AUDIO_FORMAT_DEFAULT);
4202 if (!audio_flags::audio_mix_ownership()) {
4203 res = currentRes;
4204 }
4205 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004206 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004207 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004208 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004209 }
4210 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004211 }
jiabin5740f082019-08-19 15:08:30 -07004212 rSubmixModule->removeOutputProfile(address.c_str());
4213 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004214
Kevin Rocard153f92d2018-12-18 18:33:28 -08004215 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004216 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004217 res = INVALID_OPERATION;
4218 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004219 } else {
4220 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004221 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004222 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004223 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004224
4225 if (res == NO_ERROR && checkOutputs) {
4226 checkForDeviceAndOutputChanges();
4227 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004228 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004229 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004230}
4231
Marvin Raminbdefaf02023-11-01 09:10:32 +01004232status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4233 if (!audio_flags::audio_mix_test_api()) {
4234 return INVALID_OPERATION;
4235 }
4236
4237 _aidl_return.clear();
4238 _aidl_return.reserve(mPolicyMixes.size());
4239 for (const auto &policyMix: mPolicyMixes) {
4240 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4241 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4242 policyMix->mCbFlags);
4243 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004244 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004245 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004246 }
4247
Vlad Popaa5d73f32024-03-08 16:05:38 -08004248 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004249 return OK;
4250}
4251
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004252status_t AudioPolicyManager::updatePolicyMix(
4253 const AudioMix& mix,
4254 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4255 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4256 if (res == NO_ERROR) {
4257 checkForDeviceAndOutputChanges();
4258 updateCallAndOutputRouting();
4259 }
4260 return res;
4261}
4262
Mikhail Naganov100f0122018-11-29 11:22:16 -08004263void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4264{
4265 size_t i = 0;
4266 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4267 for (const auto& fmt : mManualSurroundFormats) {
4268 if (i++ != 0) dst->append(", ");
4269 std::string sfmt;
4270 FormatConverter::toString(fmt, sfmt);
4271 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4272 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4273 }
4274}
4275
Eric Laurentc529cf62020-04-17 18:19:10 -07004276// Returns true if all devices types match the predicate and are supported by one HW module
4277bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004278 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004279 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004280 const char *context,
4281 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004282 for (size_t i = 0; i < devices.size(); i++) {
4283 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004284 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004285 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004286 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004287 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004288 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004289 return false;
4290 }
4291 }
4292 return true;
4293}
4294
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004295void AudioPolicyManager::changeOutputDevicesMuteState(
4296 const AudioDeviceTypeAddrVector& devices) {
4297 ALOGVV("%s() num devices %zu", __func__, devices.size());
4298
4299 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4300 getSoftwareOutputsForDevices(devices);
4301
4302 for (size_t i = 0; i < outputs.size(); i++) {
4303 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4304 DeviceVector prevDevices = outputDesc->devices();
4305 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4306 }
4307}
4308
4309std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4310 const AudioDeviceTypeAddrVector& devices) const
4311{
4312 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4313 DeviceVector deviceDescriptors;
4314 for (size_t j = 0; j < devices.size(); j++) {
4315 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4316 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4317 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4318 ALOGE("%s: device type %#x address %s not supported or not an output device",
4319 __func__, devices[j].mType, devices[j].getAddress());
4320 continue;
4321 }
4322 deviceDescriptors.add(desc);
4323 }
4324 for (size_t i = 0; i < mOutputs.size(); i++) {
4325 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4326 continue;
4327 }
4328 outputs.push_back(mOutputs.valueAt(i));
4329 }
4330 return outputs;
4331}
4332
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004333status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004334 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004335 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004336 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4337 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004338 }
4339 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004340 if (res != NO_ERROR) {
4341 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4342 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004343 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004344
4345 checkForDeviceAndOutputChanges();
4346 updateCallAndOutputRouting();
4347
4348 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004349}
4350
4351status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4352 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004353 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4354 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004355 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004356 __FUNCTION__, uid);
4357 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004358 }
4359
Eric Laurentc529cf62020-04-17 18:19:10 -07004360 checkForDeviceAndOutputChanges();
4361 updateCallAndOutputRouting();
4362
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004363 return res;
4364}
4365
Eric Laurent2517af32020-11-25 15:31:27 +01004366
jiabin0a488932020-08-07 17:32:40 -07004367status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4368 device_role_t role,
4369 const AudioDeviceTypeAddrVector &devices) {
4370 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4371 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004372
Eric Laurentc529cf62020-04-17 18:19:10 -07004373 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004374 return BAD_VALUE;
4375 }
jiabin0a488932020-08-07 17:32:40 -07004376 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004377 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004378 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4379 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004380 return status;
4381 }
4382
4383 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004384
4385 bool forceVolumeReeval = false;
4386 // FIXME: workaround for truncated touch sounds
4387 // to be removed when the problem is handled by system UI
4388 uint32_t delayMs = 0;
4389 if (strategy == mCommunnicationStrategy) {
4390 forceVolumeReeval = true;
4391 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4392 updateInputRouting();
4393 }
4394 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004395
4396 return NO_ERROR;
4397}
4398
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004399void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4400 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004401{
4402 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004403 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004404 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004405 // Only apply special touch sound delay once
4406 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004407 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004408 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004409 for (size_t i = 0; i < mOutputs.size(); i++) {
4410 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4411 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004412 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4413 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004414 // As done in setDeviceConnectionState, we could also fix default device issue by
4415 // preventing the force re-routing in case of default dev that distinguishes on address.
4416 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004417 bool newDevicesNotEmpty = !newDevices.isEmpty();
4418 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4419 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004420 // If the device is using preferred mixer attributes, the output need to reopen
4421 // with default configuration when the new selected devices are different from
4422 // current routing devices.
4423 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4424 continue;
4425 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304426
jiabin2361ed82024-09-20 17:36:31 +00004427 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4428 newDevicesNotEmpty /*force*/, delayMs,
4429 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4430 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004431 // Only apply special touch sound delay once
4432 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004433 }
4434 if (forceVolumeReeval && !newDevices.isEmpty()) {
4435 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4436 }
4437 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004438 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004439 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004440}
4441
Eric Laurent2517af32020-11-25 15:31:27 +01004442void AudioPolicyManager::updateInputRouting() {
4443 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304444 // Skip for hotword recording as the input device switch
4445 // is handled within sound trigger HAL
4446 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4447 continue;
4448 }
Eric Laurent2517af32020-11-25 15:31:27 +01004449 auto newDevice = getNewInputDevice(activeDesc);
4450 // Force new input selection if the new device can not be reached via current input
4451 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4452 setInputDevice(activeDesc->mIoHandle, newDevice);
4453 } else {
4454 closeInput(activeDesc->mIoHandle);
4455 }
4456 }
4457}
4458
Paul Wang5d7cdb52022-11-22 09:45:06 +00004459status_t
4460AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4461 device_role_t role,
4462 const AudioDeviceTypeAddrVector &devices) {
4463 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4464 dumpAudioDeviceTypeAddrVector(devices).c_str());
4465
Eric Laurent78fedbf2023-03-09 14:40:44 +01004466 if (!areAllDevicesSupported(
4467 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004468 return BAD_VALUE;
4469 }
4470 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4471 if (status != NO_ERROR) {
4472 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4473 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4474 return status;
4475 }
4476
4477 checkForDeviceAndOutputChanges();
4478
4479 bool forceVolumeReeval = false;
4480 // TODO(b/263479999): workaround for truncated touch sounds
4481 // to be removed when the problem is handled by system UI
4482 uint32_t delayMs = 0;
4483 if (strategy == mCommunnicationStrategy) {
4484 forceVolumeReeval = true;
4485 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4486 updateInputRouting();
4487 }
4488 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4489
4490 return NO_ERROR;
4491}
4492
4493status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4494 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004495{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004496 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004497
Paul Wang5d7cdb52022-11-22 09:45:06 +00004498 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004499 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004500 ALOGW_IF(status != NAME_NOT_FOUND,
4501 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004502 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004503 return status;
4504 }
4505
4506 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004507
4508 bool forceVolumeReeval = false;
4509 // FIXME: workaround for truncated touch sounds
4510 // to be removed when the problem is handled by system UI
4511 uint32_t delayMs = 0;
4512 if (strategy == mCommunnicationStrategy) {
4513 forceVolumeReeval = true;
4514 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4515 updateInputRouting();
4516 }
4517 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004518
4519 return NO_ERROR;
4520}
4521
jiabin0a488932020-08-07 17:32:40 -07004522status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4523 device_role_t role,
4524 AudioDeviceTypeAddrVector &devices) {
4525 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004526}
4527
Jiabin Huang3b98d322020-09-03 17:54:16 +00004528status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4529 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4530 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4531 dumpAudioDeviceTypeAddrVector(devices).c_str());
4532
Mikhail Naganov55773032020-10-01 15:08:13 -07004533 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004534 return BAD_VALUE;
4535 }
4536 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4537 ALOGW_IF(status != NO_ERROR,
4538 "Engine could not set preferred devices %s for audio source %d role %d",
4539 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4540
Wenyu Zhang47655d22024-10-01 12:24:53 +00004541 if (status == NO_ERROR) {
4542 updateInputRouting();
4543 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004544 return status;
4545}
4546
4547status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4548 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4549 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4550 dumpAudioDeviceTypeAddrVector(devices).c_str());
4551
Mikhail Naganov55773032020-10-01 15:08:13 -07004552 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004553 return BAD_VALUE;
4554 }
4555 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4556 ALOGW_IF(status != NO_ERROR,
4557 "Engine could not add preferred devices %s for audio source %d role %d",
4558 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4559
Eric Laurent2517af32020-11-25 15:31:27 +01004560 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004561 return status;
4562}
4563
4564status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4565 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4566{
4567 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4568 dumpAudioDeviceTypeAddrVector(devices).c_str());
4569
Eric Laurent78fedbf2023-03-09 14:40:44 +01004570 if (!areAllDevicesSupported(
4571 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004572 return BAD_VALUE;
4573 }
4574
4575 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4576 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004577 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004578 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004579 if (status == NO_ERROR) {
4580 updateInputRouting();
4581 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004582 return status;
4583}
4584
4585status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4586 device_role_t role) {
4587 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4588
4589 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004590 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004591 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004592 if (status == NO_ERROR) {
4593 updateInputRouting();
4594 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004595 return status;
4596}
4597
4598status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4599 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4600 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4601}
4602
Oscar Azucena90e77632019-11-27 17:12:28 -08004603status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004604 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004605 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004606 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4607 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004608 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004609 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4610 if (status != NO_ERROR) {
4611 ALOGE("%s() could not set device affinity for userId %d",
4612 __FUNCTION__, userId);
4613 return status;
4614 }
4615
4616 // reevaluate outputs for all devices
4617 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004618 changeOutputDevicesMuteState(devices);
4619 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4620 true /* skipDelays */);
4621 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004622
4623 return NO_ERROR;
4624}
4625
4626status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004627 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004628 AudioDeviceTypeAddrVector devices;
4629 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004630 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4631 if (status != NO_ERROR) {
4632 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4633 __FUNCTION__, userId);
4634 return status;
4635 }
4636
4637 // reevaluate outputs for all devices
4638 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004639 changeOutputDevicesMuteState(devices);
4640 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4641 true /* skipDelays */);
4642 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004643
4644 return NO_ERROR;
4645}
4646
Andy Hungc29d82b2018-10-05 12:23:17 -07004647void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004648{
Andy Hungc29d82b2018-10-05 12:23:17 -07004649 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004650 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004651 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004652 std::string stateLiteral;
4653 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004654 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004655 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4656 "communications", "media", "record", "dock", "system",
4657 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4658 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4659 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004660 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4661 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4662 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4663 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4664 dst->append(" (MANUAL: ");
4665 dumpManualSurroundFormats(dst);
4666 dst->append(")");
4667 }
4668 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004669 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004670 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4671 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004672 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004673 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004674
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004675 dst->append("\n");
4676 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4677 dst->append("\n");
4678 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004679 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004680 mOutputs.dump(dst);
4681 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004682 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004683 mAudioPatches.dump(dst);
4684 mPolicyMixes.dump(dst);
4685 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004686
Kevin Rocardb99cc752019-03-21 20:52:24 -07004687 dst->appendFormat(" AllowedCapturePolicies:\n");
4688 for (auto& policy : mAllowedCapturePolicies) {
4689 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4690 }
4691
jiabina84c3d32022-12-02 18:59:55 +00004692 dst->appendFormat(" Preferred mixer audio configuration:\n");
4693 for (const auto it : mPreferredMixerAttrInfos) {
4694 dst->appendFormat(" - device port id: %d\n", it.first);
4695 for (const auto preferredMixerInfoIt : it.second) {
4696 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4697 preferredMixerInfoIt.second->dump(dst);
4698 }
4699 }
4700
François Gaffiec005e562018-11-06 15:04:49 +01004701 dst->appendFormat("\nPolicy Engine dump:\n");
4702 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004703
4704 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4705 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4706 dst->appendFormat(" - device type: %s, driving stream %d\n",
4707 dumpDeviceTypes({it.first}).c_str(),
4708 mEngine->getVolumeGroupForAttributes(it.second));
4709 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004710}
4711
4712status_t AudioPolicyManager::dump(int fd)
4713{
4714 String8 result;
4715 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004716 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004717 return NO_ERROR;
4718}
4719
Kevin Rocardb99cc752019-03-21 20:52:24 -07004720status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4721{
4722 mAllowedCapturePolicies[uid] = capturePolicy;
4723 return NO_ERROR;
4724}
4725
Eric Laurente552edb2014-03-10 17:42:56 -07004726// This function checks for the parameters which can be offloaded.
4727// This can be enhanced depending on the capability of the DSP and policy
4728// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004729audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004730{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004731 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004732 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004733 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004734 offloadInfo.format,
4735 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4736 offloadInfo.has_video);
4737
jiabin2b9d5a12021-12-10 01:06:29 +00004738 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004739 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004740 }
4741
4742 // See if there is a profile to support this.
4743 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004744 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004745 offloadInfo.sample_rate,
4746 offloadInfo.format,
4747 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004748 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4749 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004750 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4751 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4752 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004753 if (profile == nullptr) {
4754 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4755 }
4756 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4757 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4758 }
4759 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004760}
4761
Michael Chana94fbb22018-04-24 14:31:19 +10004762bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4763 const audio_attributes_t& attributes) {
4764 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004765 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004766 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4767 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004768 config.sample_rate,
4769 config.format,
4770 config.channel_mask,
4771 output_flags,
4772 true /* directOnly */);
4773 ALOGV("%s() profile %sfound with name: %s, "
4774 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4775 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004776 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004777 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004778
4779 // also try the MSD module if compatible profile not found
4780 if (profile == nullptr) {
4781 profile = getMsdProfileForOutput(outputDevices,
4782 config.sample_rate,
4783 config.format,
4784 config.channel_mask,
4785 output_flags,
4786 true /* directOnly */);
4787 ALOGV("%s() MSD profile %sfound with name: %s, "
4788 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4789 __FUNCTION__, profile != 0 ? "" : "NOT ",
4790 (profile != 0 ? profile->getTagName().c_str() : "null"),
4791 config.sample_rate, config.format, config.channel_mask, output_flags);
4792 }
4793 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004794}
4795
jiabin2b9d5a12021-12-10 01:06:29 +00004796bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4797 bool durationIgnored) {
4798 if (mMasterMono) {
4799 return false; // no offloading if mono is set.
4800 }
4801
4802 // Check if offload has been disabled
4803 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4804 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4805 return false;
4806 }
4807
4808 // Check if stream type is music, then only allow offload as of now.
4809 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4810 {
4811 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4812 return false;
4813 }
4814
4815 //TODO: enable audio offloading with video when ready
4816 const bool allowOffloadWithVideo =
4817 property_get_bool("audio.offload.video", false /* default_value */);
4818 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4819 ALOGV("%s: has_video == true, returning false", __func__);
4820 return false;
4821 }
4822
4823 //If duration is less than minimum value defined in property, return false
4824 const int min_duration_secs = property_get_int32(
4825 "audio.offload.min.duration.secs", -1 /* default_value */);
4826 if (!durationIgnored) {
4827 if (min_duration_secs >= 0) {
4828 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4829 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4830 __func__, min_duration_secs);
4831 return false;
4832 }
4833 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4834 ALOGV("%s: Offload denied by duration < default min(=%u)",
4835 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4836 return false;
4837 }
4838 }
4839
4840 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4841 // creating an offloaded track and tearing it down immediately after start when audioflinger
4842 // detects there is an active non offloadable effect.
4843 // FIXME: We should check the audio session here but we do not have it in this context.
4844 // This may prevent offloading in rare situations where effects are left active by apps
4845 // in the background.
4846 if (mEffects.isNonOffloadableEffectEnabled()) {
4847 return false;
4848 }
4849
4850 return true;
4851}
4852
4853audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4854 const audio_config_t *config) {
4855 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4856 offloadInfo.format = config->format;
4857 offloadInfo.sample_rate = config->sample_rate;
4858 offloadInfo.channel_mask = config->channel_mask;
4859 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4860 offloadInfo.has_video = false;
4861 offloadInfo.is_streaming = false;
4862 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4863
4864 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4865 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4866 audio_flags_to_audio_output_flags(attr->flags, &flags);
4867 // only retain flags that will drive compressed offload or passthrough
4868 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4869 if (offloadPossible) {
4870 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4871 }
4872 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4873
Dorin Drimusfae3c642022-03-17 18:36:30 +01004874 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004875 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4876 [this, attr](sp<DeviceDescriptor> device) {
4877 return getPreferredMixerAttributesInfo(
4878 device->getId(),
4879 mEngine->getProductStrategyForAttributes(*attr),
4880 true /*activeBitPerfectPreferred*/) != nullptr;
4881 })) {
4882 // Bit-perfect playback is active on one of the selected devices, direct output will
4883 // be rejected at this instant.
4884 return AUDIO_DIRECT_NOT_SUPPORTED;
4885 }
jiabin2b9d5a12021-12-10 01:06:29 +00004886 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004887 DeviceVector outputDevices = engineOutputDevices;
4888 // the MSD module checks for different conditions and output devices
4889 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4890 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4891 continue;
4892 }
4893 outputDevices = getMsdAudioOutDevices();
4894 }
jiabin2b9d5a12021-12-10 01:06:29 +00004895 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004896 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004897 config->sample_rate, nullptr /*updatedSamplingRate*/,
4898 config->format, nullptr /*updatedFormat*/,
4899 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004900 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004901 continue;
4902 }
4903 // reject profiles not corresponding to a device currently available
4904 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4905 continue;
4906 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004907 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4908 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004909 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004910 != AUDIO_DIRECT_NOT_SUPPORTED) {
4911 // Already reports offload gapless supported. No need to report offload support.
4912 continue;
4913 }
4914 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4915 != AUDIO_OUTPUT_FLAG_NONE) {
4916 // If offload gapless is reported, no need to report offload support.
4917 directMode = (audio_direct_mode_t) ((directMode &
4918 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4919 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4920 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004921 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004922 }
4923 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004924 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004925 }
4926 }
4927 }
4928 return directMode;
4929}
4930
Dorin Drimusf2196d82022-01-03 12:11:18 +01004931status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4932 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004933 if (mEffects.isNonOffloadableEffectEnabled()) {
4934 return OK;
4935 }
jiabinf1c73972022-04-14 16:28:52 -07004936 DeviceVector devices;
4937 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004938 if (status != OK) {
4939 return status;
4940 }
4941 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4942 if (devices.empty()) {
4943 return OK; // no output devices for the attributes
4944 }
jiabinf1c73972022-04-14 16:28:52 -07004945 return getProfilesForDevices(devices, audioProfilesVector,
4946 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004947}
4948
jiabina84c3d32022-12-02 18:59:55 +00004949status_t AudioPolicyManager::getSupportedMixerAttributes(
4950 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4951 ALOGV("%s, portId=%d", __func__, portId);
4952 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4953 if (deviceDescriptor == nullptr) {
4954 ALOGE("%s the requested device is currently unavailable", __func__);
4955 return BAD_VALUE;
4956 }
jiabin96daffc2023-05-11 17:51:55 +00004957 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4958 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4959 deviceDescriptor->type());
4960 return BAD_VALUE;
4961 }
jiabina84c3d32022-12-02 18:59:55 +00004962 for (const auto& hwModule : mHwModules) {
4963 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4964 if (curProfile->supportsDevice(deviceDescriptor)) {
4965 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4966 }
4967 }
4968 }
4969 return NO_ERROR;
4970}
4971
4972status_t AudioPolicyManager::setPreferredMixerAttributes(
4973 const audio_attributes_t *attr,
4974 audio_port_handle_t portId,
4975 uid_t uid,
4976 const audio_mixer_attributes_t *mixerAttributes) {
4977 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4978 "mixerBehavior=%d}, uid=%d, portId=%u",
4979 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4980 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4981 mixerAttributes->mixer_behavior, uid, portId);
4982 if (attr->usage != AUDIO_USAGE_MEDIA) {
4983 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4984 return BAD_VALUE;
4985 }
4986 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4987 if (deviceDescriptor == nullptr) {
4988 ALOGE("%s the requested device is currently unavailable", __func__);
4989 return BAD_VALUE;
4990 }
4991 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4992 ALOGE("%s(%d), type=%d, is not a usb output device",
4993 __func__, portId, deviceDescriptor->type());
4994 return BAD_VALUE;
4995 }
4996
4997 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4998 audio_flags_to_audio_output_flags(attr->flags, &flags);
4999 flags = (audio_output_flags_t) (flags |
5000 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5001 sp<IOProfile> profile = nullptr;
5002 DeviceVector devices(deviceDescriptor);
5003 for (const auto& hwModule : mHwModules) {
5004 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5005 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005006 && curProfile->getCompatibilityScore(
5007 devices,
5008 mixerAttributes->config.sample_rate,
5009 nullptr /*updatedSamplingRate*/,
5010 mixerAttributes->config.format,
5011 nullptr /*updatedFormat*/,
5012 mixerAttributes->config.channel_mask,
5013 nullptr /*updatedChannelMask*/,
5014 flags,
5015 false /*exactMatchRequiredForInputFlags*/)
5016 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005017 profile = curProfile;
5018 break;
5019 }
5020 }
5021 }
5022 if (profile == nullptr) {
5023 ALOGE("%s, there is no compatible profile found", __func__);
5024 return BAD_VALUE;
5025 }
5026
5027 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5028 sp<PreferredMixerAttributesInfo>::make(
5029 uid, portId, profile, flags, *mixerAttributes);
5030 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5031 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5032
5033 // If 1) there is any client from the preferred mixer configuration owner that is currently
5034 // active and matches the strategy and 2) current output is on the preferred device and the
5035 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5036 // configuration.
5037 std::vector<audio_io_handle_t> outputsToReopen;
5038 for (size_t i = 0; i < mOutputs.size(); i++) {
5039 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005040 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5041 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005042 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005043 } else {
5044 for (const auto &client: output->getActiveClients()) {
5045 if (client->uid() == uid && client->strategy() == strategy) {
5046 client->setIsInvalid();
5047 outputsToReopen.push_back(output->mIoHandle);
5048 }
jiabina84c3d32022-12-02 18:59:55 +00005049 }
5050 }
5051 }
5052 }
5053 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5054 config.sample_rate = mixerAttributes->config.sample_rate;
5055 config.channel_mask = mixerAttributes->config.channel_mask;
5056 config.format = mixerAttributes->config.format;
5057 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005058 sp<SwAudioOutputDescriptor> desc =
5059 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5060 if (desc == nullptr) {
5061 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5062 continue;
5063 }
jiabin220eea12024-05-17 17:55:20 +00005064 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005065 }
5066
5067 return NO_ERROR;
5068}
5069
5070sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005071 audio_port_handle_t devicePortId,
5072 product_strategy_t strategy,
5073 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005074 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5075 if (it == mPreferredMixerAttrInfos.end()) {
5076 return nullptr;
5077 }
jiabind9a58d32023-06-01 17:57:30 +00005078 if (activeBitPerfectPreferred) {
5079 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005080 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005081 return info;
5082 }
5083 }
jiabina84c3d32022-12-02 18:59:55 +00005084 }
jiabind9a58d32023-06-01 17:57:30 +00005085 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5086 return strategyMatchedMixerAttrInfoIt == it->second.end()
5087 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005088}
5089
5090status_t AudioPolicyManager::getPreferredMixerAttributes(
5091 const audio_attributes_t *attr,
5092 audio_port_handle_t portId,
5093 audio_mixer_attributes_t* mixerAttributes) {
5094 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5095 portId, mEngine->getProductStrategyForAttributes(*attr));
5096 if (info == nullptr) {
5097 return NAME_NOT_FOUND;
5098 }
5099 *mixerAttributes = info->getMixerAttributes();
5100 return NO_ERROR;
5101}
5102
5103status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5104 audio_port_handle_t portId,
5105 uid_t uid) {
5106 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5107 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5108 if (preferredMixerAttrInfo == nullptr) {
5109 return NAME_NOT_FOUND;
5110 }
5111 if (preferredMixerAttrInfo->getUid() != uid) {
5112 ALOGE("%s, requested uid=%d, owned uid=%d",
5113 __func__, uid, preferredMixerAttrInfo->getUid());
5114 return PERMISSION_DENIED;
5115 }
5116 mPreferredMixerAttrInfos[portId].erase(strategy);
5117 if (mPreferredMixerAttrInfos[portId].empty()) {
5118 mPreferredMixerAttrInfos.erase(portId);
5119 }
5120
5121 // Reconfig existing output
5122 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5123 for (size_t i = 0; i < mOutputs.size(); i++) {
5124 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5125 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5126 }
5127 }
5128 for (const auto output : potentialOutputsToReopen) {
5129 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5130 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5131 preferredMixerAttrInfo->getFlags())) {
5132 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5133 }
5134 }
5135 return NO_ERROR;
5136}
5137
Eric Laurent6a94d692014-05-20 11:18:06 -07005138status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5139 audio_port_type_t type,
5140 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005141 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005142 unsigned int *generation)
5143{
jiabin19cdba52020-11-24 11:28:58 -08005144 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5145 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005146 return BAD_VALUE;
5147 }
5148 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005149 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005150 *num_ports = 0;
5151 }
5152
5153 size_t portsWritten = 0;
5154 size_t portsMax = *num_ports;
5155 *num_ports = 0;
5156 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005157 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5158 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005160 for (const auto& dev : mAvailableOutputDevices) {
5161 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005162 continue;
5163 }
5164 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005165 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005166 }
5167 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005169 }
5170 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005171 for (const auto& dev : mAvailableInputDevices) {
5172 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005173 continue;
5174 }
5175 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005176 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005177 }
5178 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 }
5181 }
5182 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5183 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5184 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5185 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5186 }
5187 *num_ports += mInputs.size();
5188 }
5189 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005190 size_t numOutputs = 0;
5191 for (size_t i = 0; i < mOutputs.size(); i++) {
5192 if (!mOutputs[i]->isDuplicated()) {
5193 numOutputs++;
5194 if (portsWritten < portsMax) {
5195 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5196 }
5197 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 }
Eric Laurent84c70242014-06-23 08:46:27 -07005199 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005200 }
5201 }
jiabina84c3d32022-12-02 18:59:55 +00005202
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005204 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 return NO_ERROR;
5206}
5207
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005208status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5209 std::vector<media::AudioPortFw>* _aidl_return) {
5210 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5211 audio_port_v7 port;
5212 dev->toAudioPort(&port);
5213 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5214 _aidl_return->push_back(std::move(aidlPort));
5215 return OK;
5216 };
5217
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005218 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005219 for (const auto& dev : module->getDeclaredDevices()) {
5220 if (role == media::AudioPortRole::NONE ||
5221 ((role == media::AudioPortRole::SOURCE)
5222 == audio_is_input_device(dev->type()))) {
5223 RETURN_STATUS_IF_ERROR(pushPort(dev));
5224 }
5225 }
5226 }
5227 return OK;
5228}
5229
jiabin19cdba52020-11-24 11:28:58 -08005230status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005231{
Eric Laurent99fcae42018-05-17 16:59:18 -07005232 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5233 return BAD_VALUE;
5234 }
5235 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5236 if (dev != 0) {
5237 dev->toAudioPort(port);
5238 return NO_ERROR;
5239 }
5240 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5241 if (dev != 0) {
5242 dev->toAudioPort(port);
5243 return NO_ERROR;
5244 }
5245 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5246 if (out != 0) {
5247 out->toAudioPort(port);
5248 return NO_ERROR;
5249 }
5250 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5251 if (in != 0) {
5252 in->toAudioPort(port);
5253 return NO_ERROR;
5254 }
5255 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005256}
5257
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005258status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5259 audio_patch_handle_t *handle,
5260 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005261{
François Gaffieafd4cea2019-11-18 15:50:22 +01005262 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 if (handle == NULL || patch == NULL) {
5264 return BAD_VALUE;
5265 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005266 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005267 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005268 return BAD_VALUE;
5269 }
5270 // only one source per audio patch supported for now
5271 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 return INVALID_OPERATION;
5273 }
Eric Laurent874c42872014-08-08 15:13:39 -07005274 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 return INVALID_OPERATION;
5276 }
Eric Laurent874c42872014-08-08 15:13:39 -07005277 for (size_t i = 0; i < patch->num_sinks; i++) {
5278 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5279 return INVALID_OPERATION;
5280 }
5281 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005282
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005283 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5284 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5285 if (srcDevice == nullptr || sinkDevice == nullptr) {
5286 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5287 return BAD_VALUE;
5288 }
5289 ALOGV("%s between source %s and sink %s", __func__,
5290 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5291 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5292 // Default attributes, default volume priority, not to infer with non raw audio patches.
5293 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5294 const struct audio_port_config *source = &patch->sources[0];
5295 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005296 new SourceClientDescriptor(
5297 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5298 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005299 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005300 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005301
5302 status_t status =
5303 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5304
5305 if (status != NO_ERROR) {
5306 return INVALID_OPERATION;
5307 }
5308 mAudioSources.add(portId, sourceDesc);
5309 return NO_ERROR;
5310}
5311
5312status_t AudioPolicyManager::connectAudioSourceToSink(
5313 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5314 const struct audio_patch *patch,
5315 audio_patch_handle_t &handle,
5316 uid_t uid, uint32_t delayMs)
5317{
5318 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5319 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5320 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5321 return INVALID_OPERATION;
5322 }
5323 sourceDesc->connect(handle, sinkDevice);
5324 if (isMsdPatch(handle)) {
5325 return NO_ERROR;
5326 }
5327 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5328 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5329 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5330 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5331 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5332 goto FailurePatchAdded;
5333 }
5334 status = swOutput->start();
5335 if (status != NO_ERROR) {
5336 goto FailureSourceAdded;
5337 }
5338 swOutput->addClient(sourceDesc);
5339 status = startSource(swOutput, sourceDesc, &delayMs);
5340 if (status != NO_ERROR) {
5341 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5342 goto FailureSourceActive;
5343 }
5344 if (delayMs != 0) {
5345 usleep(delayMs * 1000);
5346 }
5347 return NO_ERROR;
5348
5349FailureSourceActive:
5350 swOutput->stop();
5351 releaseOutput(sourceDesc->portId());
5352FailureSourceAdded:
5353 sourceDesc->setSwOutput(nullptr);
5354FailurePatchAdded:
5355 releaseAudioPatchInternal(handle);
5356 return INVALID_OPERATION;
5357}
5358
5359status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5360 audio_patch_handle_t *handle,
5361 uid_t uid, uint32_t delayMs,
5362 const sp<SourceClientDescriptor>& sourceDesc)
5363{
5364 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005365 sp<AudioPatch> patchDesc;
5366 ssize_t index = mAudioPatches.indexOfKey(*handle);
5367
François Gaffieafd4cea2019-11-18 15:50:22 +01005368 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5369 patch->sources[0].role,
5370 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005371#if LOG_NDEBUG == 0
5372 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005373 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5374 patch->sinks[i].role,
5375 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005376 }
5377#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005378
5379 if (index >= 0) {
5380 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005381 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5382 __func__, mUidCached, patchDesc->getUid(), uid);
5383 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 return INVALID_OPERATION;
5385 }
5386 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005387 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 }
5389
5390 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005392 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005393 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005394 return BAD_VALUE;
5395 }
Eric Laurent84c70242014-06-23 08:46:27 -07005396 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5397 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005398 if (patchDesc != 0) {
5399 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005400 ALOGV("%s source id differs for patch current id %d new id %d",
5401 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 return BAD_VALUE;
5403 }
5404 }
Eric Laurent874c42872014-08-08 15:13:39 -07005405 DeviceVector devices;
5406 for (size_t i = 0; i < patch->num_sinks; i++) {
5407 // Only support mix to devices connection
5408 // TODO add support for mix to mix connection
5409 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005410 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005411 return INVALID_OPERATION;
5412 }
5413 sp<DeviceDescriptor> devDesc =
5414 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5415 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005416 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005417 return BAD_VALUE;
5418 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005419
jiabin66acc432024-02-06 00:57:36 +00005420 if (outputDesc->mProfile->getCompatibilityScore(
5421 DeviceVector(devDesc),
5422 patch->sources[0].sample_rate,
5423 nullptr, // updatedSamplingRate
5424 patch->sources[0].format,
5425 nullptr, // updatedFormat
5426 patch->sources[0].channel_mask,
5427 nullptr, // updatedChannelMask
5428 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005429 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005430 return INVALID_OPERATION;
5431 }
5432 devices.add(devDesc);
5433 }
5434 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005435 return INVALID_OPERATION;
5436 }
Eric Laurent874c42872014-08-08 15:13:39 -07005437
Eric Laurent6a94d692014-05-20 11:18:06 -07005438 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005439 ALOGV("%s setting device %s on output %d",
5440 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305441 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 index = mAudioPatches.indexOfKey(*handle);
5443 if (index >= 0) {
5444 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005445 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 }
5447 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005448 patchDesc->setUid(uid);
5449 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005450 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005451 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005452 return INVALID_OPERATION;
5453 }
5454 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5455 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5456 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005457 // only one sink supported when connecting an input device to a mix
5458 if (patch->num_sinks > 1) {
5459 return INVALID_OPERATION;
5460 }
François Gaffie53615e22015-03-19 09:24:12 +01005461 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005462 if (inputDesc == NULL) {
5463 return BAD_VALUE;
5464 }
5465 if (patchDesc != 0) {
5466 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5467 return BAD_VALUE;
5468 }
5469 }
François Gaffie11d30102018-11-02 16:09:09 +01005470 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005471 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005472 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005473 return BAD_VALUE;
5474 }
5475
jiabin66acc432024-02-06 00:57:36 +00005476 if (inputDesc->mProfile->getCompatibilityScore(
5477 DeviceVector(device),
5478 patch->sinks[0].sample_rate,
5479 nullptr, /*updatedSampleRate*/
5480 patch->sinks[0].format,
5481 nullptr, /*updatedFormat*/
5482 patch->sinks[0].channel_mask,
5483 nullptr, /*updatedChannelMask*/
5484 // FIXME for the parameter type,
5485 // and the NONE
5486 (audio_output_flags_t)
5487 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005488 return INVALID_OPERATION;
5489 }
5490 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005491 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005492 device->toString().c_str(), inputDesc->mIoHandle);
5493 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005494 index = mAudioPatches.indexOfKey(*handle);
5495 if (index >= 0) {
5496 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005497 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005498 }
5499 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005500 patchDesc->setUid(uid);
5501 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005502 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005503 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005504 return INVALID_OPERATION;
5505 }
5506 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5507 // device to device connection
5508 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005509 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 return BAD_VALUE;
5511 }
5512 }
François Gaffie11d30102018-11-02 16:09:09 +01005513 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005514 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005515 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005516 return BAD_VALUE;
5517 }
Eric Laurent874c42872014-08-08 15:13:39 -07005518
Eric Laurent6a94d692014-05-20 11:18:06 -07005519 //update source and sink with our own data as the data passed in the patch may
5520 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005521 PatchBuilder patchBuilder;
5522 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005523
5524 // if first sink is to MSD, establish single MSD patch
5525 if (getMsdAudioOutDevices().contains(
5526 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5527 ALOGV("%s patching to MSD", __FUNCTION__);
5528 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5529 goto installPatch;
5530 }
5531
François Gaffieafd4cea2019-11-18 15:50:22 +01005532 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5533 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005534
Eric Laurent874c42872014-08-08 15:13:39 -07005535 for (size_t i = 0; i < patch->num_sinks; i++) {
5536 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005537 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005538 return INVALID_OPERATION;
5539 }
François Gaffie11d30102018-11-02 16:09:09 +01005540 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005541 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005542 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005543 return BAD_VALUE;
5544 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005545 audio_port_config sinkPortConfig = {};
5546 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5547 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005548
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005549 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5550 // volume management purpose (tracking activity)
5551 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5552 // in config XML to reach the sink so that is can be declared as available.
5553 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005554 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005555 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005556 // take care of dynamic routing for SwOutput selection,
5557 audio_attributes_t attributes = sourceDesc->attributes();
5558 audio_stream_type_t stream = sourceDesc->stream();
5559 audio_attributes_t resultAttr;
5560 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5561 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005562 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5563 config.channel_mask =
5564 (audio_channel_mask_get_representation(sourceMask)
5565 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5566 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005567 config.format = sourceDesc->config().format;
5568 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5569 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5570 bool isRequestedDeviceForExclusiveUse = false;
5571 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005572 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005573 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005574 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5575 &stream, sourceDesc->uid(), &config, &flags,
5576 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005577 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005578 if (output == AUDIO_IO_HANDLE_NONE) {
5579 ALOGV("%s no output for device %s",
5580 __FUNCTION__, sinkDevice->toString().c_str());
5581 return INVALID_OPERATION;
5582 }
5583 outputDesc = mOutputs.valueFor(output);
5584 if (outputDesc->isDuplicated()) {
5585 ALOGE("%s output is duplicated", __func__);
5586 return INVALID_OPERATION;
5587 }
François Gaffie7e39df22022-04-26 12:48:49 +02005588 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5589 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005590 } else {
5591 // Same for "raw patches" aka created from createAudioPatch API
5592 SortedVector<audio_io_handle_t> outputs =
5593 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5594 // if the sink device is reachable via an opened output stream, request to
5595 // go via this output stream by adding a second source to the patch
5596 // description
5597 output = selectOutput(outputs);
5598 if (output == AUDIO_IO_HANDLE_NONE) {
5599 ALOGE("%s no output available for internal patch sink", __func__);
5600 return INVALID_OPERATION;
5601 }
5602 outputDesc = mOutputs.valueFor(output);
5603 if (outputDesc->isDuplicated()) {
5604 ALOGV("%s output for device %s is duplicated",
5605 __func__, sinkDevice->toString().c_str());
5606 return INVALID_OPERATION;
5607 }
François Gaffie7e39df22022-04-26 12:48:49 +02005608 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005609 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005610 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005611 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005612 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005613 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005614 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5615 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005616 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5617 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005618 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005619 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005620 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005621 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005622 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005623 return INVALID_OPERATION;
5624 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005625 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005626 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005627 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005628 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005629 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005630 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005631 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005632 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5633 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005634 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005635 }
Eric Laurent83b88082014-06-20 18:31:16 -07005636 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005637 }
5638 // TODO: check from routing capabilities in config file and other conflicting patches
5639
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005640installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005641 status_t status = installPatch(
5642 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005643 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005644 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005645 return INVALID_OPERATION;
5646 }
5647 } else {
5648 return BAD_VALUE;
5649 }
5650 } else {
5651 return BAD_VALUE;
5652 }
5653 return NO_ERROR;
5654}
5655
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005656status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005657{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005658 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005659 ssize_t index = mAudioPatches.indexOfKey(handle);
5660
5661 if (index < 0) {
5662 return BAD_VALUE;
5663 }
5664 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005665 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5666 __func__, mUidCached, patchDesc->getUid(), uid);
5667 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005668 return INVALID_OPERATION;
5669 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005670 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5671 for (size_t i = 0; i < mAudioSources.size(); i++) {
5672 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5673 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5674 portId = sourceDesc->portId();
5675 break;
5676 }
5677 }
5678 return portId != AUDIO_PORT_HANDLE_NONE ?
5679 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005680}
Eric Laurent6a94d692014-05-20 11:18:06 -07005681
François Gaffieafd4cea2019-11-18 15:50:22 +01005682status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005683 uint32_t delayMs,
5684 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005685{
5686 ALOGV("%s patch %d", __func__, handle);
5687 if (mAudioPatches.indexOfKey(handle) < 0) {
5688 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5689 return BAD_VALUE;
5690 }
5691 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005692 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005693 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005694 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005695 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005696 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005697 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005698 return BAD_VALUE;
5699 }
5700
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305701 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005702 getNewOutputDevices(outputDesc, true /*fromCache*/),
5703 true,
5704 0,
5705 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005706 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5707 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005708 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005709 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005710 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005711 return BAD_VALUE;
5712 }
5713 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005714 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005715 true,
5716 NULL);
5717 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005718 status_t status =
5719 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5720 ALOGV("%s patch panel returned %d patchHandle %d",
5721 __func__, status, patchDesc->getAfHandle());
5722 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005723 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005724 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005725 // SW or HW Bridge
5726 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5727 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005728 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005729 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5730 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5731 outputDesc = sourceDesc->swOutput().promote();
5732 }
5733 if (outputDesc == nullptr) {
5734 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5735 // releaseOutput has already called closeOutput in case of direct output
5736 return NO_ERROR;
5737 }
François Gaffie7e39df22022-04-26 12:48:49 +02005738 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005739 // While using a HwBridge, force reconsidering device only if not reusing an existing
5740 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005741 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005742 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5743 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5744 // Reconsider device only for cases:
5745 // 1 / Active Output
5746 // 2 / Inactive Output previously hosting HwBridge
5747 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5748 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5749 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305750 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005751 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5752 outputDesc->devices(),
5753 force,
5754 0,
5755 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005756 } else {
5757 return BAD_VALUE;
5758 }
5759 } else {
5760 return BAD_VALUE;
5761 }
5762 return NO_ERROR;
5763}
5764
5765status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5766 struct audio_patch *patches,
5767 unsigned int *generation)
5768{
François Gaffie53615e22015-03-19 09:24:12 +01005769 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005770 return BAD_VALUE;
5771 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005772 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005773 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005774}
5775
Eric Laurente1715a42014-05-20 11:30:42 -07005776status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005777{
Eric Laurente1715a42014-05-20 11:30:42 -07005778 ALOGV("setAudioPortConfig()");
5779
5780 if (config == NULL) {
5781 return BAD_VALUE;
5782 }
5783 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5784 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005785 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5786 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005787 }
5788
Eric Laurenta121f902014-06-03 13:32:54 -07005789 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005790 if (config->type == AUDIO_PORT_TYPE_MIX) {
5791 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005792 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005793 if (outputDesc == NULL) {
5794 return BAD_VALUE;
5795 }
Eric Laurent84c70242014-06-23 08:46:27 -07005796 ALOG_ASSERT(!outputDesc->isDuplicated(),
5797 "setAudioPortConfig() called on duplicated output %d",
5798 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005799 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005800 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005801 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005802 if (inputDesc == NULL) {
5803 return BAD_VALUE;
5804 }
Eric Laurenta121f902014-06-03 13:32:54 -07005805 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005806 } else {
5807 return BAD_VALUE;
5808 }
5809 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5810 sp<DeviceDescriptor> deviceDesc;
5811 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5812 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5813 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5814 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5815 } else {
5816 return BAD_VALUE;
5817 }
5818 if (deviceDesc == NULL) {
5819 return BAD_VALUE;
5820 }
Eric Laurenta121f902014-06-03 13:32:54 -07005821 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005822 } else {
5823 return BAD_VALUE;
5824 }
5825
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005826 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005827 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5828 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005829 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005830 audioPortConfig->toAudioPortConfig(&newConfig, config);
5831 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005832 }
Eric Laurenta121f902014-06-03 13:32:54 -07005833 if (status != NO_ERROR) {
5834 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005835 }
Eric Laurente1715a42014-05-20 11:30:42 -07005836
5837 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005838}
5839
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005840void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5841{
Eric Laurentd60560a2015-04-10 11:31:20 -07005842 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005843 clearAudioPatches(uid);
5844 clearSessionRoutes(uid);
5845}
5846
Eric Laurent6a94d692014-05-20 11:18:06 -07005847void AudioPolicyManager::clearAudioPatches(uid_t uid)
5848{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005849 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005850 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005851 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005852 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005853 }
5854 }
5855}
5856
François Gaffiec005e562018-11-06 15:04:49 +01005857void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005858{
François Gaffiec005e562018-11-06 15:04:49 +01005859 // Take the first attributes following the product strategy as it is used to retrieve the routed
5860 // device. All attributes wihin a strategy follows the same "routing strategy"
5861 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5862 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005863 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005864 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005865 for (size_t j = 0; j < mOutputs.size(); j++) {
5866 if (mOutputs.keyAt(j) == ouptutToSkip) {
5867 continue;
5868 }
5869 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005870 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005871 continue;
5872 }
5873 // If the default device for this strategy is on another output mix,
5874 // invalidate all tracks in this strategy to force re connection.
5875 // Otherwise select new device on the output mix.
5876 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005877 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005878 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005879 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005880 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005881 // If the device is using preferred mixer attributes, the output need to reopen
5882 // with default configuration when the new selected devices are different from
5883 // current routing devices.
5884 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5885 continue;
5886 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305887 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005888 }
5889 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005890 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005891}
5892
5893void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5894{
5895 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005896 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005897 for (size_t i = 0; i < mOutputs.size(); i++) {
5898 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005899 for (const auto& client : outputDesc->getClientIterable()) {
5900 if (client->hasPreferredDevice() && client->uid() == uid) {
5901 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005902 auto clientStrategy = client->strategy();
5903 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5904 end(affectedStrategies)) {
5905 continue;
5906 }
5907 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005908 }
5909 }
5910 }
5911 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005912 for (const auto& strategy : affectedStrategies) {
5913 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005914 }
5915
5916 // remove input routes associated with this uid
5917 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005918 for (size_t i = 0; i < mInputs.size(); i++) {
5919 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005920 for (const auto& client : inputDesc->getClientIterable()) {
5921 if (client->hasPreferredDevice() && client->uid() == uid) {
5922 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5923 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005924 }
5925 }
5926 }
5927 // reroute inputs if necessary
5928 SortedVector<audio_io_handle_t> inputsToClose;
5929 for (size_t i = 0; i < mInputs.size(); i++) {
5930 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005931 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005932 inputsToClose.add(inputDesc->mIoHandle);
5933 }
5934 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005935 for (const auto& input : inputsToClose) {
5936 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005937 }
5938}
5939
Eric Laurentd60560a2015-04-10 11:31:20 -07005940void AudioPolicyManager::clearAudioSources(uid_t uid)
5941{
5942 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005943 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5944 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005945 stopAudioSource(mAudioSources.keyAt(i));
5946 }
5947 }
5948}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005949
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005950status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5951 audio_io_handle_t *ioHandle,
5952 audio_devices_t *device)
5953{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005954 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5955 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005956 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005957 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5958 if (deviceDesc == nullptr) {
5959 return INVALID_OPERATION;
5960 }
5961 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005962
François Gaffiedf372692015-03-19 10:43:27 +01005963 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005964}
5965
Eric Laurentd60560a2015-04-10 11:31:20 -07005966status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005967 const audio_attributes_t *attributes,
5968 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005969 uid_t uid) {
5970 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005971 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005972}
5973
5974status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5975 const audio_attributes_t *attributes,
5976 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005977 uid_t uid, bool internal, bool isCallRx,
5978 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005979{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005980 ALOGV("%s", __FUNCTION__);
5981 *portId = AUDIO_PORT_HANDLE_NONE;
5982
5983 if (source == NULL || attributes == NULL || portId == NULL) {
5984 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5985 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005986 return BAD_VALUE;
5987 }
5988
Eric Laurentd60560a2015-04-10 11:31:20 -07005989 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5990 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005991 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5992 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005993 return INVALID_OPERATION;
5994 }
5995
François Gaffie11d30102018-11-02 16:09:09 +01005996 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005997 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005998 String8(source->ext.device.address),
5999 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006000 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006001 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006002 return BAD_VALUE;
6003 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006004
jiabin4ef93452019-09-10 14:29:54 -07006005 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006006
François Gaffieaaac0fd2018-11-22 17:56:39 +01006007 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006008 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006009 mEngine->getStreamTypeForAttributes(*attributes),
6010 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006011 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006012
David Lif85c5e32024-07-01 13:14:10 +00006013 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006014 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006015 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006016 }
6017 return status;
6018}
6019
David Lif85c5e32024-07-01 13:14:10 +00006020status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6021 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006022{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006023 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006024
6025 // make sure we only have one patch per source.
6026 disconnectAudioSource(sourceDesc);
6027
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006028 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006029 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6030 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6031 sourceDesc->srcDevice()->type(),
6032 String8(sourceDesc->srcDevice()->address().c_str()),
6033 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006034 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006035 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006036 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006037 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006038 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6039 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6040 return INVALID_OPERATION;
6041 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006042 PatchBuilder patchBuilder;
6043 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6044 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006045
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006046 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006047 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006048}
6049
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006050status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006051{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006052 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6053 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006054 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006055 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006056 return BAD_VALUE;
6057 }
6058 status_t status = disconnectAudioSource(sourceDesc);
6059
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006061 return status;
6062}
6063
Andy Hung2ddee192015-12-18 17:34:44 -08006064status_t AudioPolicyManager::setMasterMono(bool mono)
6065{
6066 if (mMasterMono == mono) {
6067 return NO_ERROR;
6068 }
6069 mMasterMono = mono;
6070 // if enabling mono we close all offloaded devices, which will invalidate the
6071 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6072 // for recreating the new AudioTrack as non-offloaded PCM.
6073 //
6074 // If disabling mono, we leave all tracks as is: we don't know which clients
6075 // and tracks are able to be recreated as offloaded. The next "song" should
6076 // play back offloaded.
6077 if (mMasterMono) {
6078 Vector<audio_io_handle_t> offloaded;
6079 for (size_t i = 0; i < mOutputs.size(); ++i) {
6080 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6081 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6082 offloaded.push(desc->mIoHandle);
6083 }
6084 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006085 for (const auto& handle : offloaded) {
6086 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006087 }
6088 }
6089 // update master mono for all remaining outputs
6090 for (size_t i = 0; i < mOutputs.size(); ++i) {
6091 updateMono(mOutputs.keyAt(i));
6092 }
6093 return NO_ERROR;
6094}
6095
6096status_t AudioPolicyManager::getMasterMono(bool *mono)
6097{
6098 *mono = mMasterMono;
6099 return NO_ERROR;
6100}
6101
Eric Laurentac9cef52017-06-09 15:46:26 -07006102float AudioPolicyManager::getStreamVolumeDB(
6103 audio_stream_type_t stream, int index, audio_devices_t device)
6104{
Vlad Popa9d482762024-06-21 16:40:23 -07006105 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6106 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006107}
6108
jiabin81772902018-04-02 17:52:27 -07006109status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6110 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006111 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006112{
Kriti Dang6537def2021-03-02 13:46:59 +01006113 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6114 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006115 return BAD_VALUE;
6116 }
Kriti Dang6537def2021-03-02 13:46:59 +01006117 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6118 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006119
6120 size_t formatsWritten = 0;
6121 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006122
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006123 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006124 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6125 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006126 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006127 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006128 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006129 bool formatEnabled = true;
6130 switch (forceUse) {
6131 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006132 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006133 break;
6134 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6135 formatEnabled = false;
6136 break;
6137 default: // AUTO or ALWAYS => true
6138 break;
jiabin81772902018-04-02 17:52:27 -07006139 }
6140 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6141 }
jiabin81772902018-04-02 17:52:27 -07006142 }
6143 return NO_ERROR;
6144}
6145
Kriti Dang6537def2021-03-02 13:46:59 +01006146status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6147 audio_format_t *surroundFormats) {
6148 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6149 return BAD_VALUE;
6150 }
6151 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6152 __func__, *numSurroundFormats, surroundFormats);
6153
6154 size_t formatsWritten = 0;
6155 size_t formatsMax = *numSurroundFormats;
6156 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6157
6158 // Return formats from all device profiles that have already been resolved by
6159 // checkOutputsForDevice().
6160 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6161 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6162 audio_devices_t deviceType = device->type();
6163 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6164 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006165 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6166 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006167 continue;
6168 }
6169 // Formats reported by sink devices
6170 std::unordered_set<audio_format_t> formatset;
6171 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6172 formatset.insert(it->second.begin(), it->second.end());
6173 }
6174
6175 // Formats hard-coded in the in policy configuration file (if any).
6176 FormatVector encodedFormats = device->encodedFormats();
6177 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6178 // Filter the formats which are supported by the vendor hardware.
6179 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006180 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006181 formats.insert(*it);
6182 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006183 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006184 if (pair.second.count(*it) != 0) {
6185 formats.insert(pair.first);
6186 break;
6187 }
6188 }
6189 }
6190 }
6191 }
6192 *numSurroundFormats = formats.size();
6193 for (const auto& format: formats) {
6194 if (formatsWritten < formatsMax) {
6195 surroundFormats[formatsWritten++] = format;
6196 }
6197 }
6198 return NO_ERROR;
6199}
6200
jiabin81772902018-04-02 17:52:27 -07006201status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6202{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006203 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006204 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6205 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006206 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006207 return BAD_VALUE;
6208 }
6209
Mikhail Naganov100f0122018-11-29 11:22:16 -08006210 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6211 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006212 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006213 return INVALID_OPERATION;
6214 }
6215
Mikhail Naganov100f0122018-11-29 11:22:16 -08006216 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006217 return NO_ERROR;
6218 }
6219
Mikhail Naganov100f0122018-11-29 11:22:16 -08006220 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006221 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006222 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006223 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006224 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006225 }
6226 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006227 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006228 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006229 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006230 }
6231 }
6232
6233 sp<SwAudioOutputDescriptor> outputDesc;
6234 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006235 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6236 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006237 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6238 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006239 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006240 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006241 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006242 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6243 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006244 name.c_str(),
6245 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006246 if (status != NO_ERROR) {
6247 continue;
6248 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006249 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006250 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6251 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006252 name.c_str(),
6253 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006254 profileUpdated |= (status == NO_ERROR);
6255 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006256 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006257 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006258 AUDIO_DEVICE_IN_HDMI);
6259 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6260 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006261 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006262 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006263 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6264 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6265 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006266 name.c_str(),
6267 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006268 if (status != NO_ERROR) {
6269 continue;
6270 }
6271 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6272 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6273 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006274 name.c_str(),
6275 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006276 profileUpdated |= (status == NO_ERROR);
6277 }
6278
jiabin81772902018-04-02 17:52:27 -07006279 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006280 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006281 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006282 }
6283
6284 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6285}
6286
Eric Laurent5ada82e2019-08-29 17:53:54 -07006287void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006288{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006289 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006290 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006291 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006292 }
6293}
6294
jiabin6012f912018-11-02 17:06:30 -07006295bool AudioPolicyManager::isHapticPlaybackSupported()
6296{
6297 for (const auto& hwModule : mHwModules) {
6298 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6299 for (const auto &outProfile : outputProfiles) {
6300 struct audio_port audioPort;
6301 outProfile->toAudioPort(&audioPort);
6302 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6303 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6304 return true;
6305 }
6306 }
6307 }
6308 }
6309 return false;
6310}
6311
Carter Hsu325a8eb2022-01-19 19:56:51 +08006312bool AudioPolicyManager::isUltrasoundSupported()
6313{
6314 bool hasUltrasoundOutput = false;
6315 bool hasUltrasoundInput = false;
6316 for (const auto& hwModule : mHwModules) {
6317 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6318 if (!hasUltrasoundOutput) {
6319 for (const auto &outProfile : outputProfiles) {
6320 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6321 hasUltrasoundOutput = true;
6322 break;
6323 }
6324 }
6325 }
6326
6327 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6328 if (!hasUltrasoundInput) {
6329 for (const auto &inputProfile : inputProfiles) {
6330 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6331 hasUltrasoundInput = true;
6332 break;
6333 }
6334 }
6335 }
6336
6337 if (hasUltrasoundOutput && hasUltrasoundInput)
6338 return true;
6339 }
6340 return false;
6341}
6342
Atneya Nair698f5ef2022-12-15 16:15:09 -08006343bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6344{
6345 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6346 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6347 for (const auto& hwModule : mHwModules) {
6348 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6349 for (const auto &inputProfile : inputProfiles) {
6350 if ((inputProfile->getFlags() & mask) == mask) {
6351 return true;
6352 }
6353 }
6354 }
6355 return false;
6356}
6357
Eric Laurent8340e672019-11-06 11:01:08 -08006358bool AudioPolicyManager::isCallScreenModeSupported()
6359{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006360 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006361}
6362
6363
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006364status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006365{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006366 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006367 if (!sourceDesc->isConnected()) {
6368 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6369 return NO_ERROR;
6370 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006371 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6372 if (swOutput != 0) {
6373 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006374 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006375 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006376 }
jiabinbce0c1d2020-10-05 11:20:18 -07006377 if (releaseOutput(sourceDesc->portId())) {
6378 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6379 // no need to release audio patch here but just return NO_ERROR.
6380 return NO_ERROR;
6381 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006382 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006383 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006384 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006385 // close Hwoutput and remove from mHwOutputs
6386 } else {
6387 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6388 }
6389 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006390 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006391 sourceDesc->disconnect();
6392 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006393}
6394
François Gaffiec005e562018-11-06 15:04:49 +01006395sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6396 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006397{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006398 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006399 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006400 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006401 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006402 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6403 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006404 source = sourceDesc;
6405 break;
6406 }
6407 }
6408 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006409}
6410
Eric Laurentb4f42a92022-01-17 17:37:31 +01006411bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006412 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006413 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006414{
6415 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6416 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006417 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006418 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006419 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6420 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6421 return false;
6422 }
6423 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6424 return false;
6425 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006426 }
6427
Eric Laurentd332bc82023-08-04 11:45:23 +02006428 // The caller can have the audio config criteria ignored by either passing a null ptr or
6429 // the AUDIO_CONFIG_INITIALIZER value.
6430 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006431 // some positional channel masks and PCM format and for stereo if low latency performance
6432 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006433
6434 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006435 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006436 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6437 ? audio_channel_mask_contains_stereo(config->channel_mask)
6438 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006439 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006440 return false;
6441 }
6442 if (!audio_is_linear_pcm(config->format)) {
6443 return false;
6444 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006445 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6446 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6447 return false;
6448 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006449 }
6450
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006451 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006452 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006453 if (profile == nullptr) {
6454 return false;
6455 }
6456
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006457 return true;
6458}
6459
Shunkai Yao4c3af932024-04-26 04:12:21 +00006460// The Spatializer output is compatible with Haptic use cases if:
6461// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6462// with client if client haptic channel bits were set, or
6463// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6464// including the haptic bits or creating the HapticGenerator effect for same session.
6465bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6466 const audio_config_t* config, audio_session_t sessionId) const {
6467 const auto clientHapticChannel =
6468 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6469 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6470 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6471
6472 if (threadOutputHapticChannel) {
6473 // check format and sampleRate match if client haptic channel mask exist
6474 if (clientHapticChannel) {
6475 return mSpatializerOutput->getFormat() == config->format &&
6476 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6477 }
6478 return true;
6479 } else {
6480 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6481 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6482 // HapticGenerator effect for this session) are not supported.
6483 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006484 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006485 }
6486}
6487
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006488void AudioPolicyManager::checkVirtualizerClientRoutes() {
6489 std::set<audio_stream_type_t> streamsToInvalidate;
6490 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006491 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6492 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006493 audio_attributes_t attr = client->attributes();
6494 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6495 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6496 audio_config_base_t clientConfig = client->config();
6497 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006498 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006499 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006500 streamsToInvalidate.insert(client->stream());
6501 }
6502 }
6503 }
6504
jiabinc44b3462022-12-08 12:52:31 -08006505 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006506}
6507
Eric Laurente191d1b2022-04-15 11:59:25 +02006508
6509bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6510 const sp<SwAudioOutputDescriptor>& outputDesc) {
6511 if (outputDesc->isDuplicated()) {
6512 return false;
6513 }
6514 DeviceVector devices = outputDesc->supportedDevices();
6515 for (size_t i = 0; i < mOutputs.size(); i++) {
6516 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6517 if (desc == outputDesc || desc->isDuplicated()) {
6518 continue;
6519 }
6520 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6521 if (!sharedDevices.isEmpty()
6522 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6523 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6524 return false;
6525 }
6526 }
6527 return true;
6528}
6529
6530
Eric Laurentfa0f6742021-08-17 18:39:44 +02006531status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006532 const audio_attributes_t *attr,
6533 audio_io_handle_t *output) {
6534 *output = AUDIO_IO_HANDLE_NONE;
6535
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006536 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6537 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6538 audio_config_t *configPtr = nullptr;
6539 audio_config_t config;
6540 if (mixerConfig != nullptr) {
6541 config = audio_config_initializer(mixerConfig);
6542 configPtr = &config;
6543 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006544 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006545 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006546 return BAD_VALUE;
6547 }
6548
6549 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006550 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006551 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006552 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006553 return BAD_VALUE;
6554 }
6555
Eric Laurente191d1b2022-04-15 11:59:25 +02006556 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006557 for (size_t i = 0; i < mOutputs.size(); i++) {
6558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006559 if (!desc->isDuplicated()
6560 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6561 spatializerOutputs.push_back(desc);
6562 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006563 }
6564 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006565 mSpatializerOutput.clear();
6566 bool outputsChanged = false;
6567 for (const auto& desc : spatializerOutputs) {
6568 if (desc->mProfile == profile
6569 && (configPtr == nullptr
6570 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6571 mSpatializerOutput = desc;
6572 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6573 } else {
6574 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6575 " and devices %s", __func__, desc->mIoHandle,
6576 configPtr != nullptr ? configPtr->channel_mask : 0,
6577 devices.toString().c_str());
6578 closeOutput(desc->mIoHandle);
6579 outputsChanged = true;
6580 }
Eric Laurent39095982021-08-24 18:29:27 +02006581 }
6582
Eric Laurente191d1b2022-04-15 11:59:25 +02006583 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006584 sp<SwAudioOutputDescriptor> desc =
6585 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006586 if (desc != nullptr) {
6587 mSpatializerOutput = desc;
6588 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006589 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006590 }
6591
6592 checkVirtualizerClientRoutes();
6593
Eric Laurente191d1b2022-04-15 11:59:25 +02006594 if (outputsChanged) {
6595 mPreviousOutputs = mOutputs;
6596 mpClientInterface->onAudioPortListUpdate();
6597 }
6598
6599 if (mSpatializerOutput == nullptr) {
6600 ALOGV("%s could not open spatializer output with requested config", __func__);
6601 return BAD_VALUE;
6602 }
Eric Laurent39095982021-08-24 18:29:27 +02006603 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006604 ALOGV("%s returning new spatializer output %d", __func__, *output);
6605 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006606}
6607
Eric Laurentfa0f6742021-08-17 18:39:44 +02006608status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6609 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006610 return INVALID_OPERATION;
6611 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006612 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006613 return BAD_VALUE;
6614 }
Eric Laurent39095982021-08-24 18:29:27 +02006615
Eric Laurente191d1b2022-04-15 11:59:25 +02006616 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6617 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6618 closeOutput(mSpatializerOutput->mIoHandle);
6619 //from now on mSpatializerOutput is null
6620 checkVirtualizerClientRoutes();
6621 }
Eric Laurent39095982021-08-24 18:29:27 +02006622
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006623 return NO_ERROR;
6624}
6625
Eric Laurente552edb2014-03-10 17:42:56 -07006626// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006627// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006628// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006629uint32_t AudioPolicyManager::nextAudioPortGeneration()
6630{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006631 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006632}
6633
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006634AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006635 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006636 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006637 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006638 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006639 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006640 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006641 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006642 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006643 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006644 mAudioPortGeneration(1),
6645 mBeaconMuteRefCount(0),
6646 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006647 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006648 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006649 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006650 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006651{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006652}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006653
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006654status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006655 if (mEngine == nullptr) {
6656 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006657 }
6658 mEngine->setObserver(this);
6659 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006660 if (status != NO_ERROR) {
6661 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6662 return status;
6663 }
François Gaffie2110e042015-03-24 08:41:51 +01006664
jiabin29230182023-04-04 21:02:36 +00006665 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6666 // at the end of this function.
6667 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006668 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6669 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6670
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006671 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006672 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006673 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006674
Eric Laurent3a4311c2014-03-17 12:00:47 -07006675 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006676 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6677 defaultOutputDevice == nullptr ||
6678 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6679 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6680 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006681 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006682 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006683 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006684
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006685 // Silence ALOGV statements
6686 property_set("log.tag." LOG_TAG, "D");
6687
Eric Laurente552edb2014-03-10 17:42:56 -07006688 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006689 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006690}
6691
Eric Laurente0720872014-03-11 09:30:41 -07006692AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006693{
Eric Laurente552edb2014-03-10 17:42:56 -07006694 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006695 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006696 }
6697 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006698 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006699 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006700 mAvailableOutputDevices.clear();
6701 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006702 mOutputs.clear();
6703 mInputs.clear();
6704 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006705 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006706 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006707}
6708
Eric Laurente0720872014-03-11 09:30:41 -07006709status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006710{
Eric Laurent87ffa392015-05-22 10:32:38 -07006711 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006712}
6713
Eric Laurente552edb2014-03-10 17:42:56 -07006714// ---
6715
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006716void AudioPolicyManager::onNewAudioModulesAvailable()
6717{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006718 DeviceVector newDevices;
6719 onNewAudioModulesAvailableInt(&newDevices);
6720 if (!newDevices.empty()) {
6721 nextAudioPortGeneration();
6722 mpClientInterface->onAudioPortListUpdate();
6723 }
6724}
6725
6726void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6727{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006728 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006729 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6730 continue;
6731 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006732 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006733 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6734 handle != AUDIO_MODULE_HANDLE_NONE) {
6735 hwModule->setHandle(handle);
6736 } else {
6737 ALOGW("could not load HW module %s", hwModule->getName());
6738 continue;
6739 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006740 }
6741 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006742 // open all output streams needed to access attached devices.
6743 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006744 // This also validates mAvailableOutputDevices list
6745 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6746 if (!outProfile->canOpenNewIo()) {
6747 ALOGE("Invalid Output profile max open count %u for profile %s",
6748 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6749 continue;
6750 }
6751 if (!outProfile->hasSupportedDevices()) {
6752 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6753 continue;
6754 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006755 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6756 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006757 mTtsOutputAvailable = true;
6758 }
6759
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006760 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006761 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006762 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006763 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6764 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006765 } else {
6766 // choose first device present in profile's SupportedDevices also part of
6767 // mAvailableOutputDevices.
6768 if (availProfileDevices.isEmpty()) {
6769 continue;
6770 }
6771 supportedDevice = availProfileDevices.itemAt(0);
6772 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006773 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006774 continue;
6775 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306776
6777 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6778 && availProfileDevices.areAllDevicesAttached()) {
6779 ALOGV("%s skip opening output for mmap profile %s", __func__,
6780 outProfile->getTagName().c_str());
6781 continue;
6782 }
6783
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006784 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6785 mpClientInterface);
6786 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006787 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006788 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006789 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6790 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006791 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006792 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006793 if (status != NO_ERROR) {
6794 ALOGW("Cannot open output stream for devices %s on hw module %s",
6795 supportedDevice->toString().c_str(), hwModule->getName());
6796 continue;
6797 }
6798 for (const auto &device : availProfileDevices) {
6799 // give a valid ID to an attached device once confirmed it is reachable
6800 if (!device->isAttached()) {
6801 device->attach(hwModule);
6802 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006803 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006804 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006805 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6806 }
6807 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006808 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006809 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6810 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006811 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006812 }
Eric Laurent39095982021-08-24 18:29:27 +02006813 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006814 outputDesc->close();
6815 } else {
6816 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306817 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006818 DeviceVector(supportedDevice),
6819 true,
6820 0,
6821 NULL);
6822 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006823 }
6824 // open input streams needed to access attached devices to validate
6825 // mAvailableInputDevices list
6826 for (const auto& inProfile : hwModule->getInputProfiles()) {
6827 if (!inProfile->canOpenNewIo()) {
6828 ALOGE("Invalid Input profile max open count %u for profile %s",
6829 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6830 continue;
6831 }
6832 if (!inProfile->hasSupportedDevices()) {
6833 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6834 continue;
6835 }
6836 // chose first device present in profile's SupportedDevices also part of
6837 // available input devices
6838 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006839 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006840 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006841 ALOGV("%s: Input device list is empty! for profile %s",
6842 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006843 continue;
6844 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306845
6846 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6847 && availProfileDevices.areAllDevicesAttached()) {
6848 ALOGV("%s skip opening input for mmap profile %s", __func__,
6849 inProfile->getTagName().c_str());
6850 continue;
6851 }
6852
Eric Laurentc71b11b2024-06-03 12:54:53 +00006853 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6854 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006855
6856 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6857 status_t status = inputDesc->open(nullptr,
6858 availProfileDevices.itemAt(0),
6859 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306860 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006861 &input);
6862 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306863 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6864 __func__, availProfileDevices.toString().c_str(),
6865 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006866 continue;
6867 }
6868 for (const auto &device : availProfileDevices) {
6869 // give a valid ID to an attached device once confirmed it is reachable
6870 if (!device->isAttached()) {
6871 device->attach(hwModule);
6872 device->importAudioPortAndPickAudioProfile(inProfile, true);
6873 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006874 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006875 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6876 }
6877 }
6878 inputDesc->close();
6879 }
6880 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006881
6882 // Check if spatializer outputs can be closed until used.
6883 // mOutputs vector never contains duplicated outputs at this point.
6884 std::vector<audio_io_handle_t> outputsClosed;
6885 for (size_t i = 0; i < mOutputs.size(); i++) {
6886 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6887 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6888 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6889 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006890 nextAudioPortGeneration();
6891 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6892 if (index >= 0) {
6893 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6894 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6895 patchDesc->getAfHandle(), 0);
6896 mAudioPatches.removeItemsAt(index);
6897 mpClientInterface->onAudioPatchListUpdate();
6898 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006899 desc->close();
6900 }
6901 }
6902 for (auto output : outputsClosed) {
6903 removeOutput(output);
6904 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006905}
6906
Eric Laurent98e38192018-02-15 18:31:53 -08006907void AudioPolicyManager::addOutput(audio_io_handle_t output,
6908 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006909{
Eric Laurent1c333e22014-05-20 10:48:17 -07006910 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006911 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006912 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006913 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006914 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006915}
6916
François Gaffie53615e22015-03-19 09:24:12 +01006917void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6918{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006919 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6920 ALOGV("%s: removing primary output", __func__);
6921 mPrimaryOutput = nullptr;
6922 }
François Gaffie53615e22015-03-19 09:24:12 +01006923 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006924 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006925}
6926
Eric Laurent98e38192018-02-15 18:31:53 -08006927void AudioPolicyManager::addInput(audio_io_handle_t input,
6928 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006929{
Eric Laurent1c333e22014-05-20 10:48:17 -07006930 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006931 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006932}
Eric Laurente552edb2014-03-10 17:42:56 -07006933
François Gaffie11d30102018-11-02 16:09:09 +01006934status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006935 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006936 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006937{
François Gaffie11d30102018-11-02 16:09:09 +01006938 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006939 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006940 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006941
François Gaffie11d30102018-11-02 16:09:09 +01006942 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006943 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006944 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006945 }
Eric Laurente552edb2014-03-10 17:42:56 -07006946
Eric Laurent3b73df72014-03-11 09:06:29 -07006947 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006948 // first call getAudioPort to get the supported attributes from the HAL
6949 struct audio_port_v7 port = {};
6950 device->toAudioPort(&port);
6951 status_t status = mpClientInterface->getAudioPort(&port);
6952 if (status == NO_ERROR) {
6953 device->importAudioPort(port);
6954 }
6955
6956 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006957 for (size_t i = 0; i < mOutputs.size(); i++) {
6958 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006959 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006960 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006961 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6962 mOutputs.keyAt(i), device->toString().c_str());
6963 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006964 }
6965 }
6966 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006967 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006968 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006969 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6970 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006971 if (profile->supportsDevice(device)) {
6972 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306973 ALOGV("%s(): adding profile %s from module %s",
6974 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006975 }
6976 }
6977 }
6978
Eric Laurent7b279bb2015-12-14 10:18:23 -08006979 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006980
Eric Laurente552edb2014-03-10 17:42:56 -07006981 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006982 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006983 return BAD_VALUE;
6984 }
6985
6986 // open outputs for matching profiles if needed. Direct outputs are also opened to
6987 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6988 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006989 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006990
6991 // nothing to do if one output is already opened for this profile
6992 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006993 for (j = 0; j < outputs.size(); j++) {
6994 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006995 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006996 // matching profile: save the sample rates, format and channel masks supported
6997 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006998 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006999 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007000 }
Eric Laurente552edb2014-03-10 17:42:56 -07007001 break;
7002 }
7003 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007004 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007005 continue;
7006 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307007 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7008 ALOGV("%s skip opening output for mmap profile %s",
7009 __func__, profile->getTagName().c_str());
7010 continue;
7011 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007012 if (!profile->canOpenNewIo()) {
7013 ALOGW("Max Output number %u already opened for this profile %s",
7014 profile->maxOpenCount, profile->getTagName().c_str());
7015 continue;
7016 }
7017
Eric Laurent83efe1c2017-07-09 16:51:08 -07007018 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007019 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007020 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7021 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007022 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007023 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007024 profiles.removeAt(profile_index);
7025 profile_index--;
7026 } else {
7027 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007028 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007029 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007030 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7031 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007032 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007033 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007034
François Gaffie11d30102018-11-02 16:09:09 +01007035 if (device_distinguishes_on_address(deviceType)) {
7036 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7037 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307038 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7039 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007040 }
Eric Laurente552edb2014-03-10 17:42:56 -07007041 ALOGV("checkOutputsForDevice(): adding output %d", output);
7042 }
7043 }
7044
7045 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007046 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007047 return BAD_VALUE;
7048 }
Eric Laurentd4692962014-05-05 18:13:44 -07007049 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007050 // check if one opened output is not needed any more after disconnecting one device
7051 for (size_t i = 0; i < mOutputs.size(); i++) {
7052 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007053 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007054 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007055 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007056 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007057 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007058 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007059 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7060 mOutputs.keyAt(i));
7061 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007062 }
Eric Laurente552edb2014-03-10 17:42:56 -07007063 }
7064 }
Eric Laurentd4692962014-05-05 18:13:44 -07007065 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007066 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007067 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7068 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007069 if (!profile->supportsDevice(device)) {
7070 continue;
7071 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307072 ALOGV("%s(): clearing direct output profile %s on module %s",
7073 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007074 profile->clearAudioProfiles();
7075 if (!profile->hasDynamicAudioProfile()) {
7076 continue;
7077 }
7078 // When a device is disconnected, if there is an IOProfile that contains dynamic
7079 // profiles and supports the disconnected device, call getAudioPort to repopulate
7080 // the capabilities of the devices that is supported by the IOProfile.
7081 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7082 if (supportedDevice == device ||
7083 !mAvailableOutputDevices.contains(supportedDevice)) {
7084 continue;
7085 }
7086 struct audio_port_v7 port;
7087 supportedDevice->toAudioPort(&port);
7088 status_t status = mpClientInterface->getAudioPort(&port);
7089 if (status == NO_ERROR) {
7090 supportedDevice->importAudioPort(port);
7091 }
Eric Laurente552edb2014-03-10 17:42:56 -07007092 }
7093 }
7094 }
7095 }
7096 return NO_ERROR;
7097}
7098
François Gaffie11d30102018-11-02 16:09:09 +01007099status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007100 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007101{
François Gaffie11d30102018-11-02 16:09:09 +01007102 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007103 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007104 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007105 }
7106
Eric Laurentd4692962014-05-05 18:13:44 -07007107 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007108 sp<AudioInputDescriptor> desc;
7109
jiabinbf5f4262023-04-12 21:48:34 +00007110 // first call getAudioPort to get the supported attributes from the HAL
7111 struct audio_port_v7 port = {};
7112 device->toAudioPort(&port);
7113 status_t status = mpClientInterface->getAudioPort(&port);
7114 if (status == NO_ERROR) {
7115 device->importAudioPort(port);
7116 }
7117
Eric Laurent0dd51852019-04-19 18:18:58 -07007118 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007119 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007120 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007121 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007122 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007123 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007124 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007125
François Gaffie11d30102018-11-02 16:09:09 +01007126 if (profile->supportsDevice(device)) {
7127 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307128 ALOGV("%s : adding profile %s from module %s", __func__,
7129 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007130 }
7131 }
7132 }
7133
Eric Laurent0dd51852019-04-19 18:18:58 -07007134 if (profiles.isEmpty()) {
7135 ALOGW("%s: No input profile available for device %s",
7136 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007137 return BAD_VALUE;
7138 }
7139
7140 // open inputs for matching profiles if needed. Direct inputs are also opened to
7141 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7142 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7143
Eric Laurent1c333e22014-05-20 10:48:17 -07007144 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007145
Eric Laurentd4692962014-05-05 18:13:44 -07007146 // nothing to do if one input is already opened for this profile
7147 size_t input_index;
7148 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7149 desc = mInputs.valueAt(input_index);
7150 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007151 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007152 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007153 }
Eric Laurentd4692962014-05-05 18:13:44 -07007154 break;
7155 }
7156 }
7157 if (input_index != mInputs.size()) {
7158 continue;
7159 }
7160
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307161 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7162 ALOGV("%s skip opening input for mmap profile %s",
7163 __func__, profile->getTagName().c_str());
7164 continue;
7165 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007166 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307167 ALOGW("%s Max Input number %u already opened for this profile %s",
7168 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007169 continue;
7170 }
7171
Eric Laurentc71b11b2024-06-03 12:54:53 +00007172 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007173 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307174 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307175 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7176 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007177
Eric Laurentcf2c0212014-07-25 16:20:43 -07007178 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007179 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007180 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007181 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007182 mpClientInterface->setParameters(input, String8(param));
7183 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007184 }
jiabin12537fc2023-10-12 17:56:08 +00007185 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007186 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307187 ALOGW("%s direct input missing param for profile %s", __func__,
7188 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007189 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007190 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007191 }
7192
Eric Laurent0dd51852019-04-19 18:18:58 -07007193 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007194 addInput(input, desc);
7195 }
7196 } // endif input != 0
7197
Eric Laurentcf2c0212014-07-25 16:20:43 -07007198 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307199 ALOGW("%s could not open input for device %s on profile %s", __func__,
7200 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007201 profiles.removeAt(profile_index);
7202 profile_index--;
7203 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007204 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007205 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007206 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307207 ALOGV("%s: adding input %d for profile %s", __func__,
7208 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007209
7210 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307211 ALOGV("%s: closing input %d for profile %s", __func__,
7212 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007213 closeInput(input);
7214 }
Eric Laurentd4692962014-05-05 18:13:44 -07007215 }
7216 } // end scan profiles
7217
7218 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007219 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007220 return BAD_VALUE;
7221 }
7222 } else {
7223 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007224 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007225 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007226 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007227 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007228 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007229 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007230 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307231 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7232 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007233 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007234 }
7235 }
7236 }
7237 } // end disconnect
7238
7239 return NO_ERROR;
7240}
7241
7242
Eric Laurente0720872014-03-11 09:30:41 -07007243void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007244{
7245 ALOGV("closeOutput(%d)", output);
7246
François Gaffie1c878552018-11-22 16:53:21 +01007247 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7248 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007249 ALOGW("closeOutput() unknown output %d", output);
7250 return;
7251 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007252 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007253 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007254
Eric Laurente552edb2014-03-10 17:42:56 -07007255 // look for duplicated outputs connected to the output being removed.
7256 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007257 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7258 if (dupOutput->isDuplicated() &&
7259 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7260 sp<SwAudioOutputDescriptor> remainingOutput =
7261 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007262 // As all active tracks on duplicated output will be deleted,
7263 // and as they were also referenced on the other output, the reference
7264 // count for their stream type must be adjusted accordingly on
7265 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007266 const bool wasActive = remainingOutput->isActive();
7267 // Note: no-op on the closing output where all clients has already been set inactive
7268 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007269 // stop() will be a no op if the output is still active but is needed in case all
7270 // active streams refcounts where cleared above
7271 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007272 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007273 }
Eric Laurente552edb2014-03-10 17:42:56 -07007274 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7275 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7276
7277 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007278 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007279 }
7280 }
7281
Eric Laurent05b90f82014-08-27 15:32:29 -07007282 nextAudioPortGeneration();
7283
François Gaffie1c878552018-11-22 16:53:21 +01007284 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007285 if (index >= 0) {
7286 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007287 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7288 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007289 mAudioPatches.removeItemsAt(index);
7290 mpClientInterface->onAudioPatchListUpdate();
7291 }
7292
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007293 if (closingOutputWasActive) {
7294 closingOutput->stop();
7295 }
François Gaffie1c878552018-11-22 16:53:21 +01007296 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007297 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007298 for (const auto device : closingOutput->devices()) {
7299 device->setPreferredConfig(nullptr);
7300 }
7301 }
Eric Laurente552edb2014-03-10 17:42:56 -07007302
François Gaffie53615e22015-03-19 09:24:12 +01007303 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007304 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007305 if (closingOutput == mSpatializerOutput) {
7306 mSpatializerOutput.clear();
7307 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007308
7309 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7310 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007311 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007312 bool directOutputOpen = false;
7313 for (size_t i = 0; i < mOutputs.size(); i++) {
7314 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7315 directOutputOpen = true;
7316 break;
7317 }
7318 }
7319 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007320 ALOGV("no direct outputs open, reset MSD patches");
7321 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7322 // how output devices for patching are resolved. Avoid by caching and reusing the
7323 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7324 // devices to patch to. This may be complicated by the fact that devices may become
7325 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007326 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007327 }
7328 }
jiabin220eea12024-05-17 17:55:20 +00007329
7330 if (closingOutput->mPreferredAttrInfo != nullptr) {
7331 closingOutput->mPreferredAttrInfo->resetActiveClient();
7332 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007333}
7334
7335void AudioPolicyManager::closeInput(audio_io_handle_t input)
7336{
7337 ALOGV("closeInput(%d)", input);
7338
7339 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7340 if (inputDesc == NULL) {
7341 ALOGW("closeInput() unknown input %d", input);
7342 return;
7343 }
7344
Eric Laurent6a94d692014-05-20 11:18:06 -07007345 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007346
François Gaffie11d30102018-11-02 16:09:09 +01007347 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007348 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007349 if (index >= 0) {
7350 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007351 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7352 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007353 mAudioPatches.removeItemsAt(index);
7354 mpClientInterface->onAudioPatchListUpdate();
7355 }
7356
François Gaffie6ebbce02023-07-19 13:27:53 +02007357 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007358 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007359 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007360
François Gaffie11d30102018-11-02 16:09:09 +01007361 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7362 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007363 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007364 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007365 }
Eric Laurente552edb2014-03-10 17:42:56 -07007366}
7367
François Gaffie11d30102018-11-02 16:09:09 +01007368SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7369 const DeviceVector &devices,
7370 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007371{
7372 SortedVector<audio_io_handle_t> outputs;
7373
François Gaffie11d30102018-11-02 16:09:09 +01007374 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007375 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007376 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007377 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007378 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007379 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007380 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007381 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007382 outputs.add(openOutputs.keyAt(i));
7383 }
7384 }
7385 return outputs;
7386}
7387
Mikhail Naganov37977152018-07-11 15:54:44 -07007388void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7389{
7390 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7391 // output is suspended before any tracks are moved to it
7392 checkA2dpSuspend();
7393 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007394 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007395 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007396 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007397 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007398 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7399 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7400 // configuration changes will ultimately be rerouted correctly. We can still avoid
7401 // unnecessary rerouting by caching and reusing the arguments to
7402 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7403 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007404 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007405 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007406 // an event that changed routing likely occurred, inform upper layers
7407 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007408}
7409
François Gaffiec005e562018-11-06 15:04:49 +01007410bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7411 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
François Gaffiec005e562018-11-06 15:04:49 +01007413 return mEngine->getProductStrategyForAttributes(lAttr) ==
7414 mEngine->getProductStrategyForAttributes(rAttr);
7415}
7416
Francois Gaffieff1eb522020-05-06 18:37:04 +02007417void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7418{
7419 for (size_t i = 0; i < mAudioSources.size(); i++) {
7420 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7421 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007422 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007423 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007424 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007425 }
7426 }
7427}
7428
7429void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7430{
7431 for (size_t i = 0; i < mAudioSources.size(); i++) {
7432 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7433 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7434 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7435 disconnectAudioSource(sourceDesc);
7436 }
7437 }
7438}
7439
François Gaffiec005e562018-11-06 15:04:49 +01007440void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7441{
7442 auto psId = mEngine->getProductStrategyForAttributes(attr);
7443
7444 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7445 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007446
François Gaffie11d30102018-11-02 16:09:09 +01007447 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7448 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007449
Eric Laurentc209fe42020-06-05 18:11:23 -07007450 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007451 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007452 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007453 // take into account dynamic audio policies related changes: if a client is now associated
7454 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007455 // invalidate clients on outputs that do not support all the newly selected devices for the
7456 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007457 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007458 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007459 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007460 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007461 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007462
Eric Laurentc209fe42020-06-05 18:11:23 -07007463 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7464 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7465 continue;
7466 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007467 if (!desc->supportsAllDevices(newDevices)) {
7468 invalidatedOutputs.push_back(desc);
7469 break;
7470 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007471 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007472 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007473 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7474 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7475 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007476 if (status == OK) {
7477 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7478 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7479 maxLatency = desc->latency();
7480 }
7481 invalidatedOutputs.push_back(desc);
7482 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007483 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007484 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007485 }
7486 }
7487
Eric Laurent56ed8842022-11-15 16:04:41 +01007488 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007489 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7490 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007491 for (audio_io_handle_t srcOut : srcOutputs) {
7492 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007493 if (desc == nullptr) continue;
7494
7495 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007496 maxLatency = desc->latency();
7497 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007498
Eric Laurent56ed8842022-11-15 16:04:41 +01007499 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007500 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007501 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007502 // a client on a non direct outputs has necessarily a linear PCM format
7503 // so we can call selectOutput() safely
7504 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7505 client->flags(),
7506 client->config().format,
7507 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007508 client->config().sample_rate,
7509 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007510 if (newOutput != srcOut) {
7511 invalidate = true;
7512 break;
7513 }
7514 } else {
7515 sp<IOProfile> profile = getProfileForOutput(newDevices,
7516 client->config().sample_rate,
7517 client->config().format,
7518 client->config().channel_mask,
7519 client->flags(),
7520 true /* directOnly */);
7521 if (profile != desc->mProfile) {
7522 invalidate = true;
7523 break;
7524 }
7525 }
7526 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007527 // mute strategy while moving tracks from one output to another
7528 if (invalidate) {
7529 invalidatedOutputs.push_back(desc);
7530 if (desc->isStrategyActive(psId)) {
7531 setStrategyMute(psId, true, desc);
7532 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7533 newDevices.types());
7534 }
Eric Laurente552edb2014-03-10 17:42:56 -07007535 }
François Gaffiec005e562018-11-06 15:04:49 +01007536 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007537 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007538 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007539 }
Eric Laurente552edb2014-03-10 17:42:56 -07007540 }
7541
Eric Laurent56ed8842022-11-15 16:04:41 +01007542 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7543 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7544 std::to_string(srcOutputs[0]).c_str(),
7545 std::to_string(dstOutputs[0]).c_str());
7546
François Gaffiec005e562018-11-06 15:04:49 +01007547 // Move effects associated to this stream from previous output to new output
7548 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007549 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007550 }
François Gaffiec005e562018-11-06 15:04:49 +01007551 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007552 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007553 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007554 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007555 desc->setTracksInvalidatedStatusByStrategy(psId);
7556 }
Eric Laurente552edb2014-03-10 17:42:56 -07007557 }
7558 }
7559}
7560
Eric Laurente0720872014-03-11 09:30:41 -07007561void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007562{
François Gaffiec005e562018-11-06 15:04:49 +01007563 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7564 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7565 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007566 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007567 }
Eric Laurente552edb2014-03-10 17:42:56 -07007568}
7569
Kevin Rocard153f92d2018-12-18 18:33:28 -08007570void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007571 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007572 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007573 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007574 for (size_t i = 0; i < mOutputs.size(); i++) {
7575 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7576 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007577 sp<AudioPolicyMix> primaryMix;
7578 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007579 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007580 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7581 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7582 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007583 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7584 for (auto &secondaryMix : secondaryMixes) {
7585 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7586 if (outputDesc != nullptr &&
7587 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7588 secondaryDescs.push_back(outputDesc);
7589 }
7590 }
7591
jiabinc44b3462022-12-08 12:52:31 -08007592 if (status != OK &&
7593 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7594 // When it failed to query secondary output, only invalidate the client that is not
7595 // MMAP. The reason is that MMAP stream will not support secondary output.
7596 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007597 } else if (!std::equal(
7598 client->getSecondaryOutputs().begin(),
7599 client->getSecondaryOutputs().end(),
7600 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007601 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7602 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007603 // If the format is not PCM, the tracks should be invalidated to get correct
7604 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007605 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007606 } else {
7607 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7608 std::vector<audio_io_handle_t> secondaryOutputIds;
7609 for (const auto &secondaryDesc: secondaryDescs) {
7610 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7611 weakSecondaryDescs.push_back(secondaryDesc);
7612 }
7613 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7614 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007615 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007616 }
7617 }
7618 }
jiabin10a03f12021-05-07 23:46:28 +00007619 if (!trackSecondaryOutputs.empty()) {
7620 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7621 }
jiabinc44b3462022-12-08 12:52:31 -08007622 if (!clientsToInvalidate.empty()) {
7623 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7624 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007625 }
7626}
7627
Eric Laurent2517af32020-11-25 15:31:27 +01007628bool AudioPolicyManager::isScoRequestedForComm() const {
7629 AudioDeviceTypeAddrVector devices;
7630 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7631 for (const auto &device : devices) {
7632 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7633 return true;
7634 }
7635 }
7636 return false;
7637}
7638
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007639bool AudioPolicyManager::isHearingAidUsedForComm() const {
7640 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7641 true /*fromCache*/);
7642 for (const auto &device : devices) {
7643 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7644 return true;
7645 }
7646 }
7647 return false;
7648}
7649
7650
Eric Laurente0720872014-03-11 09:30:41 -07007651void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007652{
François Gaffie53615e22015-03-19 09:24:12 +01007653 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007654 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007655 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007656 return;
7657 }
7658
Eric Laurent3a4311c2014-03-17 12:00:47 -07007659 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007660 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7661 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007662 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007663
7664 // if suspended, restore A2DP output if:
7665 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007666 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007667 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007668 //
Eric Laurentf732e072016-08-03 19:30:28 -07007669 // if not suspended, suspend A2DP output if:
7670 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007671 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007672 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007673 //
7674 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007675 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007676 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007677 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007678 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007679
7680 mpClientInterface->restoreOutput(a2dpOutput);
7681 mA2dpSuspended = false;
7682 }
7683 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007684 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007685 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007686 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007687 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007688
7689 mpClientInterface->suspendOutput(a2dpOutput);
7690 mA2dpSuspended = true;
7691 }
7692 }
7693}
7694
François Gaffie11d30102018-11-02 16:09:09 +01007695DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7696 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007697{
François Gaffiedb1755b2023-09-01 11:50:35 +02007698 if (outputDesc == nullptr) {
7699 return DeviceVector{};
7700 }
François Gaffie11d30102018-11-02 16:09:09 +01007701
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007702 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007703 if (index >= 0) {
7704 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007705 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007706 ALOGV("%s device %s forced by patch %d", __func__,
7707 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7708 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007709 }
7710 }
7711
Dean Wheatley514b4312020-06-17 21:45:00 +10007712 // Do not retrieve engine device for outputs through MSD
7713 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7714 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7715 return outputDesc->devices();
7716 }
7717
Eric Laurent97ac8712018-07-27 18:59:02 -07007718 // Honor explicit routing requests only if no client using default routing is active on this
7719 // input: a specific app can not force routing for other apps by setting a preferred device.
7720 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007721 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007722 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007723 if (device != nullptr) {
7724 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007725 }
7726
François Gaffiea807ef92018-11-05 10:44:33 +01007727 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7728 // of setForceUse / Default Bus device here
7729 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7730 if (device != nullptr) {
7731 return DeviceVector(device);
7732 }
7733
François Gaffiedb1755b2023-09-01 11:50:35 +02007734 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007735 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7736 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307737 auto hasStreamActive = [&](auto stream) {
7738 return hasStream(streams, stream) && isStreamActive(stream, 0);
7739 };
Eric Laurent484e9272018-06-07 17:29:23 -07007740
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307741 auto doGetOutputDevicesForVoice = [&]() {
7742 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007743 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307744 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007745 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7746 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307747 };
7748
7749 // With low-latency playing on speaker, music on WFD, when the first low-latency
7750 // output is stopped, getNewOutputDevices checks for a product strategy
7751 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007752 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307753 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7754 // stream is associated to the output descriptor.
7755 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7756 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7757 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7758 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007759 // Retrieval of devices for voice DL is done on primary output profile, cannot
7760 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007761 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007762 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7763 break;
7764 }
Eric Laurente552edb2014-03-10 17:42:56 -07007765 }
François Gaffiec005e562018-11-06 15:04:49 +01007766 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007767 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007768}
7769
François Gaffie11d30102018-11-02 16:09:09 +01007770sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7771 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007772{
François Gaffie11d30102018-11-02 16:09:09 +01007773 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007774
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007775 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007776 if (index >= 0) {
7777 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007778 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007779 ALOGV("getNewInputDevice() device %s forced by patch %d",
7780 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7781 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007782 }
7783 }
7784
Eric Laurent97ac8712018-07-27 18:59:02 -07007785 // Honor explicit routing requests only if no client using default routing is active on this
7786 // input: a specific app can not force routing for other apps by setting a preferred device.
7787 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007788 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7789 if (device != nullptr) {
7790 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007791 }
7792
Eric Laurentdc95a252018-04-12 12:46:56 -07007793 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007794 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007795 audio_attributes_t attributes;
7796 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007797 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007798 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7799 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007800 attributes = topClient->attributes();
7801 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007802 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007803 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007804 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7805 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007806 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007807 }
7808
Francois Gaffie716e1432019-01-14 16:58:59 +01007809 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7810 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007811 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007812 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007813 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007814 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007815
Eric Laurente552edb2014-03-10 17:42:56 -07007816 return device;
7817}
7818
Eric Laurent794fde22016-03-11 09:50:45 -08007819bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7820 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007821 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007822}
7823
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007824status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007825 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007826 if (devices == nullptr) {
7827 return BAD_VALUE;
7828 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007829
Andy Hung6d23c0f2022-02-16 09:37:15 -08007830 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007831 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7832 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007833 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007834 for (const auto& device : curDevices) {
7835 devices->push_back(device->getDeviceTypeAddr());
7836 }
7837 return NO_ERROR;
7838}
7839
Eric Laurente0720872014-03-11 09:30:41 -07007840void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007841 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007842 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007843 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007844 updateDevicesAndOutputs();
7845 break;
7846 default:
7847 break;
7848 }
7849}
7850
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007851uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007852
7853 // skip beacon mute management if a dedicated TTS output is available
7854 if (mTtsOutputAvailable) {
7855 return 0;
7856 }
7857
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007858 switch(event) {
7859 case STARTING_OUTPUT:
7860 mBeaconMuteRefCount++;
7861 break;
7862 case STOPPING_OUTPUT:
7863 if (mBeaconMuteRefCount > 0) {
7864 mBeaconMuteRefCount--;
7865 }
7866 break;
7867 case STARTING_BEACON:
7868 mBeaconPlayingRefCount++;
7869 break;
7870 case STOPPING_BEACON:
7871 if (mBeaconPlayingRefCount > 0) {
7872 mBeaconPlayingRefCount--;
7873 }
7874 break;
7875 }
7876
7877 if (mBeaconMuteRefCount > 0) {
7878 // any playback causes beacon to be muted
7879 return setBeaconMute(true);
7880 } else {
7881 // no other playback: unmute when beacon starts playing, mute when it stops
7882 return setBeaconMute(mBeaconPlayingRefCount == 0);
7883 }
7884}
7885
7886uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7887 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7888 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7889 // keep track of muted state to avoid repeating mute/unmute operations
7890 if (mBeaconMuted != mute) {
7891 // mute/unmute AUDIO_STREAM_TTS on all outputs
7892 ALOGV("\t muting %d", mute);
7893 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007894 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7895 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7896 ALOGV("\t no tts volume source available");
7897 return 0;
7898 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007899 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007900 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007901 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007902 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007903 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007904 maxLatency = latency;
7905 }
7906 }
7907 mBeaconMuted = mute;
7908 return maxLatency;
7909 }
7910 return 0;
7911}
7912
Eric Laurente0720872014-03-11 09:30:41 -07007913void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007914{
François Gaffiec005e562018-11-06 15:04:49 +01007915 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007916 mPreviousOutputs = mOutputs;
7917}
7918
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007919uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007920 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007921 uint32_t delayMs)
7922{
7923 // mute/unmute strategies using an incompatible device combination
7924 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7925 // if unmuting, unmute only after the specified delay
7926 if (outputDesc->isDuplicated()) {
7927 return 0;
7928 }
7929
7930 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007931 DeviceVector devices = outputDesc->devices();
7932 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007933
François Gaffiec005e562018-11-06 15:04:49 +01007934 auto productStrategies = mEngine->getOrderedProductStrategies();
7935 for (const auto &productStrategy : productStrategies) {
7936 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7937 DeviceVector curDevices =
7938 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7939 curDevices = curDevices.filter(outputDesc->supportedDevices());
7940 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007941 bool doMute = false;
7942
François Gaffiec005e562018-11-06 15:04:49 +01007943 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007944 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007945 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7946 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007947 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007948 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007949 }
Eric Laurent99401132014-05-07 19:48:15 -07007950 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007951 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007952 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007953 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007954 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007955 continue;
7956 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307957 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007958 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7959 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7960 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007961 if (mute) {
7962 // FIXME: should not need to double latency if volume could be applied
7963 // immediately by the audioflinger mixer. We must account for the delay
7964 // between now and the next time the audioflinger thread for this output
7965 // will process a buffer (which corresponds to one buffer size,
7966 // usually 1/2 or 1/4 of the latency).
7967 if (muteWaitMs < desc->latency() * 2) {
7968 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007969 }
7970 }
7971 }
7972 }
7973 }
7974 }
7975
Eric Laurent99401132014-05-07 19:48:15 -07007976 // temporary mute output if device selection changes to avoid volume bursts due to
7977 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007978 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007979 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007980
Eric Laurentdc462862016-07-19 12:29:53 -07007981 if (muteWaitMs < tempMuteWaitMs) {
7982 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007983 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007984
7985 // If recommended duration is defined, replace temporary mute duration to avoid
7986 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7987 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7988 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7989 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7990 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7991
François Gaffieaaac0fd2018-11-22 17:56:39 +01007992 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7993 // make sure that we do not start the temporary mute period too early in case of
7994 // delayed device change
7995 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7996 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007997 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007998 }
7999 }
8000
Eric Laurente552edb2014-03-10 17:42:56 -07008001 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8002 if (muteWaitMs > delayMs) {
8003 muteWaitMs -= delayMs;
8004 usleep(muteWaitMs * 1000);
8005 return muteWaitMs;
8006 }
8007 return 0;
8008}
8009
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308010uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8011 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008012 const DeviceVector &devices,
8013 bool force,
8014 int delayMs,
8015 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008016 bool requiresMuteCheck, bool requiresVolumeCheck,
8017 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008018{
jiabin3ff8d7d2022-12-13 06:27:44 +00008019 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308020 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8021 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8022 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008023 uint32_t muteWaitMs;
8024
8025 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308026 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008027 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308028 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008029 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008030 return muteWaitMs;
8031 }
Eric Laurente552edb2014-03-10 17:42:56 -07008032
8033 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008034 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008035 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008036 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008037
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308038 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8039 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008040
8041 if (!filteredDevices.isEmpty()) {
8042 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008043 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008044
8045 // if the outputs are not materially active, there is no need to mute.
8046 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008047 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008048 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308049 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8050 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008051 muteWaitMs = 0;
8052 }
Eric Laurente552edb2014-03-10 17:42:56 -07008053
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008054 bool outputRouted = outputDesc->isRouted();
8055
Eric Laurent79ea9582020-06-11 18:49:24 -07008056 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8057 // output profile or if new device is not supported AND previous device(s) is(are) still
8058 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008059 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308060 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8061 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008062 // restore previous device after evaluating strategy mute state
8063 outputDesc->setDevices(prevDevices);
8064 return muteWaitMs;
8065 }
8066
Eric Laurente552edb2014-03-10 17:42:56 -07008067 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008068 // the requested device is AUDIO_DEVICE_NONE
8069 // OR the requested device is the same as current device
8070 // AND force is not specified
8071 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008072 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008073 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308074 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8075 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8076 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008077 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308078 ALOGV("%s %s setting same device on routed output, force apply volumes",
8079 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008080 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8081 }
Eric Laurente552edb2014-03-10 17:42:56 -07008082 return muteWaitMs;
8083 }
8084
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308085 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8086 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008087
Eric Laurente552edb2014-03-10 17:42:56 -07008088 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008089 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008090 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008091 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008092 PatchBuilder patchBuilder;
8093 patchBuilder.addSource(outputDesc);
8094 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8095 for (const auto &filteredDevice : filteredDevices) {
8096 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008097 }
8098
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008099 // Add half reported latency to delayMs when muteWaitMs is null in order
8100 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008101 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8102 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8103 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008104 }
Eric Laurente552edb2014-03-10 17:42:56 -07008105
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008106 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8107 if (!skipMuteDelay) {
8108 // update stream volumes according to new device
8109 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8110 }
Eric Laurente552edb2014-03-10 17:42:56 -07008111
8112 return muteWaitMs;
8113}
8114
Eric Laurentc75307b2015-03-17 15:29:32 -07008115status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008116 int delayMs,
8117 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008118{
Eric Laurent6a94d692014-05-20 11:18:06 -07008119 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008120 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8121 return INVALID_OPERATION;
8122 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008123 if (patchHandle) {
8124 index = mAudioPatches.indexOfKey(*patchHandle);
8125 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008126 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008127 }
8128 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008129 return INVALID_OPERATION;
8130 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008131 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008132 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008133 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008134 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008135 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008136 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008137 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008138 return status;
8139}
8140
8141status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008142 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008143 bool force,
8144 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008145{
8146 status_t status = NO_ERROR;
8147
Eric Laurent1f2f2232014-06-02 12:01:23 -07008148 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008149 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8150 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008151
François Gaffie11d30102018-11-02 16:09:09 +01008152 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008153 PatchBuilder patchBuilder;
8154 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008155 // AUDIO_SOURCE_HOTWORD is for internal use only:
8156 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008157 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8158 auto result = usecase;
8159 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8160 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8161 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008162 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008163 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008164 if (audio_is_remote_submix_device(device->type())) {
8165 // remote submix HAL does not support audio conversion, need source device
8166 // audio config to match the sink input descriptor audio config, otherwise AIDL
8167 // HAL patching will fail
8168 audio_port_config srcDevicePortConfig = {};
8169 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8170 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8171 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8172 srcDevicePortConfig.format = inputDesc->getFormat();
8173 patchBuilder.addSource(srcDevicePortConfig);
8174 } else {
8175 patchBuilder.addSource(device);
8176 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008177 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008178 }
8179 }
8180 return status;
8181}
8182
Eric Laurent6a94d692014-05-20 11:18:06 -07008183status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8184 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008185{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008186 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008187 ssize_t index;
8188 if (patchHandle) {
8189 index = mAudioPatches.indexOfKey(*patchHandle);
8190 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008191 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008192 }
8193 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008194 return INVALID_OPERATION;
8195 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008196 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008197 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008198 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008199 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008200 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008201 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008202 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008203 return status;
8204}
8205
François Gaffie11d30102018-11-02 16:09:09 +01008206sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008207 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008208 audio_format_t& format,
8209 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008210 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008211{
8212 // Choose an input profile based on the requested capture parameters: select the first available
8213 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008214 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008215
Atneya Nair0f0a8032022-12-12 16:20:12 -08008216 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8217 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8218 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8219
8220 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008221
jiabin2fd710d2022-05-02 23:20:22 +00008222 for (;;) {
8223 sp<IOProfile> firstInexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008224 uint32_t inexactSamplingRate = 0;
8225 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8226 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008227 uint32_t updatedSamplingRate = 0;
8228 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8229 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8230 for (const auto& hwModule : mHwModules) {
8231 for (const auto& profile : hwModule->getInputProfiles()) {
8232 // profile->log();
8233 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008234 if (profile->getCompatibilityScore(
8235 DeviceVector(device),
8236 samplingRate,
8237 &updatedSamplingRate,
8238 format,
8239 &updatedFormat,
8240 channelMask,
8241 &updatedChannelMask,
8242 // FIXME ugly cast
8243 (audio_output_flags_t) flags,
8244 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8245 samplingRate = updatedSamplingRate;
8246 format = updatedFormat;
8247 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008248 return profile;
8249 }
jiabin66acc432024-02-06 00:57:36 +00008250 if (firstInexact == nullptr
8251 && profile->getCompatibilityScore(
8252 DeviceVector(device),
8253 samplingRate,
8254 &updatedSamplingRate,
8255 format,
8256 &updatedFormat,
8257 channelMask,
8258 &updatedChannelMask,
8259 // FIXME ugly cast
8260 (audio_output_flags_t) flags,
8261 false /*exactMatchRequiredForInputFlags*/)
8262 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008263 firstInexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008264 inexactSamplingRate = updatedSamplingRate;
8265 inexactFormat = updatedFormat;
8266 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008267 }
8268 }
8269 }
8270
8271 if (firstInexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008272 samplingRate = inexactSamplingRate;
8273 format = inexactFormat;
8274 channelMask = inexactChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008275 return firstInexact;
8276 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8277 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8278 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8279 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8280 flags = AUDIO_INPUT_FLAG_NONE;
8281 } else { // fail
8282 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8283 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8284 samplingRate, format, channelMask, oriFlags);
8285 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008286 }
8287 }
jiabin2fd710d2022-05-02 23:20:22 +00008288
8289 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008290}
8291
Vlad Popa87e0e582024-05-20 18:49:20 -07008292float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8293 VolumeSource volumeSource,
8294 int index,
8295 const DeviceTypeSet &deviceTypes)
8296{
8297 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8298 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8299 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8300
8301 if (com_android_media_audio_abs_volume_index_fix()) {
8302 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8303 mAbsoluteVolumeDrivingStreams.end()) {
8304 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8305 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8306 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8307 ALOGD("%s: no group matching with %s", __FUNCTION__,
8308 toString(attributesToDriveAbs).c_str());
8309 return volumeDb;
8310 }
8311
8312 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8313 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8314 if (vsToDriveAbs == volumeSource) {
8315 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008316 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008317 } else {
8318 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8319 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8320 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8321 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8322 curvesAbs.getVolumeIndexMax());
8323 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8324 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8325 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8326 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8327 return newVolumeDb;
8328 }
8329 }
8330 return volumeDb;
8331 } else {
8332 return volumeDb;
8333 }
8334}
8335
François Gaffieaaac0fd2018-11-22 17:56:39 +01008336float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8337 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008338 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008339 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008340 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008341 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008342{
Vlad Popa9d482762024-06-21 16:40:23 -07008343 float volumeDb;
8344 if (adjustAttenuation) {
8345 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8346 } else {
8347 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8348 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008349 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8350 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8351
8352 if (!computeInternalInteraction) {
8353 return volumeDb;
8354 }
8355
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008356 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8357 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8358 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8359 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008360 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8361 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8362 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8363 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8364 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008365 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008366 mOutputs.isActive(ringVolumeSrc, 0)) {
8367 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008368 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008369 adjustAttenuation,
8370 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008371 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008372 }
8373
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008374 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008375 if ((volumeSource != callVolumeSrc && (isInCall() ||
8376 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008377 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008378 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8379 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008380 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8381 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8382 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008383 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008384 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008385 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008386 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008387 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008388 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008389 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008390 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8391 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8392 // programmatically muted.
8393 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8394 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8395 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008396 bool exemptFromCapping =
8397 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8398 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008399 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8400 volumeSource, volumeDb);
8401 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008402 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8403 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8404 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008405 }
8406 }
Eric Laurente552edb2014-03-10 17:42:56 -07008407 // if a headset is connected, apply the following rules to ring tones and notifications
8408 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008409 // - always attenuate notifications volume by 6dB
8410 // - attenuate ring tones volume by 6dB unless music is not playing and
8411 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008412 // - if music is playing, always limit the volume to current music volume,
8413 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008414 if (!Intersection(deviceTypes,
8415 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8416 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008417 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8418 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008419 ((volumeSource == alarmVolumeSrc ||
8420 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008421 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8422 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8423 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008424 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8425 curves.canBeMuted()) {
8426
Eric Laurente552edb2014-03-10 17:42:56 -07008427 // when the phone is ringing we must consider that music could have been paused just before
8428 // by the music application and behave as if music was active if the last music track was
8429 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008430 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8431 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008432 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008433 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008434 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8435 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008436 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008437 float musicVolDb = computeVolume(musicCurves,
8438 musicVolumeSrc,
8439 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008440 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008441 adjustAttenuation,
8442 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008443 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8444 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8445 if (volumeDb > minVolDb) {
8446 volumeDb = minVolDb;
8447 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008448 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008449 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8450 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008451 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8452 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8453 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8454 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008455 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008456 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008457 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8458 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008459 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8460 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008461 }
8462 }
jiabin9a3361e2019-10-01 09:38:30 -07008463 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008464 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008465 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008466 }
8467 }
8468
François Gaffie43c73442018-11-08 08:21:55 +01008469 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008470}
8471
Eric Laurent3839bc02018-07-10 18:33:34 -07008472int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008473 VolumeSource fromVolumeSource,
8474 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008475{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008476 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008477 return srcIndex;
8478 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008479 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8480 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008481 float minSrc = (float)srcCurves.getVolumeIndexMin();
8482 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8483 float minDst = (float)dstCurves.getVolumeIndexMin();
8484 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008485
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008486 // preserve mute request or correct range
8487 if (srcIndex < minSrc) {
8488 if (srcIndex == 0) {
8489 return 0;
8490 }
8491 srcIndex = minSrc;
8492 } else if (srcIndex > maxSrc) {
8493 srcIndex = maxSrc;
8494 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008495 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8496}
8497
François Gaffieaaac0fd2018-11-22 17:56:39 +01008498status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8499 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008500 int index,
8501 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008502 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008503 int delayMs,
8504 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008505{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008506 // APM is single threaded, and single instance.
8507 static std::set<IVolumeCurves*> invalidCurvesReported;
8508
François Gaffieaaac0fd2018-11-22 17:56:39 +01008509 // do not change actual attributes volume if the attributes is muted
8510 if (outputDesc->isMuted(volumeSource)) {
8511 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8512 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008513 return NO_ERROR;
8514 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008515
Eric Laurentae6e88c2024-01-10 14:42:57 +01008516 bool isVoiceVolSrc;
8517 bool isBtScoVolSrc;
8518 if (!isVolumeConsistentForCalls(
8519 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008520 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008521 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008522 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008523 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008524
jiabin9a3361e2019-10-01 09:38:30 -07008525 if (deviceTypes.empty()) {
8526 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008527 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008528 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008529 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008530 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008531
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008532 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008533 if (!invalidCurvesReported.count(&curves)) {
8534 invalidCurvesReported.insert(&curves);
8535 String8 dump;
8536 curves.dump(&dump);
8537 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8538 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008539 return BAD_VALUE;
8540 }
8541
jiabin9a3361e2019-10-01 09:38:30 -07008542 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8543 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008544 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008545 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008546 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8547 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008548 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008549 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008550 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008551 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8552 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008553
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008554 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008555 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8556 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8557 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008558 }
Eric Laurente552edb2014-03-10 17:42:56 -07008559 return NO_ERROR;
8560}
8561
Eric Laurentae6e88c2024-01-10 14:42:57 +01008562void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008563 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008564 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008565 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008566 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008567 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008568 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8569 } else {
8570 voiceVolume = index == 0 ? 0.0 : 1.0;
8571 }
8572 if (voiceVolume != mLastVoiceVolume) {
8573 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8574 mLastVoiceVolume = voiceVolume;
8575 }
8576}
8577
8578bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8579 const DeviceTypeSet& deviceTypes,
8580 bool& isVoiceVolSrc,
8581 bool& isBtScoVolSrc,
8582 const char* caller) {
8583 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008584 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8585
Eric Laurentae6e88c2024-01-10 14:42:57 +01008586 const bool isScoRequested = isScoRequestedForComm();
8587 const bool isHAUsed = isHearingAidUsedForComm();
8588
Vlad Popa695b76b2024-06-14 16:49:25 -07008589 if (com_android_media_audio_replace_stream_bt_sco()) {
8590 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8591 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8592 (isScoRequested || isHAUsed);
8593 return true;
8594 }
8595
8596 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008597 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8598
8599 if ((callVolSrc != btScoVolSrc) &&
8600 ((isVoiceVolSrc && isScoRequested) ||
8601 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8602 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8603 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8604 volumeSource, isScoRequested ? " " : " not ");
8605 return false;
8606 }
8607 return true;
8608}
8609
Eric Laurentc75307b2015-03-17 15:29:32 -07008610void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008611 const DeviceTypeSet& deviceTypes,
8612 int delayMs,
8613 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008614{
jiabincd510522020-01-22 09:40:55 -08008615 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008616 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8617 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8618 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008619 curves.getVolumeIndex(deviceTypes),
8620 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008621 }
8622}
8623
François Gaffiec005e562018-11-06 15:04:49 +01008624void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8625 bool on,
8626 const sp<AudioOutputDescriptor>& outputDesc,
8627 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008628 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008629{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008630 std::vector<VolumeSource> sourcesToMute;
8631 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8632 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8633 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008634 VolumeSource source = toVolumeSource(attributes, false);
8635 if ((source != VOLUME_SOURCE_NONE) &&
8636 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8637 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008638 sourcesToMute.push_back(source);
8639 }
Eric Laurente552edb2014-03-10 17:42:56 -07008640 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008641 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008642 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008643 }
8644
Eric Laurente552edb2014-03-10 17:42:56 -07008645}
8646
François Gaffieaaac0fd2018-11-22 17:56:39 +01008647void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8648 bool on,
8649 const sp<AudioOutputDescriptor>& outputDesc,
8650 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008651 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008652{
jiabin9a3361e2019-10-01 09:38:30 -07008653 if (deviceTypes.empty()) {
8654 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008655 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008656 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008657 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008658 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008659 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008660 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008661 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8662 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008663 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008664 }
8665 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008666 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8667 // ignored
8668 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008669 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008670 if (!outputDesc->isMuted(volumeSource)) {
8671 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008672 return;
8673 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008674 if (outputDesc->decMuteCount(volumeSource) == 0) {
8675 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008676 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008677 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008678 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008679 delayMs);
8680 }
8681 }
8682}
8683
François Gaffie53615e22015-03-19 09:24:12 +01008684bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8685{
François Gaffiec005e562018-11-06 15:04:49 +01008686 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008687 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8688 return true;
8689 }
8690
8691 // has known usage?
8692 switch (paa->usage) {
8693 case AUDIO_USAGE_UNKNOWN:
8694 case AUDIO_USAGE_MEDIA:
8695 case AUDIO_USAGE_VOICE_COMMUNICATION:
8696 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8697 case AUDIO_USAGE_ALARM:
8698 case AUDIO_USAGE_NOTIFICATION:
8699 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8700 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8701 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8702 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8703 case AUDIO_USAGE_NOTIFICATION_EVENT:
8704 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8705 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8706 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8707 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008708 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008709 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008710 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008711 case AUDIO_USAGE_EMERGENCY:
8712 case AUDIO_USAGE_SAFETY:
8713 case AUDIO_USAGE_VEHICLE_STATUS:
8714 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008715 break;
8716 default:
8717 return false;
8718 }
8719 return true;
8720}
8721
François Gaffie2110e042015-03-24 08:41:51 +01008722audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8723{
8724 return mEngine->getForceUse(usage);
8725}
8726
Eric Laurent96d1dda2022-03-14 17:14:19 +01008727bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008728 return isStateInCall(mEngine->getPhoneState());
8729}
8730
Eric Laurent96d1dda2022-03-14 17:14:19 +01008731bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008732 return is_state_in_call(state);
8733}
8734
Eric Laurentf9cccec2022-11-16 19:12:00 +01008735bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008736 audio_mode_t mode = mEngine->getPhoneState();
8737 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008738 || (mode == AUDIO_MODE_CALL_SCREEN)
8739 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008740}
8741
Eric Laurentf9cccec2022-11-16 19:12:00 +01008742bool AudioPolicyManager::isInCallOrScreening() const {
8743 audio_mode_t mode = mEngine->getPhoneState();
8744 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8745}
8746
Eric Laurentd60560a2015-04-10 11:31:20 -07008747void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8748{
8749 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008750 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008751 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008752 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008753 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008754 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008755 }
8756 }
8757
8758 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8759 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8760 bool release = false;
8761 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8762 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8763 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8764 source->ext.device.type == deviceDesc->type()) {
8765 release = true;
8766 }
8767 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008768 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008769 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8770 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8771 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008772 sink->ext.device.type == deviceDesc->type() &&
8773 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8774 || strncmp(sink->ext.device.address, address,
8775 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008776 release = true;
8777 }
8778 }
8779 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008780 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8781 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008782 }
8783 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008784
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008785 mInputs.clearSessionRoutesForDevice(deviceDesc);
8786
Francois Gaffie716e1432019-01-14 16:58:59 +01008787 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008788}
8789
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008790void AudioPolicyManager::modifySurroundFormats(
8791 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008792 std::unordered_set<audio_format_t> enforcedSurround(
8793 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008794 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008795 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008796 allSurround.insert(pair.first);
8797 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8798 }
Phil Burk09bc4612016-02-24 15:58:15 -08008799
8800 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8801 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008802 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008803 // This is the resulting set of formats depending on the surround mode:
8804 // 'all surround' = allSurround
8805 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8806 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8807 // 'manual surround' = mManualSurroundFormats
8808 // AUTO: formats v 'enforced surround'
8809 // ALWAYS: formats v 'all surround' v 'enforced surround'
8810 // NEVER: formats ^ 'non-surround'
8811 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008812
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008813 std::unordered_set<audio_format_t> formatSet;
8814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8815 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008816 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008817 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008818 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008819 formatSet.insert(*formatIter);
8820 }
8821 }
8822 } else {
8823 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8824 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008825 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008826
jiabin81772902018-04-02 17:52:27 -07008827 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008828 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008829 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8830 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8831 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008832 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008833 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8834 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8835 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008836 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008837 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008838 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008839 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008840 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008841 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008842}
8843
jiabin06e4bab2019-07-29 10:13:34 -07008844void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8845 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008846 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8847 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8848
8849 // If NEVER, then remove support for channelMasks > stereo.
8850 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008851 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8852 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008853 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008854 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008855 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008856 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008857 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008858 }
8859 }
jiabin81772902018-04-02 17:52:27 -07008860 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8861 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8862 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008863 bool supports5dot1 = false;
8864 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008865 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008866 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8867 supports5dot1 = true;
8868 break;
8869 }
8870 }
8871 // If not then add 5.1 support.
8872 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008873 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008874 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008875 }
Phil Burk09bc4612016-02-24 15:58:15 -08008876 }
8877}
8878
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008879void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008880 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008881 const sp<IOProfile>& profile) {
8882 if (!profile->hasDynamicAudioProfile()) {
8883 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008884 }
François Gaffie112b0af2015-11-19 16:13:25 +01008885
jiabin12537fc2023-10-12 17:56:08 +00008886 audio_port_v7 devicePort;
8887 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008888
jiabin12537fc2023-10-12 17:56:08 +00008889 audio_port_v7 mixPort;
8890 profile->toAudioPort(&mixPort);
8891 mixPort.ext.mix.handle = ioHandle;
8892
8893 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8894 if (status != NO_ERROR) {
8895 ALOGE("%s failed to query the attributes of the mix port", __func__);
8896 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008897 }
jiabin12537fc2023-10-12 17:56:08 +00008898
8899 std::set<audio_format_t> supportedFormats;
8900 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8901 supportedFormats.insert(mixPort.audio_profiles[i].format);
8902 }
8903 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8904 mReportedFormatsMap[devDesc] = formats;
8905
8906 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008907 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8908 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008909 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8910 modifySurroundFormats(devDesc, &formats);
8911 size_t modifiedNumProfiles = 0;
8912 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8913 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8914 formats.end()) {
8915 // Skip the format that is not present after modifying surround formats.
8916 continue;
8917 }
8918 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8919 sizeof(struct audio_profile));
8920 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8921 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8922 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8923 modifySurroundChannelMasks(&channels);
8924 std::copy(channels.begin(), channels.end(),
8925 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8926 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8927 }
8928 mixPort.num_audio_profiles = modifiedNumProfiles;
8929 }
8930 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008931}
Eric Laurentd60560a2015-04-10 11:31:20 -07008932
Mikhail Naganovdc769682018-05-04 15:34:08 -07008933status_t AudioPolicyManager::installPatch(const char *caller,
8934 audio_patch_handle_t *patchHandle,
8935 AudioIODescriptorInterface *ioDescriptor,
8936 const struct audio_patch *patch,
8937 int delayMs)
8938{
8939 ssize_t index = mAudioPatches.indexOfKey(
8940 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8941 *patchHandle : ioDescriptor->getPatchHandle());
8942 sp<AudioPatch> patchDesc;
8943 status_t status = installPatch(
8944 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8945 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008946 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008947 }
8948 return status;
8949}
8950
8951status_t AudioPolicyManager::installPatch(const char *caller,
8952 ssize_t index,
8953 audio_patch_handle_t *patchHandle,
8954 const struct audio_patch *patch,
8955 int delayMs,
8956 uid_t uid,
8957 sp<AudioPatch> *patchDescPtr)
8958{
8959 sp<AudioPatch> patchDesc;
8960 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8961 if (index >= 0) {
8962 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008963 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008964 }
8965
8966 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8967 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8968 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8969 if (status == NO_ERROR) {
8970 if (index < 0) {
8971 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008972 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008973 } else {
8974 patchDesc->mPatch = *patch;
8975 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008976 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008977 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008978 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008979 }
8980 nextAudioPortGeneration();
8981 mpClientInterface->onAudioPatchListUpdate();
8982 }
8983 if (patchDescPtr) *patchDescPtr = patchDesc;
8984 return status;
8985}
8986
jiabinbce0c1d2020-10-05 11:20:18 -07008987bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8988{
8989 const TrackClientVector activeClients = output->getActiveClients();
8990 if (activeClients.empty()) {
8991 return true;
8992 }
8993 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8994 if (index < 0) {
8995 ALOGE("%s, no audio patch found while there are active clients on output %d",
8996 __func__, output->getId());
8997 return false;
8998 }
8999 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9000 DeviceVector routedDevices;
9001 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9002 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9003 patchDesc->mPatch.sinks[i].id);
9004 if (device == nullptr) {
9005 ALOGE("%s, no audio device found with id(%d)",
9006 __func__, patchDesc->mPatch.sinks[i].id);
9007 return false;
9008 }
9009 routedDevices.add(device);
9010 }
9011 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009012 if (client->isInvalid()) {
9013 // No need to take care about invalidated clients.
9014 continue;
9015 }
jiabinbce0c1d2020-10-05 11:20:18 -07009016 sp<DeviceDescriptor> preferredDevice =
9017 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9018 if (mEngine->getOutputDevicesForAttributes(
9019 client->attributes(), preferredDevice, false) == routedDevices) {
9020 return false;
9021 }
9022 }
9023 return true;
9024}
9025
9026sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009027 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009028 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9029 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009030{
9031 for (const auto& device : devices) {
9032 // TODO: This should be checking if the profile supports the device combo.
9033 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009034 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9035 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009036 return nullptr;
9037 }
9038 }
9039 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9040 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009041 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009042 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009043 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009044 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009045 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009046 return nullptr;
9047 }
jiabin14b50cc2023-12-13 19:01:52 +00009048 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9049 auto portConfig = desc->getConfig();
9050 for (const auto& device : devices) {
9051 device->setPreferredConfig(&portConfig);
9052 }
9053 }
jiabinbce0c1d2020-10-05 11:20:18 -07009054
9055 // Here is where the out_set_parameters() for card & device gets called
9056 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9057 const audio_devices_t deviceType = device->type();
9058 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009059 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009060 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9061 mpClientInterface->setParameters(output, String8(param));
9062 free(param);
9063 }
jiabin12537fc2023-10-12 17:56:08 +00009064 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009065 if (!profile->hasValidAudioProfile()) {
9066 ALOGW("%s() missing param", __func__);
9067 desc->close();
9068 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009069 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9070 // Reopen the output with the best audio profile picked by APM when the profile supports
9071 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009072 desc->close();
9073 output = AUDIO_IO_HANDLE_NONE;
9074 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9075 profile->pickAudioProfile(
9076 config.sample_rate, config.channel_mask, config.format);
9077 config.offload_info.sample_rate = config.sample_rate;
9078 config.offload_info.channel_mask = config.channel_mask;
9079 config.offload_info.format = config.format;
9080
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009081 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009082 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009083 if (status != NO_ERROR) {
9084 return nullptr;
9085 }
9086 }
9087
9088 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009089 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9090 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9091 hwModule->getHalVersionMajor() >= 3) {
9092 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9093 }
baek.kim -61c20122022-07-27 10:05:32 +00009094 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9095 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9096
jiabinbce0c1d2020-10-05 11:20:18 -07009097 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9098 sp<AudioPolicyMix> policyMix;
9099 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9100 policyMix->setOutput(desc);
9101 desc->mPolicyMix = policyMix;
9102 } else {
9103 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009104 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009105 }
9106
baek.kim -61c20122022-07-27 10:05:32 +00009107 } else if (hasPrimaryOutput() && speaker != nullptr
9108 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009109 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9110 // no duplicated output for:
9111 // - direct outputs
9112 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009113 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009114 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9115
9116 //TODO: configure audio effect output stage here
9117
9118 // open a duplicating output thread for the new output and the primary output
9119 sp<SwAudioOutputDescriptor> dupOutputDesc =
9120 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9121 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9122 if (status == NO_ERROR) {
9123 // add duplicated output descriptor
9124 addOutput(duplicatedOutput, dupOutputDesc);
9125 } else {
9126 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9127 mPrimaryOutput->mIoHandle, output);
9128 desc->close();
9129 removeOutput(output);
9130 nextAudioPortGeneration();
9131 return nullptr;
9132 }
9133 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009134 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9135 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9136 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009137 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009138 }
jiabinbce0c1d2020-10-05 11:20:18 -07009139 return desc;
9140}
9141
jiabinf1c73972022-04-14 16:28:52 -07009142status_t AudioPolicyManager::getDevicesForAttributes(
9143 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009144 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9145 // over any usage or content type also present in attr.
9146 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9147 attr.source != AUDIO_SOURCE_INVALID) {
9148 return getInputDevicesForAttributes(attr, devices);
9149 }
9150
jiabinf1c73972022-04-14 16:28:52 -07009151 // Devices are determined in the following precedence:
9152 //
9153 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9154 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9155 //
9156 // If no such dynamic policy then
9157 // 2) Devices containing an active client using setPreferredDevice
9158 // with same strategy as the attributes.
9159 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9160 //
9161 // If no corresponding active client with setPreferredDevice then
9162 // 3) Devices associated with the strategy determined by the attributes
9163 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9164 //
9165 // See related getOutputForAttrInt().
9166
9167 // check dynamic policies but only for primary descriptors (secondary not used for audible
9168 // audio routing, only used for duplication for playback capture)
9169 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009170 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009171 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009172 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9173 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9174 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009175 if (status != OK) {
9176 return status;
9177 }
9178
9179 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9180 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9181 // as they are unaffected by device/stream volume
9182 // (per SwAudioOutputDescriptor::isFixedVolume()).
9183 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9184 ) {
9185 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9186 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9187 devices.add(deviceDesc);
9188 } else {
9189 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9190 // which selects setPreferredDevice if active. This means forVolume call
9191 // will take an active setPreferredDevice, if such exists.
9192
9193 devices = mEngine->getOutputDevicesForAttributes(
9194 attr, nullptr /* preferredDevice */, false /* fromCache */);
9195 }
9196
9197 if (forVolume) {
9198 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9199 // for single volume control in AudioService (such relationship should exist if
9200 // SPEAKER_SAFE is present).
9201 //
9202 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9203 DeviceVector speakerSafeDevices =
9204 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9205 if (!speakerSafeDevices.isEmpty()) {
9206 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9207 devices.remove(speakerSafeDevices);
9208 }
9209 }
9210
9211 return NO_ERROR;
9212}
9213
wenyu zhang8558a332024-09-09 15:12:48 +00009214status_t AudioPolicyManager::getInputDevicesForAttributes(
9215 const audio_attributes_t &attr, DeviceVector &devices) {
9216 devices = DeviceVector(
9217 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9218 AUDIO_SESSION_NONE,
9219 nullptr /* mix */));
9220 return NO_ERROR;
9221}
9222
jiabinf1c73972022-04-14 16:28:52 -07009223status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9224 AudioProfileVector& audioProfiles,
9225 uint32_t flags,
9226 bool isInput) {
9227 for (const auto& hwModule : mHwModules) {
9228 // the MSD module checks for different conditions
9229 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9230 continue;
9231 }
9232 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9233 : hwModule->getOutputProfiles();
9234 for (const auto& profile : ioProfiles) {
9235 if (!profile->areAllDevicesSupported(devices) ||
9236 !profile->isCompatibleProfileForFlags(
9237 flags, false /*exactMatchRequiredForInputFlags*/)) {
9238 continue;
9239 }
9240 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9241 }
9242 }
9243
9244 if (!isInput) {
9245 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9246 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9247 if (msdModule != nullptr) {
9248 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9249 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9250 for (const auto &profile: msdModule->getOutputProfiles()) {
9251 if (!profile->asAudioPort()->isDirectOutput()) {
9252 continue;
9253 }
9254 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9255 }
9256 } else {
9257 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9258 }
9259 }
9260 }
9261
9262 return NO_ERROR;
9263}
9264
jiabin3ff8d7d2022-12-13 06:27:44 +00009265sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9266 const audio_config_t *config,
9267 audio_output_flags_t flags,
9268 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009269 closeOutput(outputDesc->mIoHandle);
9270 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9271 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9272 if (preferredOutput == nullptr) {
9273 ALOGE("%s failed to reopen output device=%d, caller=%s",
9274 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009275 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009276 return preferredOutput;
9277}
9278
9279void AudioPolicyManager::reopenOutputsWithDevices(
9280 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9281 for (const auto& [output, devices] : outputsToReopen) {
9282 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9283 closeOutput(output);
9284 openOutputWithProfileAndDevice(desc->mProfile, devices);
9285 }
jiabina84c3d32022-12-02 18:59:55 +00009286}
9287
jiabinc44b3462022-12-08 12:52:31 -08009288PortHandleVector AudioPolicyManager::getClientsForStream(
9289 audio_stream_type_t streamType) const {
9290 PortHandleVector clients;
9291 for (size_t i = 0; i < mOutputs.size(); ++i) {
9292 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9293 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9294 }
9295 return clients;
9296}
9297
9298void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9299 PortHandleVector clients;
9300 for (auto stream : streams) {
9301 PortHandleVector clientsForStream = getClientsForStream(stream);
9302 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9303 }
9304 mpClientInterface->invalidateTracks(clients);
9305}
9306
jiabin220eea12024-05-17 17:55:20 +00009307void AudioPolicyManager::updateClientsInternalMute(
9308 const sp<android::SwAudioOutputDescriptor> &desc) {
9309 if (!desc->isBitPerfect() ||
9310 !com::android::media::audioserver::
9311 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9312 // This is only used for bit perfect output now.
9313 return;
9314 }
9315 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9316 bool bitPerfectClientInternalMute = false;
9317 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9318 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9319 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9320 bitPerfectClient = client;
9321 continue;
9322 }
9323 bool muted = false;
9324 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9325 // System sound is muted.
9326 muted = true;
9327 } else {
9328 bitPerfectClientInternalMute = true;
9329 }
9330 if (client->setInternalMute(muted)) {
9331 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9332 if (!result.ok()) {
9333 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9334 continue;
9335 }
9336 media::TrackInternalMuteInfo info;
9337 info.portId = result.value();
9338 info.muted = client->getInternalMute();
9339 clientsInternalMute.push_back(std::move(info));
9340 }
9341 }
9342 if (bitPerfectClient != nullptr &&
9343 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9344 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9345 if (result.ok()) {
9346 media::TrackInternalMuteInfo info;
9347 info.portId = result.value();
9348 info.muted = bitPerfectClient->getInternalMute();
9349 clientsInternalMute.push_back(std::move(info));
9350 } else {
9351 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9352 __func__, bitPerfectClient->portId());
9353 }
9354 }
9355 if (!clientsInternalMute.empty()) {
9356 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9357 status != NO_ERROR) {
9358 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9359 }
9360 }
9361}
9362
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009363} // namespace android