blob: d57ab49c4e4f4781edf58c3ca13640af05aebb19 [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
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000126void 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);
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000131 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
132 status != OK) {
133 ALOGE("Error %d while setting connected state %d for device %s",
134 status, static_cast<int>(state),
135 device->getDeviceTypeAddr().toString(false).c_str());
136 }
François Gaffie44481e72016-04-20 07:49:57 +0200137}
138
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100139status_t AudioPolicyManager::setDeviceConnectionStateInt(
140 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
141 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100142 if (port.ext.getTag() != AudioPortExt::device) {
143 return BAD_VALUE;
144 }
145 audio_devices_t device_type;
146 std::string device_address;
147 if (status_t status = aidl2legacy_AudioDevice_audio_device(
148 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
149 status != OK) {
150 return status;
151 };
152 const char* device_name = port.name.c_str();
153 // connect/disconnect only 1 device at a time
154 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
155 return BAD_VALUE;
156
157 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
158 device_type, device_address.c_str(), device_name, encodedFormat,
159 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000160 if (device == nullptr) {
161 return INVALID_OPERATION;
162 }
163 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
164 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
165 }
166 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167}
168
François Gaffie11d30102018-11-02 16:09:09 +0100169status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800170 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171 const char* device_address,
172 const char* device_name,
173 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800174 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
176 status == OK) {
177 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
178 } else {
179 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
180 return status;
181 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182}
Paul McLeane743a472015-01-28 11:07:31 -0800183
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700184status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
185 audio_policy_dev_state_t state)
186{
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700189 SortedVector <audio_io_handle_t> outputs;
190
François Gaffie11d30102018-11-02 16:09:09 +0100191 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // save a copy of the opened output descriptors before any output is opened or closed
194 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
195 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100196
197 bool wasLeUnicastActive = isLeUnicastActive();
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 switch (state)
200 {
201 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800202 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return INVALID_OPERATION;
206 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800207 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700208 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700209
Eric Laurente552edb2014-03-10 17:42:56 -0700210 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200211 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700212 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700213 }
214
François Gaffie44481e72016-04-20 07:49:57 +0200215 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
216 // parameters on newly connected devices (instead of opening the outputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000217 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200218
François Gaffie11d30102018-11-02 16:09:09 +0100219 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
220 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200221
jiabinc0048632023-04-27 22:04:31 +0000222 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700223
224 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 return INVALID_OPERATION;
226 }
François Gaffie2110e042015-03-24 08:41:51 +0100227
jiabin1c4794b2020-05-05 10:08:05 -0700228 // Populate encapsulation information when a output device is connected.
229 device->setEncapsulationInfoFromHal(mpClientInterface);
230
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700231 // outputs should never be empty here
232 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
233 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700238 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100240 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700241 return INVALID_OPERATION;
242 }
243
François Gaffie11d30102018-11-02 16:09:09 +0100244 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
jiabinc0048632023-04-27 22:04:31 +0000246 // Notify the HAL to prepare to disconnect device
247 broadcastDeviceConnectionState(
248 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
jiabinc0048632023-04-27 22:04:31 +0000257 // Send Disconnect to HALs
258 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
259
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800260 // Reset active device codec
261 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
262
Kriti Dangef6be8f2020-11-05 11:58:19 +0100263 // remove device from mReportedFormatsMap cache
264 mReportedFormatsMap.erase(device);
265
jiabina84c3d32022-12-02 18:59:55 +0000266 // remove preferred mixer configurations
267 mPreferredMixerAttrInfos.erase(device->getId());
268
Eric Laurente552edb2014-03-10 17:42:56 -0700269 } break;
270
271 default:
François Gaffie11d30102018-11-02 16:09:09 +0100272 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 return BAD_VALUE;
274 }
275
Eric Laurent736a1022019-03-27 18:28:46 -0700276 // Propagate device availability to Engine
277 setEngineDeviceConnectionState(device, state);
278
Eric Laurentae970022019-01-29 14:25:04 -0800279 // No need to evaluate playback routing when connecting a remote submix
280 // output device used by a dynamic policy of type recorder as no
281 // playback use case is affected.
282 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800284 for (audio_io_handle_t output : outputs) {
285 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800286 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
287 if (policyMix != nullptr
288 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000289 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800290 doCheckForDeviceAndOutputChanges = false;
291 break;
292 }
293 }
294 }
295
296 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // outputs must be closed after checkOutputForAllStrategies() is executed
298 if (!outputs.isEmpty()) {
299 for (audio_io_handle_t output : outputs) {
300 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100301 // close unused outputs after device disconnection or direct outputs that have
302 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200303 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200304 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
305 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200306 (desc->mDirectOpenCount == 0))
307 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
308 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200309 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 closeOutput(output);
311 }
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700313 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
314 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700315 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700316 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800317 };
318
319 if (doCheckForDeviceAndOutputChanges) {
320 checkForDeviceAndOutputChanges(checkCloseOutputs);
321 } else {
322 checkCloseOutputs();
323 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100324 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100325 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700326 const DeviceVector activeMediaDevices =
327 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000328 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700329 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530331 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
332 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100333 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // do not force device change on duplicated output because if device is 0, it will
335 // also force a device 0 for the two outputs it is duplicated to which may override
336 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100337 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100338 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700339 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 // always force when disconnecting (a non-duplicated device)
341 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000342 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000343 // If the device is using preferred mixer attributes, the output need to reopen
344 // with default configuration when the new selected devices are different from
345 // current routing devices
346 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
347 continue;
348 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530349 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700350 }
jiabinbce0c1d2020-10-05 11:20:18 -0700351 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000352 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700353 desc->supportsDevicesForPlayback(activeMediaDevices)) {
354 // Reopen the output to query the dynamic profiles when there is not active
355 // clients or all active clients will be rerouted. Otherwise, set the flag
356 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
357 // can be reopened to query dynamic profiles when all clients are inactive.
358 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000359 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700360 } else {
361 desc->mPendingReopenToQueryProfiles = true;
362 }
363 }
364 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Clear the flag that previously set for re-querying profiles.
366 desc->mPendingReopenToQueryProfiles = false;
367 }
368 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000369 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700370
Eric Laurentd60560a2015-04-10 11:31:20 -0700371 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100372 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700373 }
374
Eric Laurent96d1dda2022-03-14 17:14:19 +0100375 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
376
Eric Laurent72aa32f2014-05-30 18:51:48 -0700377 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530378 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700379 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } // end if is output device
381
Eric Laurente552edb2014-03-10 17:42:56 -0700382 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700383 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700385 switch (state)
386 {
387 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700388 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700389 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700391 return INVALID_OPERATION;
392 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700393
Jaideep Sharma33173202024-06-18 17:46:45 +0530394 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
395
Eric Laurent0dd51852019-04-19 18:18:58 -0700396 if (mAvailableInputDevices.add(device) < 0) {
397 return NO_MEMORY;
398 }
399
François Gaffie44481e72016-04-20 07:49:57 +0200400 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
401 // parameters on newly connected devices (instead of opening the inputs...)
Priyanka Advani (xWF)8af658c2024-08-28 22:16:57 +0000402 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 // Propagate device availability to Engine
404 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700407 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
408
Eric Laurent0dd51852019-04-19 18:18:58 -0700409 mAvailableInputDevices.remove(device);
410
jiabinc0048632023-04-27 22:04:31 +0000411 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100412
413 mHwModules.cleanUpForDevice(device);
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 return INVALID_OPERATION;
416 }
417
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700421 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700424 return INVALID_OPERATION;
425 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700426
François Gaffie11d30102018-11-02 16:09:09 +0100427 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
jiabinc0048632023-04-27 22:04:31 +0000429 // Notify the HAL to prepare to disconnect device
430 broadcastDeviceConnectionState(
431 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700432
François Gaffie11d30102018-11-02 16:09:09 +0100433 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700434
435 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436
jiabinc0048632023-04-27 22:04:31 +0000437 // Set Disconnect to HALs
438 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
439
Kriti Dangef6be8f2020-11-05 11:58:19 +0100440 // remove device from mReportedFormatsMap cache
441 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700442
443 // Propagate device availability to Engine
444 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700446
447 default:
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450 }
451
Eric Laurent0dd51852019-04-19 18:18:58 -0700452 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700453 // As the input device list can impact the output device selection, update
454 // getDeviceForStrategy() cache
455 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700456
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100457 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200458 // Reconnect Audio Source
459 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
460 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
461 checkAudioSourceForAttributes(attributes);
462 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700463 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100464 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700465 }
466
Eric Laurentb52c1522014-05-20 11:27:36 -0700467 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530468 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700470 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700471
François Gaffie11d30102018-11-02 16:09:09 +0100472 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700473 return BAD_VALUE;
474}
475
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100476status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
477 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800478 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700479 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
480 devDescr->setName(device_name);
481 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100482}
483
Eric Laurent736a1022019-03-27 18:28:46 -0700484void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
485 audio_policy_dev_state_t state) {
486
487 // the Engine does not have to know about remote submix devices used by dynamic audio policies
488 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
489 return;
490 }
491 mEngine->setDeviceConnectionState(device, state);
492}
493
494
Eric Laurente0720872014-03-11 09:30:41 -0700495audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100496 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700497{
Eric Laurent634b7142016-04-20 13:48:02 -0700498 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
500 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700501 (strlen(device_address) != 0)/*matchAddress*/);
502
503 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100504 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700505 device, device_address);
506 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
507 }
François Gaffie53615e22015-03-19 09:24:12 +0100508
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 DeviceVector *deviceVector;
510
Eric Laurente552edb2014-03-10 17:42:56 -0700511 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700514 deviceVector = &mAvailableInputDevices;
515 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100516 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700517 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700518 }
Eric Laurent634b7142016-04-20 13:48:02 -0700519
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 return (deviceVector->getDevice(
521 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800523}
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
526 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 const char *device_name,
528 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
531 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800533 // connect/disconnect only 1 device at a time
534 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
535
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800536 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700537 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539 // Nothing to do: device is not connected
540 return NO_ERROR;
541 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700544 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 // configure codecs.
546 // Handle two specific cases by sending a set parameter to
547 // configure A2DP codecs. No need to toggle device state.
548 // Case 1: A2DP active device switches from primary to primary
549 // module
550 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700552 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800553 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
554 if (availablePrimaryOutputDevices().contains(devDesc) &&
555 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 bool isA2dp = audio_is_a2dp_out_device(device);
557 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
558 : String8(AudioParameter::keyReconfigLeSupported);
559 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100561 int isReconfigSupported;
562 repliedParameters.getInt(supportKey, isReconfigSupported);
563 if (isReconfigSupported) {
564 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
565 : String8(AudioParameter::keyReconfigLe);
566 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 param.add(key, String8("true"));
568 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
569 devDesc->setEncodedFormat(encodedFormat);
570 return NO_ERROR;
571 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700572 }
573 }
cnx421bd2dcc42020-07-11 14:58:44 +0800574 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000575 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800576 for (size_t i = 0; i < mOutputs.size(); i++) {
577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000578 // mute media strategies to avoid sending the music tail into
579 // the earpiece or headset.
580 if (desc->isStrategyActive(musicStrategy)) {
581 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
582 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
583 tempRecommendedMuteDuration : desc->latency() * 4;
584 if (muteWaitMs < tempMuteDurationMs) {
585 muteWaitMs = tempMuteDurationMs;
586 }
587 }
cnx421bd2dcc42020-07-11 14:58:44 +0800588 setStrategyMute(musicStrategy, true, desc);
589 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
590 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
591 nullptr, true /*fromCache*/).types());
592 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
594 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
595 // happens after the actual device switch.
596 if (muteWaitMs > 0) {
597 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
598 usleep(muteWaitMs * 1000);
599 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800600 // Toggle the device state: UNAVAILABLE -> AVAILABLE
601 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100602 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800604 device_address, device_name,
605 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
608 status);
609 return status;
610 }
611
612 status = setDeviceConnectionState(device,
613 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800614 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800615 if (status != NO_ERROR) {
616 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
617 status);
618 return status;
619 }
620
621 return NO_ERROR;
622}
623
Pattydd807582021-11-04 21:01:03 +0800624status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
625 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626{
Pattydd807582021-11-04 21:01:03 +0800627 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 std::unordered_set<audio_format_t> formatSet;
630 sp<HwModule> primaryModule =
631 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700632 if (primaryModule == nullptr) {
633 ALOGE("%s() unable to get primary module", __func__);
634 return NO_INIT;
635 }
Pattydd807582021-11-04 21:01:03 +0800636
637 DeviceTypeSet audioDeviceSet;
638
639 switch(device) {
640 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
641 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
642 break;
643 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800644 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
645 break;
646 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
647 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800648 break;
649 default:
650 ALOGE("%s() device type 0x%08x not supported", __func__, device);
651 return BAD_VALUE;
652 }
653
jiabin9a3361e2019-10-01 09:38:30 -0700654 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800655 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800656 for (const auto& device : declaredDevices) {
657 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800658 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800659 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800660 return status;
661}
662
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
664{
665 DeviceVector rxSinkdevices{};
666 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
667 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
668 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
669 auto rxSinkDevice = rxSinkdevices.itemAt(0);
670 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
671 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
672 // retrieve Rx Source device descriptor
673 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
674 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
675
676 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
677 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
678 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
679 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
680 return DeviceVector(rxSinkDevice);
681 }
682 }
683 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
684 // the device returned is not necessarily reachable via this output
685 // (filter later by setOutputDevices())
686 return getNewOutputDevices(mPrimaryOutput, fromCache);
687}
688
689status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
690{
François Gaffiedb1755b2023-09-01 11:50:35 +0200691 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
693 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
694 }
695 return INVALID_OPERATION;
696}
697
698status_t AudioPolicyManager::updateCallRoutingInternal(
699 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700700{
701 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100702 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700703 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200704 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700705 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100706 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 }
François Gaffie11d30102018-11-02 16:09:09 +0100708
Francois Gaffie716e1432019-01-14 16:58:59 +0100709 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100710 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200711
Eric Laurentb2fb4102024-06-21 12:25:26 +0000712 if (!fix_call_audio_patch()) {
713 disconnectTelephonyAudioSource(mCallRxSourceClient);
714 disconnectTelephonyAudioSource(mCallTxSourceClient);
715 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200716
717 if (rxDevices.isEmpty()) {
718 ALOGW("%s() no selected output device", __func__);
719 return INVALID_OPERATION;
720 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000721 if (txSourceDevice == nullptr) {
722 ALOGE("%s() selected input device not available", __func__);
723 return INVALID_OPERATION;
724 }
François Gaffiec005e562018-11-06 15:04:49 +0100725
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100726 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100727 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728
François Gaffie9eb18552018-11-05 10:33:26 +0100729 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700730 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100731 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700732 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100733 // retrieve Rx Source and Tx Sink device descriptors
734 sp<DeviceDescriptor> rxSourceDevice =
735 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738 sp<DeviceDescriptor> txSinkDevice =
739 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
740 String8(),
741 AUDIO_FORMAT_DEFAULT);
742
743 // RX and TX Telephony device are declared by Primary Audio HAL
744 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
745 (telephonyRxModule->getHalVersionMajor() >= 3)) {
746 if (rxSourceDevice == 0 || txSinkDevice == 0) {
747 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100748 ALOGE("%s() no telephony Tx and/or RX device", __func__);
749 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100751 // createAudioPatchInternal now supports both HW / SW bridging
752 createRxPatch = true;
753 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100754 } else {
755 // If the RX device is on the primary HW module, then use legacy routing method for
756 // voice calls via setOutputDevice() on primary output.
757 // Otherwise, create two audio patches for TX and RX path.
758 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
759 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 // If the TX device is also on the primary HW module, setOutputDevice() will take care
761 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100762 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
763 (txSinkDevice != 0);
764 }
765 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
766 // Otherwise, create two audio patches for TX and RX path.
767 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000768 if (fix_call_audio_patch()) {
769 disconnectTelephonyAudioSource(mCallRxSourceClient);
770 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200771 if (!hasPrimaryOutput()) {
772 ALOGW("%s() no primary output available", __func__);
773 return INVALID_OPERATION;
774 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530775 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000777 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800778 // If the TX device is on the primary HW module but RX device is
779 // on other HW module, SinkMetaData of telephony input should handle it
780 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700782 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100783 // terminate active capture if on the same HW module as the call TX source device
784 // FIXME: would be better to refine to only inputs whose profile connects to the
785 // call TX device but this information is not in the audio patch and logic here must be
786 // symmetric to the one in startInput()
787 for (const auto& activeDesc : mInputs.getActiveInputs()) {
788 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
789 closeActiveClients(activeDesc);
790 }
791 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200792 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000793 } else if (fix_call_audio_patch()) {
794 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800795 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100796 if (waitMs != nullptr) {
797 *waitMs = muteWaitMs;
798 }
799 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800800}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700801
Mikhail Naganov100f0122018-11-29 11:22:16 -0800802bool AudioPolicyManager::isDeviceOfModule(
803 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
804 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
805 if (module != 0) {
806 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
807 .indexOf(devDesc) != NAME_NOT_FOUND
808 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
809 .indexOf(devDesc) != NAME_NOT_FOUND;
810 }
811 return false;
812}
813
David Lif85c5e32024-07-01 13:14:10 +0000814void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200815{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000816 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
817
818 if (fix_call_audio_patch()) {
819 if (mCallRxSourceClient != nullptr) {
820 DeviceVector rxDevices =
821 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
822 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
823 "connectTelephonyRxAudioSource(): no device found for call RX source");
824 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
825 if (mCallRxSourceClient->isConnected()
826 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
827 return;
828 }
829 disconnectTelephonyAudioSource(mCallRxSourceClient);
830 }
831 } else {
832 disconnectTelephonyAudioSource(mCallRxSourceClient);
833 }
834
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835 const struct audio_port_config source = {
836 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
837 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
838 };
Eric Laurent541a2002024-01-15 18:11:42 +0100839 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000840
Eric Laurentccbd7872024-06-20 12:34:15 +0000841 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000842 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
844 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000845 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
846 mCallRxSourceClient->srcDevice()->toString().c_str(),
847 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200848 ALOGE_IF(mCallRxSourceClient == nullptr,
849 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200850}
851
Francois Gaffie601801d2021-06-22 13:27:39 +0200852void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853{
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 if (clientDesc == nullptr) {
855 return;
856 }
857 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
858 "%s error stopping audio source", __func__);
859 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200860}
861
862void AudioPolicyManager::connectTelephonyTxAudioSource(
863 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
864 uint32_t delayMs)
865{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200866 if (srcDevice == nullptr || sinkDevice == nullptr) {
867 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
868 return;
869 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000870
871 if (fix_call_audio_patch()) {
872 if (mCallTxSourceClient != nullptr) {
873 if (mCallTxSourceClient->isConnected()
874 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
875 return;
876 }
877 disconnectTelephonyAudioSource(mCallTxSourceClient);
878 }
879 } else {
880 disconnectTelephonyAudioSource(mCallTxSourceClient);
881 }
882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200883 PatchBuilder patchBuilder;
884 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000885
Francois Gaffie601801d2021-06-22 13:27:39 +0200886 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200887 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
888
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200889 struct audio_port_config source = {};
890 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient = new SourceClientDescriptor(
892 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000893 mCommunnicationStrategy, toVolumeSource(aa), true,
894 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100895 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
896
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
898 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
900 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000902 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
903 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200904 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200905 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200906 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200907}
908
Eric Laurente0720872014-03-11 09:30:41 -0700909void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700910{
911 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100912 // store previous phone state for management of sonification strategy below
913 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100914 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100915
916 if (mEngine->setPhoneState(state) != NO_ERROR) {
917 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700918 return;
919 }
François Gaffie2110e042015-03-24 08:41:51 +0100920 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700921 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700922 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700923 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800924 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
926
François Gaffie2110e042015-03-24 08:41:51 +0100927 /**
928 * Switching to or from incall state or switching between telephony and VoIP lead to force
929 * routing command.
930 */
Eric Laurent74b71512019-11-06 17:21:57 -0800931 bool force = ((isStateInCall(oldState) != isStateInCall(state))
932 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700933
934 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700935 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 int delayMs = 0;
938 if (isStateInCall(state)) {
939 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100940 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
941 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700942 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700943 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700944 // mute media and sonification strategies and delay device switch by the largest
945 // latency of any output where either strategy is active.
946 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100947 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
948 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
949 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700950 (delayMs < (int)desc->latency()*2)) {
951 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffiec005e562018-11-06 15:04:49 +0100953 setStrategyMute(musicStrategy, true, desc);
954 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
956 nullptr, true /*fromCache*/).types());
957 setStrategyMute(sonificationStrategy, true, desc);
958 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
959 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
960 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962 }
963
François Gaffiedb1755b2023-09-01 11:50:35 +0200964 if (state == AUDIO_MODE_IN_CALL) {
965 (void)updateCallRouting(false /*fromCache*/, delayMs);
966 } else {
967 if (oldState == AUDIO_MODE_IN_CALL) {
968 disconnectTelephonyAudioSource(mCallRxSourceClient);
969 disconnectTelephonyAudioSource(mCallTxSourceClient);
970 }
971 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100972 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
973 // force routing command to audio hardware when ending call
974 // even if no device change is needed
975 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
976 rxDevices = mPrimaryOutput->devices();
977 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530978 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700979 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700980 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700981
jiabin3ff8d7d2022-12-13 06:27:44 +0000982 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700983 // reevaluate routing on all outputs in case tracks have been started during the call
984 for (size_t i = 0; i < mOutputs.size(); i++) {
985 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100986 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000987 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
988 && desc->mPreferredAttrInfo != nullptr) {
989 // If the output is using preferred mixer attributes and the audio mode is not normal,
990 // the output need to reopen with default configuration.
991 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
992 continue;
993 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200994 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
995 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200997 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700998 }
999 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001
Eric Laurent96d1dda2022-03-14 17:14:19 +01001002 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1003
Eric Laurente552edb2014-03-10 17:42:56 -07001004 if (isStateInCall(state)) {
1005 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001006 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001007 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001008 }
1009
1010 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001011 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1012 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001013}
1014
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001015audio_mode_t AudioPolicyManager::getPhoneState() {
1016 return mEngine->getPhoneState();
1017}
1018
Eric Laurente0720872014-03-11 09:30:41 -07001019void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001020 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001021{
François Gaffie2110e042015-03-24 08:41:51 +01001022 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001023 if (config == mEngine->getForceUse(usage)) {
1024 return;
1025 }
Eric Laurente552edb2014-03-10 17:42:56 -07001026
François Gaffie2110e042015-03-24 08:41:51 +01001027 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1028 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1029 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
François Gaffie2110e042015-03-24 08:41:51 +01001031 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1032 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1033 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001036 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001037
Eric Laurent22fcda22019-05-17 16:28:47 -07001038 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1039 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001040 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001041 }
1042
Eric Laurentdc462862016-07-19 12:29:53 -07001043 //FIXME: workaround for truncated touch sounds
1044 // to be removed when the problem is handled by system UI
1045 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001046 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1047 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1048 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001049
1050 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001051 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001052}
1053
Eric Laurente0720872014-03-11 09:30:41 -07001054void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001055{
1056 ALOGV("setSystemProperty() property %s, value %s", property, value);
1057}
1058
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059// Find an MSD output profile compatible with the parameters passed.
1060// When "directOnly" is set, restrict search to profiles for direct outputs.
1061sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1062 const DeviceVector& devices,
1063 uint32_t samplingRate,
1064 audio_format_t format,
1065 audio_channel_mask_t channelMask,
1066 audio_output_flags_t flags,
1067 bool directOnly)
1068{
1069 flags = getRelevantFlags(flags, directOnly);
1070
1071 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1072 if (msdModule != nullptr) {
1073 // for the msd module check if there are patches to the output devices
1074 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1075 HwModuleCollection modules;
1076 modules.add(msdModule);
1077 return searchCompatibleProfileHwModules(
1078 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1079 flags, directOnly);
1080 }
1081 }
1082 return nullptr;
1083}
1084
Michael Chana94fbb22018-04-24 14:31:19 +10001085// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1086// search to profiles for direct outputs.
1087sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001088 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001089 uint32_t samplingRate,
1090 audio_format_t format,
1091 audio_channel_mask_t channelMask,
1092 audio_output_flags_t flags,
1093 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001094{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001095 flags = getRelevantFlags(flags, directOnly);
1096
1097 return searchCompatibleProfileHwModules(
1098 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1099}
1100
1101audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1102 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001103 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 // only retain flags that will drive the direct output profile selection
1105 // if explicitly requested
1106 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001107 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1109 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001110 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001111 return flags;
1112}
Eric Laurent861a6282015-05-18 15:40:16 -07001113
Dorin Drimusecc9f422022-03-09 17:57:40 +01001114sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1115 const HwModuleCollection& hwModules,
1116 const DeviceVector& devices,
1117 uint32_t samplingRate,
1118 audio_format_t format,
1119 audio_channel_mask_t channelMask,
1120 audio_output_flags_t flags,
1121 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001122 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001123 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001124 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001125 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 samplingRate, NULL /*updatedSamplingRate*/,
1127 format, NULL /*updatedFormat*/,
1128 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001129 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001130 continue;
1131 }
1132 // reject profiles not corresponding to a device currently available
1133 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1134 continue;
1135 }
1136 // reject profiles if connected device does not support codec
1137 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1138 continue;
1139 }
1140 if (!directOnly) {
1141 return curProfile;
1142 }
1143
1144 // when searching for direct outputs, if several profiles are compatible, give priority
1145 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001146 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001147 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001148 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001149 }
1150 profile = curProfile;
1151 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1152 break;
1153 }
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155 }
Eric Laurent861a6282015-05-18 15:40:16 -07001156 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001157}
1158
Eric Laurentfa0f6742021-08-17 18:39:44 +02001159sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001160 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161{
1162 for (const auto& hwModule : mHwModules) {
1163 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001164 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001165 continue;
1166 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001167 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001168 // reject profiles not corresponding to a device currently available
1169 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1170 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1171 continue;
1172 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001173 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1174 != devices.size()) {
1175 continue;
1176 }
1177 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001178 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1179 return curProfile;
1180 }
1181 }
1182 return nullptr;
1183}
1184
Eric Laurentf4e63452017-11-06 19:31:46 +00001185audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
François Gaffiec005e562018-11-06 15:04:49 +01001187 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001188
1189 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1190 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1191 // format, flags, etc. This may result in some discrepancy for functions that utilize
1192 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1193 // and AudioSystem::getOutputSamplingRate().
1194
François Gaffie11d30102018-11-02 16:09:09 +01001195 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001196 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001197 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001198 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1199 }
1200 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001201
François Gaffie11d30102018-11-02 16:09:09 +01001202 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1203 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001204 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001205}
1206
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1208 const audio_attributes_t *srcAttr,
1209 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001210{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001211 if (srcAttr != NULL) {
1212 if (!isValidAttributes(srcAttr)) {
1213 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1214 __func__,
1215 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1216 srcAttr->tags);
1217 return BAD_VALUE;
1218 }
1219 *dstAttr = *srcAttr;
1220 } else {
1221 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1222 ALOGE("%s: invalid stream type", __func__);
1223 return BAD_VALUE;
1224 }
François Gaffiec005e562018-11-06 15:04:49 +01001225 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001226 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001227
1228 // Only honor audibility enforced when required. The client will be
1229 // forced to reconnect if the forced usage changes.
1230 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001231 dstAttr->flags = static_cast<audio_flags_mask_t>(
1232 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001233 }
1234
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001235 return NO_ERROR;
1236}
1237
Kevin Rocard153f92d2018-12-18 18:33:28 -08001238status_t AudioPolicyManager::getOutputForAttrInt(
1239 audio_attributes_t *resultAttr,
1240 audio_io_handle_t *output,
1241 audio_session_t session,
1242 const audio_attributes_t *attr,
1243 audio_stream_type_t *stream,
1244 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001245 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 audio_output_flags_t *flags,
1247 audio_port_handle_t *selectedDeviceId,
1248 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001249 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001250 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001251 bool *isSpatialized,
1252 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001253{
François Gaffiec005e562018-11-06 15:04:49 +01001254 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001255 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001256 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001257 const sp<DeviceDescriptor> requestedDevice =
1258 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1259
Eric Laurent8a1095a2019-11-08 14:44:16 -08001260 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001261 *isSpatialized = false;
1262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1264 if (status != NO_ERROR) {
1265 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001266 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001267 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001268 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001269 }
François Gaffiec005e562018-11-06 15:04:49 +01001270 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001271
François Gaffiec005e562018-11-06 15:04:49 +01001272 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1273 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001274
Oscar Azucena873d10f2023-01-12 18:34:42 -08001275 bool usePrimaryOutputFromPolicyMixes = false;
1276
Kevin Rocard153f92d2018-12-18 18:33:28 -08001277 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1278 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1279 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001280 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001281 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1282 .channel_mask = config->channel_mask,
1283 .format = config->format,
1284 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001285 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001286 mAvailableOutputDevices, requestedDevice, primaryMix,
1287 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001288 if (status != OK) {
1289 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001290 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001291
Kevin Rocard153f92d2018-12-18 18:33:28 -08001292 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001293 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001294 && (!audio_is_linear_pcm(config->format) ||
1295 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001296 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001297 return BAD_VALUE;
1298 }
1299 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001300 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001301 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1302 primaryMix->mDeviceAddress,
1303 AUDIO_FORMAT_DEFAULT);
1304 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001305 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001306 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1307 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001308 // if a direct output can be opened to deliver the track's multi-channel content to the
1309 // output rather than being downmixed by the primary output, then use this direct
1310 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1311 // mix.
1312 bool tryDirectForChannelMask = policyDesc != nullptr
1313 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1314 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001315 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001316 audio_io_handle_t newOutput;
1317 status = openDirectOutput(
1318 *stream, session, config,
1319 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001320 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001321 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001322 policyDesc = mOutputs.valueFor(newOutput);
1323 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001324 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001325 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001326 policyDesc = nullptr;
1327 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001328 }
1329 if (policyDesc != nullptr) {
1330 policyDesc->mPolicyMix = primaryMix;
1331 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001332 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1333 : AUDIO_PORT_HANDLE_NONE;
1334 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1335 // Remove direct flag as it is not on a direct output.
1336 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1337 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001338
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001339 ALOGV("getOutputForAttr() returns output %d", *output);
1340 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1341 *outputType = API_OUT_MIX_PLAYBACK;
1342 } else {
1343 *outputType = API_OUTPUT_LEGACY;
1344 }
1345 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001346 } else {
1347 if (policyMixDevice != nullptr) {
1348 ALOGE("%s, try to use primary mix but no output found", __func__);
1349 return INVALID_OPERATION;
1350 }
1351 // Fallback to default engine selection as the selected primary mix device is not
1352 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001353 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001354 }
François Gaffiec005e562018-11-06 15:04:49 +01001355 // Virtual sources must always be dynamicaly or explicitly routed
1356 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1357 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1358 return BAD_VALUE;
1359 }
1360 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1361 // in order to let the choice of the order to future vendor engine
1362 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001363
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001365 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001366 }
1367
Nadav Barb2f18162018-07-18 13:01:53 +03001368 // Set incall music only if device was explicitly set, and fallback to the device which is
1369 // chosen by the engine if not.
1370 // FIXME: provide a more generic approach which is not device specific and move this back
1371 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001372 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001373 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001374 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001375 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001376 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001377 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001378 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001379 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001380 }
1381 }
1382
François Gaffiec005e562018-11-06 15:04:49 +01001383 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1384 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1385 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001386
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001388 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001389 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001390 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001391 ALOGV("%s() Using MSD devices %s instead of devices %s",
1392 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001393 } else {
1394 *output = AUDIO_IO_HANDLE_NONE;
1395 }
1396 }
1397 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001398 sp<PreferredMixerAttributesInfo> info = nullptr;
1399 if (outputDevices.size() == 1) {
1400 info = getPreferredMixerAttributesInfo(
1401 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001402 mEngine->getProductStrategyForAttributes(*resultAttr),
1403 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001404 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1405 // and it is currently active.
1406 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001407 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001408 info = nullptr;
1409 }
jiabin8a096672024-09-18 18:20:24 +00001410
1411 if (info != nullptr && info->isBitPerfect() &&
1412 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1413 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1414 // Reject direct request if a preferred mixer config in use is bit-perfect.
1415 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1416 __func__);
1417 return BAD_VALUE;
1418 }
1419
jiabin220eea12024-05-17 17:55:20 +00001420 if (com::android::media::audioserver::
1421 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1422 if (info != nullptr && info->getUid() == uid &&
1423 info->configMatches(*config) &&
1424 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1425 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1426 [this, &outputDevices](audio_usage_t usage) {
1427 return mOutputs.isUsageActiveOnDevice(
1428 usage, outputDevices[0]); }))) {
1429 // Bit-perfect request is not allowed when the phone mode is not normal or
1430 // there is any higher priority user case active.
1431 return INVALID_OPERATION;
1432 }
1433 }
jiabina84c3d32022-12-02 18:59:55 +00001434 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001435 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001436 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001437 // The client will be active if the client is currently preferred mixer owner and the
1438 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001439 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001440 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001441 && info->getUid() == uid
1442 && *output != AUDIO_IO_HANDLE_NONE
1443 // When bit-perfect output is selected for the preferred mixer attributes owner,
1444 // only need to consider the config matches.
1445 && mOutputs.valueFor(*output)->isConfigurationMatched(
1446 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001447
1448 if (*isBitPerfect) {
1449 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1450 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001451 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001452 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001453 AudioProfileVector profiles;
1454 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1455 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001456 const auto channels = profiles[0]->getChannels();
1457 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1458 config->channel_mask = *channels.begin();
1459 }
1460 const auto sampleRates = profiles[0]->getSampleRates();
1461 if (!sampleRates.empty() &&
1462 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1463 config->sample_rate = *sampleRates.begin();
1464 }
jiabinf1c73972022-04-14 16:28:52 -07001465 config->format = profiles[0]->getFormat();
1466 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001467 return INVALID_OPERATION;
1468 }
Paul McLeanaa981192015-03-21 09:55:15 -07001469
François Gaffiec005e562018-11-06 15:04:49 +01001470 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001471 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001472 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001473 *selectedDeviceId = outputDevice->getId();
1474 break;
1475 }
1476 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001477
Eric Laurent8a1095a2019-11-08 14:44:16 -08001478 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1479 *outputType = API_OUTPUT_TELEPHONY_TX;
1480 } else {
1481 *outputType = API_OUTPUT_LEGACY;
1482 }
1483
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001484 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1485
1486 return NO_ERROR;
1487}
1488
1489status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1490 audio_io_handle_t *output,
1491 audio_session_t session,
1492 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001493 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001494 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001495 audio_output_flags_t *flags,
1496 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001497 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001498 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001499 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001500 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001501 bool *isBitPerfect,
1502 float *volume)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001503{
1504 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1505 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1506 return INVALID_OPERATION;
1507 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001508 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001509 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001510 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001512 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001513 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001514 const sp<DeviceDescriptor> requestedDevice =
1515 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1516
1517 // Prevent from storing invalid requested device id in clients
1518 const audio_port_handle_t sanitizedRequestedPortId =
1519 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1520 *selectedDeviceId = sanitizedRequestedPortId;
1521
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001522 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001523 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001524 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1525 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001526 if (status != NO_ERROR) {
1527 return status;
1528 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001529 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001530 if (secondaryOutputs != nullptr) {
1531 for (auto &secondaryMix : secondaryMixes) {
1532 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1533 if (outputDesc != nullptr &&
1534 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1535 secondaryOutputs->push_back(outputDesc->mIoHandle);
1536 weakSecondaryOutputDescs.push_back(outputDesc);
1537 }
1538 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001539 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001540
Eric Laurent8fc147b2018-07-22 19:13:55 -07001541 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001542 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001543 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001544 };
jiabin4ef93452019-09-10 14:29:54 -07001545 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001546
Eric Laurentc209fe42020-06-05 18:11:23 -07001547 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001548 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001549 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001550 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001551 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001552 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001553 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001554 std::move(weakSecondaryOutputDescs),
1555 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001556 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001557
Andy Hung6b137d12024-08-27 22:35:17 +00001558 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
1559
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001560 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1561 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001562
Eric Laurente83b55d2014-11-14 10:06:21 -08001563 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001564}
1565
Eric Laurentc529cf62020-04-17 18:19:10 -07001566status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1567 audio_session_t session,
1568 const audio_config_t *config,
1569 audio_output_flags_t flags,
1570 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001571 audio_io_handle_t *output,
1572 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001573
1574 *output = AUDIO_IO_HANDLE_NONE;
1575
1576 // skip direct output selection if the request can obviously be attached to a mixed output
1577 // and not explicitly requested
1578 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1579 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1580 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1581 return NAME_NOT_FOUND;
1582 }
1583
Mikhail Naganov806170e2024-09-05 17:26:50 -07001584 // Reject flag combinations that do not make sense. Note that the requested flags might not
1585 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1586 // combine the requested flags with its own flags, yielding an unsupported combination.
1587 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1588 return NAME_NOT_FOUND;
1589 }
1590
Eric Laurentc529cf62020-04-17 18:19:10 -07001591 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1592 // This prevents creating an offloaded track and tearing it down immediately after start
1593 // when audioflinger detects there is an active non offloadable effect.
1594 // FIXME: We should check the audio session here but we do not have it in this context.
1595 // This may prevent offloading in rare situations where effects are left active by apps
1596 // in the background.
1597 sp<IOProfile> profile;
1598 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1599 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1600 profile = getProfileForOutput(
1601 devices, config->sample_rate, config->format, config->channel_mask,
1602 flags, true /* directOnly */);
1603 }
1604
1605 if (profile == nullptr) {
1606 return NAME_NOT_FOUND;
1607 }
1608
1609 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1610 for (size_t i = 0; i < mOutputs.size(); i++) {
1611 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1612 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1613 // reuse direct output if currently open by the same client
1614 // and configured with same parameters
1615 if ((config->sample_rate == desc->getSamplingRate()) &&
1616 (config->format == desc->getFormat()) &&
1617 (config->channel_mask == desc->getChannelMask()) &&
1618 (session == desc->mDirectClientSession)) {
1619 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301620 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001621 mOutputs.keyAt(i), session);
1622 *output = mOutputs.keyAt(i);
1623 return NO_ERROR;
1624 }
1625 }
1626 }
1627
1628 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001629 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301630 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1631 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001632 return NAME_NOT_FOUND;
1633 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1634 // MMAP gracefully handles lack of an exclusive track resource by mixing
1635 // above the audio framework. For AAudio to know that the limit is reached,
1636 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301637 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1638 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001639 return NAME_NOT_FOUND;
1640 } else {
1641 // Close outputs on this profile, if available, to free resources for this request
1642 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1643 const auto desc = mOutputs.valueAt(i);
1644 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301645 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1646 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001647 closeOutput(desc->mIoHandle);
1648 }
1649 }
1650 }
1651 }
1652
1653 // Unable to close streams to find free resources for this request
1654 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301655 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1656 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001657 return NAME_NOT_FOUND;
1658 }
1659
Atneya Nairb16666a2023-12-11 20:18:33 -08001660 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001661
Michael Chan6fb34492020-12-08 15:44:49 +11001662 // An MSD patch may be using the only output stream that can service this request. Release
1663 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001664 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001665
Eric Laurentf1f22e72021-07-13 14:04:14 +02001666 status_t status =
Haofan Wangf6e304f2024-07-09 23:06:58 -07001667 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1668 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001669
1670 // only accept an output with the requested parameters
1671 if (status != NO_ERROR ||
1672 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1673 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1674 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1675 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1676 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1677 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1678 config->channel_mask, outputDesc->getChannelMask());
1679 if (*output != AUDIO_IO_HANDLE_NONE) {
1680 outputDesc->close();
1681 }
1682 // fall back to mixer output if possible when the direct output could not be open
1683 if (audio_is_linear_pcm(config->format) &&
1684 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1685 return NAME_NOT_FOUND;
1686 }
1687 *output = AUDIO_IO_HANDLE_NONE;
1688 return BAD_VALUE;
1689 }
1690 outputDesc->mDirectOpenCount = 1;
1691 outputDesc->mDirectClientSession = session;
1692
1693 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001694 setOutputDevices(__func__, outputDesc,
1695 devices,
1696 true,
1697 0,
1698 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001699 mPreviousOutputs = mOutputs;
1700 ALOGV("%s returns new direct output %d", __func__, *output);
1701 mpClientInterface->onAudioPortListUpdate();
1702 return NO_ERROR;
1703}
1704
François Gaffie11d30102018-11-02 16:09:09 +01001705audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1706 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001707 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001708 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001709 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001710 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001711 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001712 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001713 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001714{
Andy Hungc88b0642018-04-27 15:42:35 -07001715 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001716
jiabine375d412019-02-26 12:54:53 -08001717 // Discard haptic channel mask when forcing muting haptic channels.
1718 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001719 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1720 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001721
Eric Laurente552edb2014-03-10 17:42:56 -07001722 // open a direct output if required by specified parameters
1723 //force direct flag if offload flag is set: offloading implies a direct output stream
1724 // and all common behaviors are driven by checking only the direct flag
1725 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001726 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1727 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001728 }
Nadav Bar766fb022018-01-07 12:18:03 +02001729 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1730 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001731 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001732
1733 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1734
Eric Laurente83b55d2014-11-14 10:06:21 -08001735 // only allow deep buffering for music stream type
1736 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001737 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001738 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001739 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001740 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001741 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001742 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001743 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001744 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001745 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001746 audio_is_linear_pcm(config->format) &&
1747 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001748 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001749 AUDIO_OUTPUT_FLAG_DIRECT);
1750 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001751 }
Eric Laurente552edb2014-03-10 17:42:56 -07001752
Carter Hsua3abb402021-10-26 11:11:20 +08001753 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1754 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1755 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1756 }
1757
Eric Laurentf9230d52024-01-26 18:49:09 +01001758 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001759 // was specified and offload or direct playback is not explicitly requested, and there is no
1760 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001761 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001762 if (mSpatializerOutput != nullptr &&
1763 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1764 prefMixerConfigInfo == nullptr &&
1765 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1766 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001767 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001768 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001769 }
1770
Eric Laurentc529cf62020-04-17 18:19:10 -07001771 audio_config_t directConfig = *config;
1772 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001773
1774 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1775 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001776 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001777 return output;
1778 }
1779
Eric Laurent14cbfca2016-03-17 09:42:16 -07001780 // A request for HW A/V sync cannot fallback to a mixed output because time
1781 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001782 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001783 return AUDIO_IO_HANDLE_NONE;
1784 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001785 // A request for Tuner cannot fallback to a mixed output
1786 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1787 return AUDIO_IO_HANDLE_NONE;
1788 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001789
Eric Laurente552edb2014-03-10 17:42:56 -07001790 // ignoring channel mask due to downmix capability in mixer
1791
1792 // open a non direct output
1793
1794 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001795 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001796 // get which output is suitable for the specified stream. The actual
1797 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001798 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001799 if (prefMixerConfigInfo != nullptr) {
1800 for (audio_io_handle_t outputHandle : outputs) {
1801 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1802 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1803 output = outputHandle;
1804 break;
1805 }
1806 }
1807 if (output == AUDIO_IO_HANDLE_NONE) {
1808 // No output open with the preferred profile. Open a new one.
1809 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1810 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1811 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1812 config.format = prefMixerConfigInfo->getConfigBase().format;
1813 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1814 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1815 &config, prefMixerConfigInfo->getFlags());
1816 if (preferredOutput == nullptr) {
1817 ALOGE("%s failed to open output with preferred mixer config", __func__);
1818 } else {
1819 output = preferredOutput->mIoHandle;
1820 }
1821 }
1822 } else {
1823 // at this stage we should ignore the DIRECT flag as no direct output could be
1824 // found earlier
1825 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001826 if (com::android::media::audioserver::
1827 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1828 // If the preferred mixer attributes is null, do not select the bit-perfect output
1829 // unless the bit-perfect output is the only output.
1830 // The bit-perfect output can exist while the passed in preferred mixer attributes
1831 // info is null when it is a high priority client. The high priority clients are
1832 // ringtone or alarm, which is not a bit-perfect use case.
1833 size_t i = 0;
1834 while (i < outputs.size() && outputs.size() > 1) {
1835 auto desc = mOutputs.valueFor(outputs[i]);
1836 // The output descriptor must not be null here.
1837 if (desc->isBitPerfect()) {
1838 outputs.removeItemsAt(i);
1839 } else {
1840 i += 1;
1841 }
1842 }
1843 }
jiabina84c3d32022-12-02 18:59:55 +00001844 output = selectOutput(
1845 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1846 }
Eric Laurente552edb2014-03-10 17:42:56 -07001847 }
François Gaffie11d30102018-11-02 16:09:09 +01001848 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001849 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001850 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001851
Eric Laurente552edb2014-03-10 17:42:56 -07001852 return output;
1853}
1854
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001855sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001856 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1857 mAvailableInputDevices);
1858 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1859}
1860
1861DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1862 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1863 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001864}
1865
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001866const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001868 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1869 if (msdModule != 0) {
1870 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1871 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1872 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1873 const struct audio_port_config *source = &patch->mPatch.sources[j];
1874 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1875 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001876 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001877 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001878 }
1879 }
1880 }
1881 return msdPatches;
1882}
1883
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001884bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1885 ssize_t index = mAudioPatches.indexOfKey(handle);
1886 if (index < 0) {
1887 return false;
1888 }
1889 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1890 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1891 if (msdModule == nullptr) {
1892 return false;
1893 }
1894 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1895 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1896 return true;
1897 }
1898 index = getMsdOutputPatches().indexOfKey(handle);
1899 if (index < 0) {
1900 return false;
1901 }
1902 return true;
1903}
1904
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001905status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1906 const InputProfileCollection &inputProfiles,
1907 const OutputProfileCollection &outputProfiles,
1908 const sp<DeviceDescriptor> &sourceDevice,
1909 const sp<DeviceDescriptor> &sinkDevice,
1910 AudioProfileVector& sourceProfiles,
1911 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001913 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001914 return NO_INIT;
1915 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001916 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001917 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001918 return NO_INIT;
1919 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001920 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001921 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1922 inProfile->supportsDevice(sourceDevice)) {
1923 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001924 }
1925 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001926 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001927 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001928 outProfile->supportsDevice(sinkDevice)) {
1929 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 }
1931 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001932 return NO_ERROR;
1933}
1934
1935status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1936 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1937 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1938{
Dean Wheatley16809da2022-12-09 14:55:46 +11001939 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1940 static const std::vector<audio_format_t> formatsOrder = {{
1941 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001942 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1943 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001944 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1945 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1946 // preferred).
1947 std::vector<audio_channel_mask_t> masks = {{
1948 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1949 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1950 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1951 // insert index masks (higher counts most preferred) as preferred over position masks
1952 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1953 masks.insert(
1954 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1955 }
1956 return masks;
1957 }();
1958
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001959 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001960 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1961 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001962 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001963 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1964 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001965 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 }
1967 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1968 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1969 sinkConfig->format = bestSinkConfig.format;
1970 // For encoded streams force direct flag to prevent downstream mixing.
1971 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1972 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001973 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1974 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001975 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001976 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1977 // raw and IEC61937 framed streams.
1978 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1979 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1980 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001981 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1982 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001983 sourceConfig->channel_mask =
1984 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1985 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1986 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001987 sourceConfig->format = bestSinkConfig.format;
1988 // Copy input stream directly without any processing (e.g. resampling).
1989 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1990 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1991 if (hwAvSync) {
1992 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1993 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1994 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1995 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1996 }
1997 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1998 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1999 sinkConfig->config_mask |= config_mask;
2000 sourceConfig->config_mask |= config_mask;
2001 return NO_ERROR;
2002}
2003
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002004PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2005 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006{
2007 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002008 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2009 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2010 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2011 if (deviceModule == nullptr) {
2012 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2013 return patchBuilder;
2014 }
2015 const InputProfileCollection inputProfiles = msdIsSource ?
2016 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2017 const OutputProfileCollection outputProfiles = msdIsSource ?
2018 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2019
2020 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2021 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2022 device : getMsdAudioOutDevices().itemAt(0);
2023 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2024
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002025 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2026 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002027 AudioProfileVector sourceProfiles;
2028 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002029 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2030 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002031 for (auto hwAvSync : { true, false }) {
2032 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2033 sourceProfiles, sinkProfiles) != NO_ERROR) {
2034 continue;
2035 }
2036 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2037 &sinkConfig) == NO_ERROR) {
2038 // Found a matching config. Re-create PatchBuilder with this config.
2039 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2040 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002041 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002042 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002043 " supporting PCM format conversion.", __func__);
2044 return patchBuilder;
2045}
2046
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002047status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002048 DeviceVector devices;
2049 if (outputDevices != nullptr && outputDevices->size() > 0) {
2050 devices.add(*outputDevices);
2051 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002052 // Use media strategy for unspecified output device. This should only
2053 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2054 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002055 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002056 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002057 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002058 }
Michael Chan6fb34492020-12-08 15:44:49 +11002059 std::vector<PatchBuilder> patchesToCreate;
2060 for (auto i = 0u; i < devices.size(); ++i) {
2061 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002062 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002063 }
2064 // Retain only the MSD patches associated with outputDevices request.
2065 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002066 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002067 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2068 auto retainedPatch = false;
2069 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2070 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2071 patchesToRemove.removeItemsAt(i);
2072 retainedPatch = true;
2073 break;
2074 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002075 }
Michael Chan6fb34492020-12-08 15:44:49 +11002076 if (retainedPatch) {
2077 it = patchesToCreate.erase(it);
2078 continue;
2079 }
2080 ++it;
2081 }
2082 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2083 return NO_ERROR;
2084 }
2085 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2086 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002087 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002088 }
Michael Chan6fb34492020-12-08 15:44:49 +11002089 status_t status = NO_ERROR;
2090 for (const auto &p : patchesToCreate) {
2091 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2092 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2093 char message[256];
2094 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2095 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2096 currStatus == NO_ERROR ? "Success" : "Error",
2097 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2098 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2099 if (currStatus == NO_ERROR) {
2100 ALOGD("%s", message);
2101 } else {
2102 ALOGE("%s", message);
2103 if (status == NO_ERROR) {
2104 status = currStatus;
2105 }
2106 }
2107 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002108 return status;
2109}
2110
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002111void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2112 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002113 for (size_t i = 0; i < msdPatches.size(); i++) {
2114 const auto& patch = msdPatches[i];
2115 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2116 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2117 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2118 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2119 releaseAudioPatch(patch->getHandle(), mUidCached);
2120 break;
2121 }
2122 }
2123 }
2124}
2125
Dorin Drimus94d94412022-02-02 09:05:02 +01002126bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002127 DeviceVector devicesToCheck =
2128 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002129 AudioPatchCollection msdPatches = getMsdOutputPatches();
2130 for (size_t i = 0; i < msdPatches.size(); i++) {
2131 const auto& patch = msdPatches[i];
2132 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2133 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2134 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2135 const auto& foundDevice = devicesToCheck.getDevice(
2136 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2137 if (foundDevice != nullptr) {
2138 devicesToCheck.remove(foundDevice);
2139 if (devicesToCheck.isEmpty()) {
2140 return true;
2141 }
2142 }
2143 }
2144 }
2145 }
2146 return false;
2147}
2148
Eric Laurente0720872014-03-11 09:30:41 -07002149audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002150 audio_output_flags_t flags,
2151 audio_format_t format,
2152 audio_channel_mask_t channelMask,
2153 uint32_t samplingRate,
2154 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002155{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002156 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2157 "%s called with format %#x", __func__, format);
2158
jiabinebb6af42020-06-09 17:31:17 -07002159 // Return the output that haptic-generating attached to when 1) session id is specified,
2160 // 2) haptic-generating effect exists for given session id and 3) the output that
2161 // haptic-generating effect attached to is in given outputs.
2162 if (sessionId != AUDIO_SESSION_NONE) {
2163 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2164 sessionId, FX_IID_HAPTICGENERATOR);
2165 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2166 return hapticGeneratingOutput;
2167 }
2168 }
2169
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 // Flags disqualifying an output: the match must happen before calling selectOutput()
2171 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2172 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2173
2174 // Flags expressing a functional request: must be honored in priority over
2175 // other criteria
2176 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2177 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002178 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2179 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002180 // Flags expressing a performance request: have lower priority than serving
2181 // requested sampling rate or channel mask
2182 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2183 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2184 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2185
2186 const audio_output_flags_t functionalFlags =
2187 (audio_output_flags_t)(flags & kFunctionalFlags);
2188 const audio_output_flags_t performanceFlags =
2189 (audio_output_flags_t)(flags & kPerformanceFlags);
2190
2191 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2192
Eric Laurente552edb2014-03-10 17:42:56 -07002193 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002194 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002195 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002196 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002197 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002198 // with tiebreak preferring the minimum number of extra functional flags
2199 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002200 // 3: the output supporting the exact channel mask
2201 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002202 // 5: the output with the highest sampling rate if the requested sample rate is
2203 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002204 // 6: the output with the highest number of requested performance flags
2205 // 7: the output with the bit depth the closest to the requested one
2206 // 8: the primary output
2207 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002208
Eric Laurent16c66dd2019-05-01 17:54:10 -07002209 // matching criteria values in priority order for best matching output so far
2210 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002211
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002212 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2214 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2215 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002216
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002217 for (audio_io_handle_t output : outputs) {
2218 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002219 // matching criteria values in priority order for current output
2220 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002221
Eric Laurent16c66dd2019-05-01 17:54:10 -07002222 if (outputDesc->isDuplicated()) {
2223 continue;
2224 }
2225 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2226 continue;
2227 }
Eric Laurent8838a382014-09-08 16:44:28 -07002228
Eric Laurent16c66dd2019-05-01 17:54:10 -07002229 // If haptic channel is specified, use the haptic output if present.
2230 // When using haptic output, same audio format and sample rate are required.
2231 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002232 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002233 // skip if haptic channel specified but output does not support it, or output support haptic
2234 // but there is no haptic channel requested AND no orphan haptic effect exist
2235 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2236 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002237 continue;
2238 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002239 // In the case of audio-coupled-haptic playback, there is no format conversion and
2240 // resampling in the framework, same format/channel/sampleRate for client and the output
2241 // thread is required. In the case of HapticGenerator effect, do not require format
2242 // matching.
2243 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2244 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002245 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002246 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 }
2248
2249 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002250 const int matchingFunctionalFlags =
2251 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2252 const int totalFunctionalFlags =
2253 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2254 // Prefer matching functional flags, but subtract unnecessary functional flags.
2255 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256
2257 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002258 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2259 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002260 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2261 channelCount <= outputChannelCount) {
2262 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002263 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2264 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002265 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002266 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002267 currentMatchCriteria[3] = outputChannelCount;
2268 }
2269
2270 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002271 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002272 int diff; // avoid unsigned integer overflow.
2273 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2274
2275 // prefer the closest output sampling rate greater than or equal to target
2276 // if none exists, prefer the closest output sampling rate less than target.
2277 //
2278 // criteria is offset to make non-negative.
2279 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002280 }
2281
2282 // performance flags match
2283 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2284
2285 // format match
2286 if (format != AUDIO_FORMAT_INVALID) {
2287 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002288 PolicyAudioPort::kFormatDistanceMax -
2289 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002290 }
2291
2292 // primary output match
2293 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2294
2295 // compare match criteria by priority then value
2296 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2297 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2298 bestMatchCriteria = currentMatchCriteria;
2299 bestOutput = output;
2300
2301 std::stringstream result;
2302 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2303 std::ostream_iterator<int>(result, " "));
2304 ALOGV("%s new bestOutput %d criteria %s",
2305 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002306 }
2307 }
2308
Eric Laurent16c66dd2019-05-01 17:54:10 -07002309 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002310}
2311
Eric Laurent8fc147b2018-07-22 19:13:55 -07002312status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002313{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002314 ALOGV("%s portId %d", __FUNCTION__, portId);
2315
2316 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2317 if (outputDesc == 0) {
2318 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002319 return BAD_VALUE;
2320 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002321 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002322
Eric Laurent8fc147b2018-07-22 19:13:55 -07002323 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002324 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002325
jiabin220eea12024-05-17 17:55:20 +00002326 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2327 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2328 && outputDesc->isBitPerfect()) {
2329 // Usually, APM selects bit-perfect output for high priority use cases only when
2330 // bit-perfect output is the only output that can be routed to the selected device.
2331 // However, here is no need to play high priority use cases such as ringtone and alarm
2332 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2333 // can attach to new output.
2334 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2335 __func__, client->stream());
2336 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2337 return DEAD_OBJECT;
2338 }
2339
Eric Laurent733ce942017-12-07 12:18:25 -08002340 status_t status = outputDesc->start();
2341 if (status != NO_ERROR) {
2342 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002343 }
2344
Eric Laurent97ac8712018-07-27 18:59:02 -07002345 uint32_t delayMs;
2346 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002347
2348 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002349 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002350 if (status == DEAD_OBJECT) {
2351 sp<SwAudioOutputDescriptor> desc =
2352 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2353 if (desc == nullptr) {
2354 // This is not common, it may indicate something wrong with the HAL.
2355 ALOGE("%s unable to open output with default config", __func__);
2356 return status;
2357 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002358 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002359 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002360 }
jiabina84c3d32022-12-02 18:59:55 +00002361
2362 // If the client is the first one active on preferred mixer parameters, reopen the output
2363 // if the current mixer parameters doesn't match the preferred one.
2364 if (outputDesc->devices().size() == 1) {
2365 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2366 outputDesc->devices()[0]->getId(), client->strategy());
2367 if (info != nullptr && info->getUid() == client->uid()) {
2368 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2369 info->getConfigBase(), info->getFlags())) {
2370 stopSource(outputDesc, client);
2371 outputDesc->stop();
2372 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2373 config.channel_mask = info->getConfigBase().channel_mask;
2374 config.sample_rate = info->getConfigBase().sample_rate;
2375 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002376 sp<SwAudioOutputDescriptor> desc =
2377 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2378 if (desc == nullptr) {
2379 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002380 }
jiabin220eea12024-05-17 17:55:20 +00002381 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002382 // Intentionally return error to let the client side resending request for
2383 // creating and starting.
2384 return DEAD_OBJECT;
2385 }
2386 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002387 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002388 // If it is first bit-perfect client, reroute all clients that will be routed to
2389 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2390 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002391 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002392 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002393 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2394 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002395 continue;
2396 }
jiabine6b87492024-09-18 23:36:14 +00002397 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2398 outputsToResetDevice.push_back(mOutputs[i]);
2399 }
jiabine3d1f552023-06-14 17:42:17 +00002400 for (const auto& c : mOutputs[i]->getClientIterable()) {
2401 clientsToInvalidate.push_back(c->portId());
2402 }
2403 }
2404 if (!clientsToInvalidate.empty()) {
2405 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2406 __func__);
2407 mpClientInterface->invalidateTracks(clientsToInvalidate);
2408 }
jiabine6b87492024-09-18 23:36:14 +00002409 for (const auto& output : outputsToResetDevice) {
2410 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2411 }
jiabine3d1f552023-06-14 17:42:17 +00002412 }
jiabina84c3d32022-12-02 18:59:55 +00002413 }
2414 }
2415
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002416 if (client->hasPreferredDevice()) {
2417 // playback activity with preferred device impacts routing occurred, inform upper layers
2418 mpClientInterface->onRoutingUpdated();
2419 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002420 if (delayMs != 0) {
2421 usleep(delayMs * 1000);
2422 }
2423
jiabin220eea12024-05-17 17:55:20 +00002424 if (status == NO_ERROR &&
2425 outputDesc->mPreferredAttrInfo != nullptr &&
2426 outputDesc->isBitPerfect() &&
2427 com::android::media::audioserver::
2428 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2429 // A new client is started on bit-perfect output, update all clients internal mute.
2430 updateClientsInternalMute(outputDesc);
2431 }
2432
Eric Laurentc75307b2015-03-17 15:29:32 -07002433 return status;
2434}
2435
Eric Laurent96d1dda2022-03-14 17:14:19 +01002436bool AudioPolicyManager::isLeUnicastActive() const {
2437 if (isInCall()) {
2438 return true;
2439 }
2440 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2441}
2442
2443bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2444 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2445 return false;
2446 }
2447 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2448 ALOGV("%s active %d", __func__, active);
2449 return active;
2450}
2451
Eric Laurent97ac8712018-07-27 18:59:02 -07002452status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2453 const sp<TrackClientDescriptor>& client,
2454 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002455{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002456 // cannot start playback of STREAM_TTS if any other output is being used
2457 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002458
2459 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002460 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002461 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002462 auto clientStrategy = client->strategy();
2463 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002464 if (stream == AUDIO_STREAM_TTS) {
2465 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002466 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002467 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002468 return INVALID_OPERATION;
2469 } else {
2470 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2471 }
2472 } else {
2473 // some playback other than beacon starts
2474 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2475 }
2476
Eric Laurent77305a62016-07-25 16:39:22 -07002477 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002478 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002479 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002480
François Gaffie11d30102018-11-02 16:09:09 +01002481 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002482 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002483 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002484 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002485 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002486 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002487 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002488 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002489 } else {
2490 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002491 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002492 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2493 AUDIO_FORMAT_DEFAULT);
2494 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2495 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002496 }
2497
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002498 // requiresMuteCheck is false when we can bypass mute strategy.
2499 // It covers a common case when there is no materially active audio
2500 // and muting would result in unnecessary delay and dropped audio.
2501 const uint32_t outputLatencyMs = outputDesc->latency();
2502 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002503 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002504
Eric Laurente552edb2014-03-10 17:42:56 -07002505 // increment usage count for this stream on the requested output:
2506 // NOTE that the usage count is the same for duplicated output and hardware output which is
2507 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002508 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002509
2510 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002511 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002512 // Preferred device may be exclusive, use only if no other active clients on this output
2513 devices = DeviceVector(
2514 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2515 } else {
2516 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2517 }
François Gaffie11d30102018-11-02 16:09:09 +01002518 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002519 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002520 }
2521 }
Eric Laurente552edb2014-03-10 17:42:56 -07002522
François Gaffiec005e562018-11-06 15:04:49 +01002523 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002524 selectOutputForMusicEffects();
2525 }
2526
François Gaffie1c878552018-11-22 16:53:21 +01002527 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002528 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002529 if (devices.isEmpty()) {
2530 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 }
François Gaffiec005e562018-11-06 15:04:49 +01002532 bool shouldWait =
2533 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2534 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2535 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002536 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002537 const bool needToCloseBitPerfectOutput =
2538 (com::android::media::audioserver::
2539 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2540 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2541 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002542 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002543 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002544 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002545 // An output has a shared device if
2546 // - managed by the same hw module
2547 // - supports the currently selected device
2548 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002549 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002550
Eric Laurent77305a62016-07-25 16:39:22 -07002551 // force a device change if any other output is:
2552 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002553 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002554 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002555 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002556 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002557 // change the device currently selected by the other output.
2558 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002559 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002560 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002561 force = true;
2562 }
2563 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002564 // a notification so that audio focus effect can propagate, or that a mute/unmute
2565 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002566 const uint32_t latencyMs = desc->latency();
2567 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2568
2569 if (shouldWait && isActive && (waitMs < latencyMs)) {
2570 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002571 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002572
2573 // Require mute check if another output is on a shared device
2574 // and currently active to have proper drain and avoid pops.
2575 // Note restoring AudioTracks onto this output needs to invoke
2576 // a volume ramp if there is no mute.
2577 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002578
2579 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2580 outputsToReopen.push_back(desc);
2581 }
Eric Laurente552edb2014-03-10 17:42:56 -07002582 }
2583 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002584
jiabin220eea12024-05-17 17:55:20 +00002585 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002586 // If the output is open with preferred mixer attributes, but the routed device is
2587 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2588 // changed.
2589 return DEAD_OBJECT;
2590 }
jiabin220eea12024-05-17 17:55:20 +00002591 for (auto& outputToReopen : outputsToReopen) {
2592 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2593 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002594 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302595 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2596 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002597
Eric Laurente552edb2014-03-10 17:42:56 -07002598 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002599 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002600 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002601 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002602 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002603 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002604 outputDesc->useHwGain() /*force*/)) {
2605 // request AudioService to reinitialize the volume curves asynchronously
2606 ALOGE("checkAndSetVolume failed, requesting volume range init");
2607 mpClientInterface->onVolumeRangeInitRequest();
2608 };
Eric Laurente552edb2014-03-10 17:42:56 -07002609
2610 // update the outputs if starting an output with a stream that can affect notification
2611 // routing
2612 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002613
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002614 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002615 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002616 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002617 }
Eric Laurentdc462862016-07-19 12:29:53 -07002618
2619 if (waitMs > muteWaitMs) {
2620 *delayMs = waitMs - muteWaitMs;
2621 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002622
2623 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2624 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2625 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2626 // change occurs after the MixerThread starts and causes a stream volume
2627 // glitch.
2628 //
2629 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002630 }
Eric Laurentdc462862016-07-19 12:29:53 -07002631
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002632 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002633 mEngine->getForceUse(
2634 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002635 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002636 }
2637
Eric Laurent97ac8712018-07-27 18:59:02 -07002638 // Automatically enable the remote submix input when output is started on a re routing mix
2639 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002640 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2641 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002642 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2643 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2644 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002645 "remote-submix",
2646 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002647 }
2648
Eric Laurent96d1dda2022-03-14 17:14:19 +01002649 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2650
Eric Laurente552edb2014-03-10 17:42:56 -07002651 return NO_ERROR;
2652}
2653
Eric Laurent96d1dda2022-03-14 17:14:19 +01002654void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2655 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2656 bool isUnicastActive = isLeUnicastActive();
2657
2658 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002659 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002660 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2661 for (size_t i = 0; i < mOutputs.size(); i++) {
2662 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2663 if (desc != ignoredOutput && desc->isActive()
2664 && ((isUnicastActive &&
2665 !desc->devices().
2666 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2667 || (wasUnicastActive &&
2668 !desc->devices().getDevicesFromTypes(
2669 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2670 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2671 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002672 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002673 // If the device is using preferred mixer attributes, the output need to reopen
2674 // with default configuration when the new selected devices are different from
2675 // current routing devices.
2676 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2677 continue;
2678 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302679 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002680 // re-apply device specific volume if not done by setOutputDevice()
2681 if (!force) {
2682 applyStreamVolumes(desc, newDevices.types(), delayMs);
2683 }
2684 }
2685 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002686 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002687 }
2688}
2689
Eric Laurent8fc147b2018-07-22 19:13:55 -07002690status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002691{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002692 ALOGV("%s portId %d", __FUNCTION__, portId);
2693
2694 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2695 if (outputDesc == 0) {
2696 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002697 return BAD_VALUE;
2698 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002699 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002700
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002701 if (client->hasPreferredDevice(true)) {
2702 // playback activity with preferred device impacts routing occurred, inform upper layers
2703 mpClientInterface->onRoutingUpdated();
2704 }
2705
Eric Laurent97ac8712018-07-27 18:59:02 -07002706 ALOGV("stopOutput() output %d, stream %d, session %d",
2707 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002708
Eric Laurent97ac8712018-07-27 18:59:02 -07002709 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002710
Eric Laurent733ce942017-12-07 12:18:25 -08002711 if (status == NO_ERROR ) {
2712 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002713 } else {
2714 return status;
2715 }
2716
2717 if (outputDesc->devices().size() == 1) {
2718 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2719 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002720 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002721 if (info != nullptr && info->getUid() == client->uid()) {
2722 info->decreaseActiveClient();
2723 if (info->getActiveClientCount() == 0) {
2724 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002725 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002726 }
2727 }
jiabin220eea12024-05-17 17:55:20 +00002728 if (com::android::media::audioserver::
2729 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2730 !outputReopened && outputDesc->isBitPerfect()) {
2731 // Only need to update the clients' internal mute when the output is bit-perfect and it
2732 // is not reopened.
2733 updateClientsInternalMute(outputDesc);
2734 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002735 }
2736 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002737}
2738
Eric Laurent97ac8712018-07-27 18:59:02 -07002739status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2740 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002741{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002742 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002743 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002744 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002745 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002746
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002747 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2748
François Gaffie1c878552018-11-22 16:53:21 +01002749 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2750 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002751 // Automatically disable the remote submix input when output is stopped on a
2752 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002753 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002754 if (isSingleDeviceType(
2755 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002756 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002757 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002758 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2759 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002760 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002761 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002762 }
2763 }
2764 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002765 if (client->hasPreferredDevice(true) &&
2766 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002767 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002768 forceDeviceUpdate = true;
2769 }
2770
Eric Laurente552edb2014-03-10 17:42:56 -07002771 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002772 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002773
Eric Laurente552edb2014-03-10 17:42:56 -07002774 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002775 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002776 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002777 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002778
2779 // If the routing does not change, if an output is routed on a device using HwGain
2780 // (aka setAudioPortConfig) and there are still active clients following different
2781 // volume group(s), force reapply volume
2782 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2783 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2784
Eric Laurente552edb2014-03-10 17:42:56 -07002785 // delay the device switch by twice the latency because stopOutput() is executed when
2786 // the track stop() command is received and at that time the audio track buffer can
2787 // still contain data that needs to be drained. The latency only covers the audio HAL
2788 // and kernel buffers. Also the latency does not always include additional delay in the
2789 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302790 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002791 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002792
2793 // force restoring the device selection on other active outputs if it differs from the
2794 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002795 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002796 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002797 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002798 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002799 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002800 desc->isActive() &&
2801 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002802 (newDevices != desc->devices())) {
2803 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2804 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002805
jiabin220eea12024-05-17 17:55:20 +00002806 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002807 // If the device is using preferred mixer attributes, the output need to
2808 // reopen with default configuration when the new selected devices are
2809 // different from current routing devices.
2810 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2811 continue;
2812 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302813 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002814
Eric Laurent57de36c2016-09-28 16:59:11 -07002815 // re-apply device specific volume if not done by setOutputDevice()
2816 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002817 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002818 }
Eric Laurente552edb2014-03-10 17:42:56 -07002819 }
2820 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002821 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002822 // update the outputs if stopping one with a stream that can affect notification routing
2823 handleNotificationRoutingForStream(stream);
2824 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002825
2826 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2827 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002828 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002829 }
2830
François Gaffiec005e562018-11-06 15:04:49 +01002831 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002832 selectOutputForMusicEffects();
2833 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002834
2835 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2836
Eric Laurente552edb2014-03-10 17:42:56 -07002837 return NO_ERROR;
2838 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002839 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002840 return INVALID_OPERATION;
2841 }
2842}
2843
jiabinbce0c1d2020-10-05 11:20:18 -07002844bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002845{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002846 ALOGV("%s portId %d", __FUNCTION__, portId);
2847
2848 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2849 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002850 // If an output descriptor is closed due to a device routing change,
2851 // then there are race conditions with releaseOutput from tracks
2852 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2853 // destroyed shortly thereafter.
2854 //
2855 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002856 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002857 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002858 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002859
2860 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002861
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302862 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2863 if (outputDesc->isClientActive(client)) {
2864 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2865 stopOutput(portId);
2866 }
2867
Eric Laurent8fc147b2018-07-22 19:13:55 -07002868 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2869 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002870 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002871 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002872 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002873 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002874 if (--outputDesc->mDirectOpenCount == 0) {
2875 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002876 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002877 }
2878 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302879
Andy Hung39efb7a2018-09-26 15:39:28 -07002880 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002881 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2882 // The output is pending reopened to query dynamic profiles and
2883 // there is no active clients
2884 closeOutput(outputDesc->mIoHandle);
2885 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2886 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2887 if (newOutputDesc == nullptr) {
2888 ALOGE("%s failed to open output", __func__);
2889 }
2890 return true;
2891 }
2892 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002893}
2894
Eric Laurentcaf7f482014-11-25 17:50:47 -08002895status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2896 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002897 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002898 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002899 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002900 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002901 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002902 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002903 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002904 audio_port_handle_t *portId,
2905 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002906{
François Gaffiec005e562018-11-06 15:04:49 +01002907 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002908 "flags %#x attributes=%s requested device ID %d",
2909 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2910 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002911
Eric Laurentad2e7b92017-09-14 20:06:42 -07002912 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002913 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002914 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002915 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002916 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002917 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002918 sp<RecordClientDescriptor> clientDesc;
2919 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002920 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002921 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922
2923 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2924 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2925 return INVALID_OPERATION;
2926 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002927
Francois Gaffie716e1432019-01-14 16:58:59 +01002928 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2929 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002930 }
2931
Paul McLean466dc8e2015-04-17 13:15:36 -06002932 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002933 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002934 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002935
Eric Laurentad2e7b92017-09-14 20:06:42 -07002936 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2937 // possible
2938 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2939 *input != AUDIO_IO_HANDLE_NONE) {
2940 ssize_t index = mInputs.indexOfKey(*input);
2941 if (index < 0) {
2942 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2943 status = BAD_VALUE;
2944 goto error;
2945 }
2946 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002947 RecordClientVector clients = inputDesc->getClientsForSession(session);
2948 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002949 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2950 status = BAD_VALUE;
2951 goto error;
2952 }
2953 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2954 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002955 // corresponds to a new client and is only permitted from the same UID.
2956 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002957 if (clients.size() > 1) {
2958 for (const auto& client : clients) {
2959 // The client map is ordered by key values (portId) and portIds are allocated
2960 // incrementaly. So the first client in this list is the one opened by audio flinger
2961 // when the mmap stream is created and should be ignored as it does not correspond
2962 // to an actual client
2963 if (client == *clients.cbegin()) {
2964 continue;
2965 }
2966 if (uid != client->uid() && !client->isSilenced()) {
2967 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2968 uid, client->portId(), client->uid());
2969 status = INVALID_OPERATION;
2970 goto error;
2971 }
Eric Laurent331679c2018-04-16 17:03:16 -07002972 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002973 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002974 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002975 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002976
Eric Laurentfecbceb2021-02-09 14:46:43 +01002977 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002978 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002979 }
2980
2981 *input = AUDIO_IO_HANDLE_NONE;
2982 *inputType = API_INPUT_INVALID;
2983
Francois Gaffie716e1432019-01-14 16:58:59 +01002984 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002985 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002986 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002987 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002988 ALOGW("%s could not find input mix for attr %s",
2989 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002990 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002991 }
jiabinc1de2df2019-05-07 14:26:40 -07002992 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2993 String8(attr->tags + strlen("addr=")),
2994 AUDIO_FORMAT_DEFAULT);
2995 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002996 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002997 __func__, attributes.source, attributes.tags);
2998 status = BAD_VALUE;
2999 goto error;
3000 }
3001
Kevin Rocard25f9b052019-02-27 15:08:54 -08003002 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3003 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3004 } else {
3005 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3006 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003007 if (virtualDeviceId) {
3008 *virtualDeviceId = policyMix->mVirtualDeviceId;
3009 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003010 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003011 if (explicitRoutingDevice != nullptr) {
3012 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003013 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003014 // Prevent from storing invalid requested device id in clients
3015 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003016 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003017 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3018 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003019 }
François Gaffie11d30102018-11-02 16:09:09 +01003020 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003021 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003022 status = BAD_VALUE;
3023 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003024 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003025 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3026 *inputType = API_INPUT_MIX_CAPTURE;
3027 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003028 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3029 // there is an external policy, but this input is attached to a mix of recorders,
3030 // meaning it receives audio injected into the framework, so the recorder doesn't
3031 // know about it and is therefore considered "legacy"
3032 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003033
3034 if (virtualDeviceId) {
3035 *virtualDeviceId = policyMix->mVirtualDeviceId;
3036 }
François Gaffie11d30102018-11-02 16:09:09 +01003037 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003038 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003039 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003040 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003041 } else {
3042 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003043 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003044
Eric Laurent599c7582015-12-07 18:05:55 -08003045 }
3046
François Gaffiec005e562018-11-06 15:04:49 +01003047 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003048 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003049 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003050 AudioProfileVector profiles;
3051 status_t ret = getProfilesForDevices(
3052 DeviceVector(device), profiles, flags, true /*isInput*/);
3053 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003054 const auto channels = profiles[0]->getChannels();
3055 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3056 config->channel_mask = *channels.begin();
3057 }
3058 const auto sampleRates = profiles[0]->getSampleRates();
3059 if (!sampleRates.empty() &&
3060 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3061 config->sample_rate = *sampleRates.begin();
3062 }
jiabinf1c73972022-04-14 16:28:52 -07003063 config->format = profiles[0]->getFormat();
3064 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003065 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003066 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003067
Marvin Ramine5a122d2023-12-07 13:57:59 +01003068
3069 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3070 *virtualDeviceId = policyMix->mVirtualDeviceId;
3071 }
3072
Eric Laurent8f42ea12018-08-08 09:08:25 -07003073exit:
3074
François Gaffiec005e562018-11-06 15:04:49 +01003075 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3076 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003077
Francois Gaffie716e1432019-01-14 16:58:59 +01003078 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003079 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003080 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081
Mikhail Naganov2996f672019-04-18 12:29:59 -07003082 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003083 requestedDeviceId, attributes.source, flags,
3084 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003085 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003086 // Move (if found) effect for the client session to its input
3087 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003088 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003089
3090 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3091 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003092
Eric Laurent599c7582015-12-07 18:05:55 -08003093 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003094
3095error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003096 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003097}
3098
3099
François Gaffie11d30102018-11-02 16:09:09 +01003100audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003101 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003102 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003103 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003104 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003105 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003106{
3107 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003108 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003109 bool isSoundTrigger = false;
3110
François Gaffiec005e562018-11-06 15:04:49 +01003111 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003112 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3113 if (index >= 0) {
3114 input = mSoundTriggerSessions.valueFor(session);
3115 isSoundTrigger = true;
3116 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3117 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3118 } else {
3119 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003120 }
François Gaffiec005e562018-11-06 15:04:49 +01003121 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003122 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003123 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003124 }
3125
Carter Hsua3abb402021-10-26 11:11:20 +08003126 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3127 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3128 }
3129
Eric Laurentfe231122017-11-17 17:48:06 -08003130 // sampling rate and flags may be updated by getInputProfile
3131 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3132 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003133 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003134 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003135 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003136 // find a compatible input profile (not necessarily identical in parameters)
3137 sp<IOProfile> profile = getInputProfile(
3138 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3139 if (profile == nullptr) {
3140 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003141 }
jiabin2fd710d2022-05-02 23:20:22 +00003142
Glenn Kasten05ddca52016-02-11 08:17:12 -08003143 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003144 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003145 if (samplingRate == 0) {
3146 samplingRate = profileSamplingRate;
3147 }
Eric Laurente552edb2014-03-10 17:42:56 -07003148
Eric Laurent322b4d22015-04-03 15:57:54 -07003149 if (profile->getModuleHandle() == 0) {
3150 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003151 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003152 }
3153
Eric Laurentec376dc2021-04-08 20:41:22 +02003154 // Reuse an already opened input if a client with the same session ID already exists
3155 // on that input
3156 for (size_t i = 0; i < mInputs.size(); i++) {
3157 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3158 if (desc->mProfile != profile) {
3159 continue;
3160 }
3161 RecordClientVector clients = desc->clientsList();
3162 for (const auto &client : clients) {
3163 if (session == client->session()) {
3164 return desc->mIoHandle;
3165 }
3166 }
3167 }
3168
Eric Laurentc71b11b2024-06-03 12:54:53 +00003169 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003170 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003171 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3172 // First pick best candidate for preemption (there may not be any):
3173 // - Preempt and input if:
3174 // - It has only strictly lower priority use cases than the new client
3175 // - It has equal priority use cases than the new client, was not
3176 // opened thanks to preemption or has been active since opened.
3177 // - Order the preemption candidates by inactive first and priority second
3178 sp<AudioInputDescriptor> closeCandidate;
3179 int leastCloseRank = INT_MAX;
3180 static const int sCloseActive = 0x100;
3181
3182 for (size_t i = 0; i < mInputs.size(); i++) {
3183 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3184 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003185 continue;
3186 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003187 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3188 if (topPrioClient == nullptr) {
3189 continue;
3190 }
3191 int topPrio = source_priority(topPrioClient->source());
3192 if (topPrio < source_priority(attributes.source)
3193 || (topPrio == source_priority(attributes.source)
3194 && !desc->isPreemptor())) {
3195 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3196 if (closeRank < leastCloseRank) {
3197 leastCloseRank = closeRank;
3198 closeCandidate = desc;
3199 }
3200 }
3201 }
3202
3203 if (closeCandidate != nullptr) {
3204 closeInput(closeCandidate->mIoHandle);
3205 // Mark the new input as being issued from a preemption
3206 // so that is will not be preempted later
3207 isPreemptor = true;
3208 } else {
3209 // Then pick the best reusable input (There is always one)
3210 // The order of preference is:
3211 // 1) active inputs with same use case as the new client
3212 // 2) inactive inputs with same use case
3213 // 3) active inputs with different use cases
3214 // 4) inactive inputs with different use cases
3215 sp<AudioInputDescriptor> reuseCandidate;
3216 int leastReuseRank = INT_MAX;
3217 static const int sReuseDifferentUseCase = 0x100;
3218
3219 for (size_t i = 0; i < mInputs.size(); i++) {
3220 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3221 if (desc->mProfile != profile) {
3222 continue;
3223 }
3224 int reuseRank = sReuseDifferentUseCase;
3225 for (const auto& client: desc->getClientIterable()) {
3226 if (client->source() == attributes.source) {
3227 reuseRank = 0;
3228 break;
3229 }
3230 }
3231 reuseRank += desc->isActive() ? 0 : 1;
3232 if (reuseRank < leastReuseRank) {
3233 leastReuseRank = reuseRank;
3234 reuseCandidate = desc;
3235 }
3236 }
3237 return reuseCandidate->mIoHandle;
3238 }
3239 } else { // fix_input_sharing_logic()
3240 for (size_t i = 0; i < mInputs.size(); ) {
3241 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3242 if (desc->mProfile != profile) {
3243 i++;
3244 continue;
3245 }
3246 // if sound trigger, reuse input if used by other sound trigger on same session
3247 // else
3248 // reuse input if active client app is not in IDLE state
3249 //
3250 RecordClientVector clients = desc->clientsList();
3251 bool doClose = false;
3252 for (const auto& client : clients) {
3253 if (isSoundTrigger != client->isSoundTrigger()) {
3254 continue;
3255 }
3256 if (client->isSoundTrigger()) {
3257 if (session == client->session()) {
3258 return desc->mIoHandle;
3259 }
3260 continue;
3261 }
3262 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003263 return desc->mIoHandle;
3264 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003265 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003266 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003267 if (doClose) {
3268 closeInput(desc->mIoHandle);
3269 } else {
3270 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003271 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003272 }
3273 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003274 }
3275
Eric Laurentc71b11b2024-06-03 12:54:53 +00003276 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3277 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003278
Eric Laurentfe231122017-11-17 17:48:06 -08003279 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3280 lConfig.sample_rate = profileSamplingRate;
3281 lConfig.channel_mask = profileChannelMask;
3282 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003283
François Gaffie11d30102018-11-02 16:09:09 +01003284 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003285
3286 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003287 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003288 (profileSamplingRate != lConfig.sample_rate) ||
3289 !audio_formats_match(profileFormat, lConfig.format) ||
3290 (profileChannelMask != lConfig.channel_mask)) {
3291 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003292 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003293 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003294 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003295 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003296 }
Eric Laurent599c7582015-12-07 18:05:55 -08003297 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 }
3299
Eric Laurentc722f302014-12-10 11:21:49 -08003300 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003301
Eric Laurent599c7582015-12-07 18:05:55 -08003302 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003303 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003304
Eric Laurent599c7582015-12-07 18:05:55 -08003305 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003306}
3307
Eric Laurent4eb58f12018-12-07 16:41:02 -08003308status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003309{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003310 ALOGV("%s portId %d", __FUNCTION__, portId);
3311
3312 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3313 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003314 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003315 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003316 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003317 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003318 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003319 if (client->active()) {
3320 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3321 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003322 }
3323
Eric Laurent8f42ea12018-08-08 09:08:25 -07003324 audio_session_t session = client->session();
3325
Eric Laurent4eb58f12018-12-07 16:41:02 -08003326 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327
Eric Laurent4eb58f12018-12-07 16:41:02 -08003328 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003329
Eric Laurent4eb58f12018-12-07 16:41:02 -08003330 status_t status = inputDesc->start();
3331 if (status != NO_ERROR) {
3332 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003333 }
Eric Laurente552edb2014-03-10 17:42:56 -07003334
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003335 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003336 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003337 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003338
Eric Laurent8f42ea12018-08-08 09:08:25 -07003339 // indicate active capture to sound trigger service if starting capture from a mic on
3340 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003341 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003342 if (device != nullptr) {
3343 status = setInputDevice(input, device, true /* force */);
3344 } else {
3345 ALOGW("%s no new input device can be found for descriptor %d",
3346 __FUNCTION__, inputDesc->getId());
3347 status = BAD_VALUE;
3348 }
Eric Laurente552edb2014-03-10 17:42:56 -07003349
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003350 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003351 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003353 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003354 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3355 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003356 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003357 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003358
François Gaffie11d30102018-11-02 16:09:09 +01003359 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3360 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003361 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003362 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003363 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003364
Eric Laurent8f42ea12018-08-08 09:08:25 -07003365 // automatically enable the remote submix output when input is started if not
3366 // used by a policy mix of type MIX_TYPE_RECORDERS
3367 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003368 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003369 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003370 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003371 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003372 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3373 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003374 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 if (address != "") {
3376 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3377 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003378 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003379 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003380 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003381 } else if (status != NO_ERROR) {
3382 // Restore client activity state.
3383 inputDesc->setClientActive(client, false);
3384 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003385 }
3386
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003387 ALOGV("%s input %d source = %d status = %d exit",
3388 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003389
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003390 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003391}
3392
Eric Laurent8fc147b2018-07-22 19:13:55 -07003393status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003394{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003395 ALOGV("%s portId %d", __FUNCTION__, portId);
3396
3397 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3398 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003399 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003400 return BAD_VALUE;
3401 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003402 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003403 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003404 if (!client->active()) {
3405 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003406 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003407 }
Carter Hsue6139d52021-07-08 10:30:20 +08003408 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003409 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003410
Eric Laurent8f42ea12018-08-08 09:08:25 -07003411 inputDesc->stop();
3412 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003413 auto current_source = inputDesc->source();
3414 setInputDevice(input, getNewInputDevice(inputDesc),
3415 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003416 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003417 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003418 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003419 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003420 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3421 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003422 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003423 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003424
3425 // automatically disable the remote submix output when input is stopped if not
3426 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003427 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003428 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003429 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003430 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003431 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3432 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003433 }
3434 if (address != "") {
3435 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3436 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003437 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003438 }
3439 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003440 resetInputDevice(input);
3441
3442 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3443 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003444 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3445 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003446 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003447 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003448 }
3449 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003450 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003451 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003452}
3453
Eric Laurent8fc147b2018-07-22 19:13:55 -07003454void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003455{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003456 ALOGV("%s portId %d", __FUNCTION__, portId);
3457
3458 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3459 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003460 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003461 return;
3462 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003463 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003464 audio_io_handle_t input = inputDesc->mIoHandle;
3465
Eric Laurent8f42ea12018-08-08 09:08:25 -07003466 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003467
Andy Hung39efb7a2018-09-26 15:39:28 -07003468 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003469
3470 // If no more clients are present in this session, park effects to an orphan chain
3471 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3472 if (clientsOnSession.size() == 0) {
3473 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3474 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003475 if (inputDesc->getClientCount() > 0) {
3476 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003477 return;
3478 }
3479
Eric Laurent05b90f82014-08-27 15:32:29 -07003480 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003481 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003482 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003483}
3484
Eric Laurent8f42ea12018-08-08 09:08:25 -07003485void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003486{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003487 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003488
3489 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003490 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003491 }
3492}
3493
Eric Laurent8f42ea12018-08-08 09:08:25 -07003494void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3495{
3496 stopInput(portId);
3497 releaseInput(portId);
3498}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003499
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003500bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3501 if (input->clientsList().size() == 0
3502 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3503 return true;
3504 }
3505 for (const auto& client : input->clientsList()) {
3506 sp<DeviceDescriptor> device =
3507 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3508 client->session());
3509 if (!input->supportedDevices().contains(device)) {
3510 return true;
3511 }
3512 }
3513 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3514 return false;
3515}
3516
Eric Laurent0dd51852019-04-19 18:18:58 -07003517void AudioPolicyManager::checkCloseInputs() {
3518 // After connecting or disconnecting an input device, close input if:
3519 // - it has no client (was just opened to check profile) OR
3520 // - none of its supported devices are connected anymore OR
3521 // - one of its clients cannot be routed to one of its supported
3522 // devices anymore. Otherwise update device selection
3523 std::vector<audio_io_handle_t> inputsToClose;
3524 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003525 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003526 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003527 }
3528 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003529 for (const audio_io_handle_t handle : inputsToClose) {
3530 ALOGV("%s closing input %d", __func__, handle);
3531 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003532 }
Eric Laurentd4692962014-05-05 18:13:44 -07003533}
3534
Vlad Popa87e0e582024-05-20 18:49:20 -07003535status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3536 const char *address __unused,
3537 bool enabled,
3538 audio_stream_type_t streamToDriveAbs)
3539{
Vlad Popaa536eb32024-07-18 16:00:35 -07003540 if (!enabled) {
3541 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3542 return NO_ERROR;
3543 }
3544
Vlad Popa87e0e582024-05-20 18:49:20 -07003545 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3546 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3547 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3548 toString(streamToDriveAbs).c_str());
3549 return BAD_VALUE;
3550 }
3551
Vlad Popaa536eb32024-07-18 16:00:35 -07003552 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003553 return NO_ERROR;
3554}
3555
François Gaffie251c7f02018-11-07 10:41:08 +01003556void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003557{
3558 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003559 if (indexMin < 0 || indexMax < 0) {
3560 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3561 return;
3562 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003563 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003564
3565 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003566 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3567 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003568 continue;
3569 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003570 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003571 }
Eric Laurente552edb2014-03-10 17:42:56 -07003572}
3573
Eric Laurente0720872014-03-11 09:30:41 -07003574status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003575 int index,
3576 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003577{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003578 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003579 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3580 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3581 return NO_ERROR;
3582 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303583 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3584 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003585 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003586}
3587
Eric Laurente0720872014-03-11 09:30:41 -07003588status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003589 int *index,
3590 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003591{
François Gaffiec005e562018-11-06 15:04:49 +01003592 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3593 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003594 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003595 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003596 deviceTypes = mEngine->getOutputDevicesForStream(
3597 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003598 }
jiabin9a3361e2019-10-01 09:38:30 -07003599 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003600}
3601
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003602status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003603 int index,
3604 audio_devices_t device)
3605{
3606 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003607 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3608 if (group == VOLUME_GROUP_NONE) {
3609 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003610 return BAD_VALUE;
3611 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003612 ALOGV("%s: group %d matching with %s index %d",
3613 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003614 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003615 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003616 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003617 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3618 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3619 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3620 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003621 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3622
3623 status = setVolumeCurveIndex(index, device, curves);
3624 if (status != NO_ERROR) {
3625 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3626 return status;
3627 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003628
jiabin9a3361e2019-10-01 09:38:30 -07003629 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003630 auto curCurvAttrs = curves.getAttributes();
3631 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3632 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003633 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003634 } else if (!curves.getStreamTypes().empty()) {
3635 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003636 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003637 } else {
3638 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3639 return BAD_VALUE;
3640 }
jiabin9a3361e2019-10-01 09:38:30 -07003641 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3642 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003643
François Gaffiecfe17322018-11-07 13:41:29 +01003644 // update volume on all outputs and streams matching the following:
3645 // - The requested stream (or a stream matching for volume control) is active on the output
3646 // - The device (or devices) selected by the engine for this stream includes
3647 // the requested device
3648 // - For non default requested device, currently selected device on the output is either the
3649 // requested device or one of the devices selected by the engine for this stream
3650 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3651 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003652 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003653 for (size_t i = 0; i < mOutputs.size(); i++) {
3654 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003655 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003656
jiabin9a3361e2019-10-01 09:38:30 -07003657 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3658 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003659 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003660
3661 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003662 continue;
3663 }
3664 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3665 curDevices.find(device) == curDevices.end()) {
3666 continue;
3667 }
3668 bool applyVolume = false;
3669 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3670 curSrcDevices.insert(device);
3671 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003672 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3673 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003674 } else {
3675 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3676 }
3677 if (!applyVolume) {
3678 continue; // next output
3679 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003680 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3681 // If a higher priority strategy is active, and the output is routed to a device with a
3682 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003683 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003684 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003685 // If the volume source is active with higher priority source, ensure at least Sw Muted
3686 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003687 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3688 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3689 false /*preferredDevice*/);
3690 if (activeClients.empty()) {
3691 continue;
3692 }
3693 bool isPreempted = false;
3694 bool isHigherPriority = productStrategy < strategy;
3695 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003696 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003697 ALOGV("%s: Strategy=%d (\nrequester:\n"
3698 " group %d, volumeGroup=%d attributes=%s)\n"
3699 " higher priority source active:\n"
3700 " volumeGroup=%d attributes=%s) \n"
3701 " on output %zu, bailing out", __func__, productStrategy,
3702 group, group, toString(attributes).c_str(),
3703 client->volumeSource(), toString(client->attributes()).c_str(), i);
3704 applyVolume = false;
3705 isPreempted = true;
3706 break;
3707 }
3708 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003709 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003710 applyVolume = true;
3711 }
3712 }
3713 if (isPreempted || applyVolume) {
3714 break;
3715 }
3716 }
3717 if (!applyVolume) {
3718 continue; // next output
3719 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003720 }
François Gaffieed91f582020-01-31 10:35:37 +01003721 //FIXME: workaround for truncated touch sounds
3722 // delayed volume change for system stream to be removed when the problem is
3723 // handled by system UI
3724 status_t volStatus = checkAndSetVolume(
3725 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003726 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003727 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3728 if (volStatus != NO_ERROR) {
3729 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003730 }
3731 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003732
3733 // update voice volume if the an active call route exists
3734 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3735 && (curSrcDevices.find(
3736 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3737 != curSrcDevices.end())) {
3738 bool isVoiceVolSrc;
3739 bool isBtScoVolSrc;
3740 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3741 isVoiceVolSrc, isBtScoVolSrc, __func__)
3742 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003743 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3744 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3745 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003746 }
3747 }
3748
François Gaffiecfe17322018-11-07 13:41:29 +01003749 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3750 return status;
3751}
3752
François Gaffieaaac0fd2018-11-22 17:56:39 +01003753status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003754 audio_devices_t device,
3755 IVolumeCurves &volumeCurves)
3756{
3757 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3758 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003759 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3760 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003761 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303762 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3763 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003764 return BAD_VALUE;
3765 }
3766 if (!audio_is_output_device(device)) {
3767 return BAD_VALUE;
3768 }
3769
3770 // Force max volume if stream cannot be muted
3771 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3772
François Gaffieaaac0fd2018-11-22 17:56:39 +01003773 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003774 volumeCurves.addCurrentVolumeIndex(device, index);
3775 return NO_ERROR;
3776}
3777
3778status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3779 int &index,
3780 audio_devices_t device)
3781{
3782 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3783 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003784 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003785 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003786 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003787 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003788 }
jiabin9a3361e2019-10-01 09:38:30 -07003789 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003790}
3791
3792status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3793 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003794 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003795{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003796 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003797 return BAD_VALUE;
3798 }
jiabin9a3361e2019-10-01 09:38:30 -07003799 index = curves.getVolumeIndex(deviceTypes);
3800 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003801 return NO_ERROR;
3802}
3803
3804status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3805 int &index)
3806{
3807 index = getVolumeCurves(attr).getVolumeIndexMin();
3808 return NO_ERROR;
3809}
3810
3811status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3812 int &index)
3813{
3814 index = getVolumeCurves(attr).getVolumeIndexMax();
3815 return NO_ERROR;
3816}
3817
Eric Laurent36829f92017-04-07 19:04:42 -07003818audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003819{
3820 // select one output among several suitable for global effects.
3821 // The priority is as follows:
3822 // 1: An offloaded output. If the effect ends up not being offloadable,
3823 // AudioFlinger will invalidate the track and the offloaded output
3824 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003825 // 2: Spatializer output if the stereo spatializer feature enabled
3826 // 3: A deep buffer output
3827 // 4: The primary output
3828 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003829
François Gaffiec005e562018-11-06 15:04:49 +01003830 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3831 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003832 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003833
Eric Laurent36829f92017-04-07 19:04:42 -07003834 if (outputs.size() == 0) {
3835 return AUDIO_IO_HANDLE_NONE;
3836 }
Eric Laurente552edb2014-03-10 17:42:56 -07003837
Eric Laurent36829f92017-04-07 19:04:42 -07003838 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3839 bool activeOnly = true;
3840
3841 while (output == AUDIO_IO_HANDLE_NONE) {
3842 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003843 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003844 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3845 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3846
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003847 for (audio_io_handle_t outputLoop : outputs) {
3848 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003849 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003850 continue;
3851 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003852 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003853 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003854 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003855 outputOffloaded = outputLoop;
3856 }
3857 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3858 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3859 outputSpatializer = outputLoop;
3860 }
Eric Laurent36829f92017-04-07 19:04:42 -07003861 }
3862 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003863 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003864 }
3865 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003866 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003867 }
3868 }
3869 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3870 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003871 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3872 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003873 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3874 output = outputDeepBuffer;
3875 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3876 output = outputPrimary;
3877 } else {
3878 output = outputs[0];
3879 }
3880 activeOnly = false;
3881 }
3882
3883 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003884 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3885 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003886 mMusicEffectOutput = output;
3887 }
3888
3889 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003890 return output;
3891}
3892
Eric Laurent36829f92017-04-07 19:04:42 -07003893audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3894{
3895 return selectOutputForMusicEffects();
3896}
3897
Eric Laurente0720872014-03-11 09:30:41 -07003898status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003899 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003900 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003901 int session,
3902 int id)
3903{
Shunkai Yao29d10572024-03-19 04:31:47 +00003904 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003905 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003906 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003907 index = mInputs.indexOfKey(io);
3908 if (index < 0) {
3909 ALOGW("registerEffect() unknown io %d", io);
3910 return INVALID_OPERATION;
3911 }
Eric Laurente552edb2014-03-10 17:42:56 -07003912 }
3913 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003914 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3915 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3916 || strategy == PRODUCT_STRATEGY_NONE));
3917 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003918}
3919
Eric Laurentc241b0d2018-11-28 09:08:49 -08003920status_t AudioPolicyManager::unregisterEffect(int id)
3921{
3922 if (mEffects.getEffect(id) == nullptr) {
3923 return INVALID_OPERATION;
3924 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003925 if (mEffects.isEffectEnabled(id)) {
3926 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3927 setEffectEnabled(id, false);
3928 }
3929 return mEffects.unregisterEffect(id);
3930}
3931
3932status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3933{
3934 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3935 if (effect == nullptr) {
3936 return INVALID_OPERATION;
3937 }
3938
3939 status_t status = mEffects.setEffectEnabled(id, enabled);
3940 if (status == NO_ERROR) {
3941 mInputs.trackEffectEnabled(effect, enabled);
3942 }
3943 return status;
3944}
3945
Eric Laurent6c796322019-04-09 14:13:17 -07003946
3947status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3948{
3949 mEffects.moveEffects(ids, io);
3950 return NO_ERROR;
3951}
3952
Eric Laurentc75307b2015-03-17 15:29:32 -07003953bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3954{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003955 auto vs = toVolumeSource(stream, false);
3956 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003957}
3958
3959bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3960{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003961 auto vs = toVolumeSource(stream, false);
3962 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003963}
3964
Eric Laurente0720872014-03-11 09:30:41 -07003965bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003966{
3967 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003968 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003969 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003970 return true;
3971 }
3972 }
3973 return false;
3974}
3975
Eric Laurent275e8e92014-11-30 15:14:47 -08003976// Register a list of custom mixes with their attributes and format.
3977// When a mix is registered, corresponding input and output profiles are
3978// added to the remote submix hw module. The profile contains only the
3979// parameters (sampling rate, format...) specified by the mix.
3980// The corresponding input remote submix device is also connected.
3981//
3982// When a remote submix device is connected, the address is checked to select the
3983// appropriate profile and the corresponding input or output stream is opened.
3984//
3985// When capture starts, getInputForAttr() will:
3986// - 1 look for a mix matching the address passed in attribtutes tags if any
3987// - 2 if none found, getDeviceForInputSource() will:
3988// - 2.1 look for a mix matching the attributes source
3989// - 2.2 if none found, default to device selection by policy rules
3990// At this time, the corresponding output remote submix device is also connected
3991// and active playback use cases can be transferred to this mix if needed when reconnecting
3992// after AudioTracks are invalidated
3993//
3994// When playback starts, getOutputForAttr() will:
3995// - 1 look for a mix matching the address passed in attribtutes tags if any
3996// - 2 if none found, look for a mix matching the attributes usage
3997// - 3 if none found, default to device and output selection by policy rules.
3998
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003999status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004000{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004001 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4002 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004003 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004004 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004005 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 // examine each mix's route type
4007 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004008 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004009 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4010 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4011 ALOGE("Unsupported Policy Mix %zu of %zu: "
4012 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4013 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004014 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004015 break;
4016 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004017 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4018 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004019 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004020 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4021 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004022 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004023 rSubmixModule = mHwModules.getModuleFromName(
4024 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4025 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004026 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004027 i);
4028 res = INVALID_OPERATION;
4029 break;
4030 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004031 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004032
Eric Laurent97ac8712018-07-27 18:59:02 -07004033 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004034 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004035 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004036 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004037 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4038 } else {
4039 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4040 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004041 }
François Gaffie036e1e92015-03-19 10:16:24 +01004042
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004043 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004044 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004045 res = INVALID_OPERATION;
4046 break;
4047 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004048 audio_config_t outputConfig = mix.mFormat;
4049 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004050 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4051 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004052 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4053 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004054 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004055 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4056 audio_is_linear_pcm(outputConfig.format)
4057 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004058 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004059 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4060 audio_is_linear_pcm(inputConfig.format)
4061 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004062
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004063 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004064 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004065 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004066 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004067 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004068 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004069 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004070 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4071 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004072 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004073 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004074 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004075
4076 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4077 mix.mDeviceType, mix.mDeviceAddress,
4078 String8(), AUDIO_FORMAT_DEFAULT);
4079 if (device == nullptr) {
4080 res = INVALID_OPERATION;
4081 break;
4082 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004083
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004084 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004085 // First try to find an already opened output supporting the device
4086 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004087 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004088
Eric Laurentc529cf62020-04-17 18:19:10 -07004089 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004090 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004091 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004092 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004093 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004094 } else {
4095 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004096 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004097 }
4098 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004099 // If no output found, try to find a direct output profile supporting the device
4100 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4101 sp<HwModule> module = mHwModules[i];
4102 for (size_t j = 0;
4103 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4104 j++) {
4105 sp<IOProfile> profile = module->getOutputProfiles()[j];
4106 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4107 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4108 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004109 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004110 res = INVALID_OPERATION;
4111 } else {
4112 foundOutput = true;
4113 }
4114 }
4115 }
4116 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004117 if (res != NO_ERROR) {
4118 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004119 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004120 res = INVALID_OPERATION;
4121 break;
4122 } else if (!foundOutput) {
4123 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004124 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004125 res = INVALID_OPERATION;
4126 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004127 } else {
4128 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004129 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004130 }
Eric Laurentc722f302014-12-10 11:21:49 -08004131 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004132 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004133 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004134 if (audio_flags::audio_mix_ownership()) {
4135 // Only unregister mixes that were actually registered to not accidentally unregister
4136 // mixes that already existed previously.
4137 unregisterPolicyMixes(registeredMixes);
4138 registeredMixes.clear();
4139 } else {
4140 unregisterPolicyMixes(mixes);
4141 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004142 } else if (checkOutputs) {
4143 checkForDeviceAndOutputChanges();
4144 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004145 }
4146 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004147}
4148
4149status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4150{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004151 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004152 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004153 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004154 sp<HwModule> rSubmixModule;
4155 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004156 for (const auto& mix : mixes) {
4157 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004158
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004159 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004160 rSubmixModule = mHwModules.getModuleFromName(
4161 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4162 if (rSubmixModule == 0) {
4163 res = INVALID_OPERATION;
4164 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004165 }
4166 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004167
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004168 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004169
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004170 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004171 res = INVALID_OPERATION;
4172 continue;
4173 }
4174
Marvin Ramin0783e202024-03-05 12:45:50 +01004175 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004176 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004177 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4178 status_t currentRes =
4179 setDeviceConnectionStateInt(device,
4180 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4181 address.c_str(),
4182 "remote-submix",
4183 AUDIO_FORMAT_DEFAULT);
4184 if (!audio_flags::audio_mix_ownership()) {
4185 res = currentRes;
4186 }
4187 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004188 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004189 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004190 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004191 }
4192 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004193 }
jiabin5740f082019-08-19 15:08:30 -07004194 rSubmixModule->removeOutputProfile(address.c_str());
4195 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004196
Kevin Rocard153f92d2018-12-18 18:33:28 -08004197 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004198 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004199 res = INVALID_OPERATION;
4200 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004201 } else {
4202 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004203 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004204 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004205 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004206
4207 if (res == NO_ERROR && checkOutputs) {
4208 checkForDeviceAndOutputChanges();
4209 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004210 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004211 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004212}
4213
Marvin Raminbdefaf02023-11-01 09:10:32 +01004214status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4215 if (!audio_flags::audio_mix_test_api()) {
4216 return INVALID_OPERATION;
4217 }
4218
4219 _aidl_return.clear();
4220 _aidl_return.reserve(mPolicyMixes.size());
4221 for (const auto &policyMix: mPolicyMixes) {
4222 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4223 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4224 policyMix->mCbFlags);
4225 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004226 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004227 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004228 }
4229
Vlad Popaa5d73f32024-03-08 16:05:38 -08004230 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004231 return OK;
4232}
4233
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004234status_t AudioPolicyManager::updatePolicyMix(
4235 const AudioMix& mix,
4236 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4237 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4238 if (res == NO_ERROR) {
4239 checkForDeviceAndOutputChanges();
4240 updateCallAndOutputRouting();
4241 }
4242 return res;
4243}
4244
Mikhail Naganov100f0122018-11-29 11:22:16 -08004245void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4246{
4247 size_t i = 0;
4248 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4249 for (const auto& fmt : mManualSurroundFormats) {
4250 if (i++ != 0) dst->append(", ");
4251 std::string sfmt;
4252 FormatConverter::toString(fmt, sfmt);
4253 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4254 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4255 }
4256}
4257
Eric Laurentc529cf62020-04-17 18:19:10 -07004258// Returns true if all devices types match the predicate and are supported by one HW module
4259bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004260 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004261 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004262 const char *context,
4263 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004264 for (size_t i = 0; i < devices.size(); i++) {
4265 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004266 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004267 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004268 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004269 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004270 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004271 return false;
4272 }
4273 }
4274 return true;
4275}
4276
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004277void AudioPolicyManager::changeOutputDevicesMuteState(
4278 const AudioDeviceTypeAddrVector& devices) {
4279 ALOGVV("%s() num devices %zu", __func__, devices.size());
4280
4281 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4282 getSoftwareOutputsForDevices(devices);
4283
4284 for (size_t i = 0; i < outputs.size(); i++) {
4285 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4286 DeviceVector prevDevices = outputDesc->devices();
4287 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4288 }
4289}
4290
4291std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4292 const AudioDeviceTypeAddrVector& devices) const
4293{
4294 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4295 DeviceVector deviceDescriptors;
4296 for (size_t j = 0; j < devices.size(); j++) {
4297 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4298 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4299 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4300 ALOGE("%s: device type %#x address %s not supported or not an output device",
4301 __func__, devices[j].mType, devices[j].getAddress());
4302 continue;
4303 }
4304 deviceDescriptors.add(desc);
4305 }
4306 for (size_t i = 0; i < mOutputs.size(); i++) {
4307 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4308 continue;
4309 }
4310 outputs.push_back(mOutputs.valueAt(i));
4311 }
4312 return outputs;
4313}
4314
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004315status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004316 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004317 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004318 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4319 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004320 }
4321 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004322 if (res != NO_ERROR) {
4323 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4324 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004325 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004326
4327 checkForDeviceAndOutputChanges();
4328 updateCallAndOutputRouting();
4329
4330 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004331}
4332
4333status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4334 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004335 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4336 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004337 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004338 __FUNCTION__, uid);
4339 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004340 }
4341
Eric Laurentc529cf62020-04-17 18:19:10 -07004342 checkForDeviceAndOutputChanges();
4343 updateCallAndOutputRouting();
4344
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004345 return res;
4346}
4347
Eric Laurent2517af32020-11-25 15:31:27 +01004348
jiabin0a488932020-08-07 17:32:40 -07004349status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4350 device_role_t role,
4351 const AudioDeviceTypeAddrVector &devices) {
4352 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4353 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004354
Eric Laurentc529cf62020-04-17 18:19:10 -07004355 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004356 return BAD_VALUE;
4357 }
jiabin0a488932020-08-07 17:32:40 -07004358 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004359 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004360 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4361 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004362 return status;
4363 }
4364
4365 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004366
4367 bool forceVolumeReeval = false;
4368 // FIXME: workaround for truncated touch sounds
4369 // to be removed when the problem is handled by system UI
4370 uint32_t delayMs = 0;
4371 if (strategy == mCommunnicationStrategy) {
4372 forceVolumeReeval = true;
4373 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4374 updateInputRouting();
4375 }
4376 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004377
4378 return NO_ERROR;
4379}
4380
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004381void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4382 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004383{
4384 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004385 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004386 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004387 // Only apply special touch sound delay once
4388 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004389 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004390 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004391 for (size_t i = 0; i < mOutputs.size(); i++) {
4392 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4393 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004394 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4395 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004396 // As done in setDeviceConnectionState, we could also fix default device issue by
4397 // preventing the force re-routing in case of default dev that distinguishes on address.
4398 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004399 bool newDevicesNotEmpty = !newDevices.isEmpty();
4400 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4401 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004402 // If the device is using preferred mixer attributes, the output need to reopen
4403 // with default configuration when the new selected devices are different from
4404 // current routing devices.
4405 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4406 continue;
4407 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304408
jiabin2361ed82024-09-20 17:36:31 +00004409 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4410 newDevicesNotEmpty /*force*/, delayMs,
4411 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4412 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004413 // Only apply special touch sound delay once
4414 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004415 }
4416 if (forceVolumeReeval && !newDevices.isEmpty()) {
4417 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4418 }
4419 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004420 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004421 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004422}
4423
Eric Laurent2517af32020-11-25 15:31:27 +01004424void AudioPolicyManager::updateInputRouting() {
4425 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304426 // Skip for hotword recording as the input device switch
4427 // is handled within sound trigger HAL
4428 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4429 continue;
4430 }
Eric Laurent2517af32020-11-25 15:31:27 +01004431 auto newDevice = getNewInputDevice(activeDesc);
4432 // Force new input selection if the new device can not be reached via current input
4433 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4434 setInputDevice(activeDesc->mIoHandle, newDevice);
4435 } else {
4436 closeInput(activeDesc->mIoHandle);
4437 }
4438 }
4439}
4440
Paul Wang5d7cdb52022-11-22 09:45:06 +00004441status_t
4442AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4443 device_role_t role,
4444 const AudioDeviceTypeAddrVector &devices) {
4445 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4446 dumpAudioDeviceTypeAddrVector(devices).c_str());
4447
Eric Laurent78fedbf2023-03-09 14:40:44 +01004448 if (!areAllDevicesSupported(
4449 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004450 return BAD_VALUE;
4451 }
4452 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4453 if (status != NO_ERROR) {
4454 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4455 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4456 return status;
4457 }
4458
4459 checkForDeviceAndOutputChanges();
4460
4461 bool forceVolumeReeval = false;
4462 // TODO(b/263479999): workaround for truncated touch sounds
4463 // to be removed when the problem is handled by system UI
4464 uint32_t delayMs = 0;
4465 if (strategy == mCommunnicationStrategy) {
4466 forceVolumeReeval = true;
4467 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4468 updateInputRouting();
4469 }
4470 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4471
4472 return NO_ERROR;
4473}
4474
4475status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4476 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004477{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004478 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004479
Paul Wang5d7cdb52022-11-22 09:45:06 +00004480 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004481 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004482 ALOGW_IF(status != NAME_NOT_FOUND,
4483 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004484 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004485 return status;
4486 }
4487
4488 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004489
4490 bool forceVolumeReeval = false;
4491 // FIXME: workaround for truncated touch sounds
4492 // to be removed when the problem is handled by system UI
4493 uint32_t delayMs = 0;
4494 if (strategy == mCommunnicationStrategy) {
4495 forceVolumeReeval = true;
4496 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4497 updateInputRouting();
4498 }
4499 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004500
4501 return NO_ERROR;
4502}
4503
jiabin0a488932020-08-07 17:32:40 -07004504status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4505 device_role_t role,
4506 AudioDeviceTypeAddrVector &devices) {
4507 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004508}
4509
Jiabin Huang3b98d322020-09-03 17:54:16 +00004510status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4511 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4512 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4513 dumpAudioDeviceTypeAddrVector(devices).c_str());
4514
Mikhail Naganov55773032020-10-01 15:08:13 -07004515 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004516 return BAD_VALUE;
4517 }
4518 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4519 ALOGW_IF(status != NO_ERROR,
4520 "Engine could not set preferred devices %s for audio source %d role %d",
4521 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4522
Wenyu Zhang47655d22024-10-01 12:24:53 +00004523 if (status == NO_ERROR) {
4524 updateInputRouting();
4525 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004526 return status;
4527}
4528
4529status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4530 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4531 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4532 dumpAudioDeviceTypeAddrVector(devices).c_str());
4533
Mikhail Naganov55773032020-10-01 15:08:13 -07004534 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004535 return BAD_VALUE;
4536 }
4537 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4538 ALOGW_IF(status != NO_ERROR,
4539 "Engine could not add preferred devices %s for audio source %d role %d",
4540 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4541
Eric Laurent2517af32020-11-25 15:31:27 +01004542 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004543 return status;
4544}
4545
4546status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4547 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4548{
4549 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4550 dumpAudioDeviceTypeAddrVector(devices).c_str());
4551
Eric Laurent78fedbf2023-03-09 14:40:44 +01004552 if (!areAllDevicesSupported(
4553 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004554 return BAD_VALUE;
4555 }
4556
4557 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4558 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004559 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004560 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004561 if (status == NO_ERROR) {
4562 updateInputRouting();
4563 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004564 return status;
4565}
4566
4567status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4568 device_role_t role) {
4569 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4570
4571 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004572 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004573 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004574 if (status == NO_ERROR) {
4575 updateInputRouting();
4576 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004577 return status;
4578}
4579
4580status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4581 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4582 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4583}
4584
Oscar Azucena90e77632019-11-27 17:12:28 -08004585status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004586 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004587 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004588 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4589 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004590 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004591 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4592 if (status != NO_ERROR) {
4593 ALOGE("%s() could not set device affinity for userId %d",
4594 __FUNCTION__, userId);
4595 return status;
4596 }
4597
4598 // reevaluate outputs for all devices
4599 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004600 changeOutputDevicesMuteState(devices);
4601 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4602 true /* skipDelays */);
4603 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004604
4605 return NO_ERROR;
4606}
4607
4608status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004609 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004610 AudioDeviceTypeAddrVector devices;
4611 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004612 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4613 if (status != NO_ERROR) {
4614 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4615 __FUNCTION__, userId);
4616 return status;
4617 }
4618
4619 // reevaluate outputs for all devices
4620 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004621 changeOutputDevicesMuteState(devices);
4622 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4623 true /* skipDelays */);
4624 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004625
4626 return NO_ERROR;
4627}
4628
Andy Hungc29d82b2018-10-05 12:23:17 -07004629void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004630{
Andy Hungc29d82b2018-10-05 12:23:17 -07004631 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004632 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004633 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004634 std::string stateLiteral;
4635 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004636 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004637 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4638 "communications", "media", "record", "dock", "system",
4639 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4640 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4641 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004642 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4643 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4644 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4645 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4646 dst->append(" (MANUAL: ");
4647 dumpManualSurroundFormats(dst);
4648 dst->append(")");
4649 }
4650 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004651 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004652 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4653 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004654 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004655 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004656
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004657 dst->append("\n");
4658 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4659 dst->append("\n");
4660 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004661 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004662 mOutputs.dump(dst);
4663 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004664 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004665 mAudioPatches.dump(dst);
4666 mPolicyMixes.dump(dst);
4667 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004668
Kevin Rocardb99cc752019-03-21 20:52:24 -07004669 dst->appendFormat(" AllowedCapturePolicies:\n");
4670 for (auto& policy : mAllowedCapturePolicies) {
4671 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4672 }
4673
jiabina84c3d32022-12-02 18:59:55 +00004674 dst->appendFormat(" Preferred mixer audio configuration:\n");
4675 for (const auto it : mPreferredMixerAttrInfos) {
4676 dst->appendFormat(" - device port id: %d\n", it.first);
4677 for (const auto preferredMixerInfoIt : it.second) {
4678 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4679 preferredMixerInfoIt.second->dump(dst);
4680 }
4681 }
4682
François Gaffiec005e562018-11-06 15:04:49 +01004683 dst->appendFormat("\nPolicy Engine dump:\n");
4684 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004685
4686 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4687 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4688 dst->appendFormat(" - device type: %s, driving stream %d\n",
4689 dumpDeviceTypes({it.first}).c_str(),
4690 mEngine->getVolumeGroupForAttributes(it.second));
4691 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004692}
4693
4694status_t AudioPolicyManager::dump(int fd)
4695{
4696 String8 result;
4697 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004698 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004699 return NO_ERROR;
4700}
4701
Kevin Rocardb99cc752019-03-21 20:52:24 -07004702status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4703{
4704 mAllowedCapturePolicies[uid] = capturePolicy;
4705 return NO_ERROR;
4706}
4707
Eric Laurente552edb2014-03-10 17:42:56 -07004708// This function checks for the parameters which can be offloaded.
4709// This can be enhanced depending on the capability of the DSP and policy
4710// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004711audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004712{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004713 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004714 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004715 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004716 offloadInfo.format,
4717 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4718 offloadInfo.has_video);
4719
jiabin2b9d5a12021-12-10 01:06:29 +00004720 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004721 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004722 }
4723
4724 // See if there is a profile to support this.
4725 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004726 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004727 offloadInfo.sample_rate,
4728 offloadInfo.format,
4729 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004730 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4731 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004732 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4733 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4734 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004735 if (profile == nullptr) {
4736 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4737 }
4738 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4739 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4740 }
4741 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004742}
4743
Michael Chana94fbb22018-04-24 14:31:19 +10004744bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4745 const audio_attributes_t& attributes) {
4746 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004747 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004748 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4749 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004750 config.sample_rate,
4751 config.format,
4752 config.channel_mask,
4753 output_flags,
4754 true /* directOnly */);
4755 ALOGV("%s() profile %sfound with name: %s, "
4756 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4757 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004758 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004759 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004760
4761 // also try the MSD module if compatible profile not found
4762 if (profile == nullptr) {
4763 profile = getMsdProfileForOutput(outputDevices,
4764 config.sample_rate,
4765 config.format,
4766 config.channel_mask,
4767 output_flags,
4768 true /* directOnly */);
4769 ALOGV("%s() MSD profile %sfound with name: %s, "
4770 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4771 __FUNCTION__, profile != 0 ? "" : "NOT ",
4772 (profile != 0 ? profile->getTagName().c_str() : "null"),
4773 config.sample_rate, config.format, config.channel_mask, output_flags);
4774 }
4775 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004776}
4777
jiabin2b9d5a12021-12-10 01:06:29 +00004778bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4779 bool durationIgnored) {
4780 if (mMasterMono) {
4781 return false; // no offloading if mono is set.
4782 }
4783
4784 // Check if offload has been disabled
4785 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4786 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4787 return false;
4788 }
4789
4790 // Check if stream type is music, then only allow offload as of now.
4791 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4792 {
4793 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4794 return false;
4795 }
4796
4797 //TODO: enable audio offloading with video when ready
4798 const bool allowOffloadWithVideo =
4799 property_get_bool("audio.offload.video", false /* default_value */);
4800 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4801 ALOGV("%s: has_video == true, returning false", __func__);
4802 return false;
4803 }
4804
4805 //If duration is less than minimum value defined in property, return false
4806 const int min_duration_secs = property_get_int32(
4807 "audio.offload.min.duration.secs", -1 /* default_value */);
4808 if (!durationIgnored) {
4809 if (min_duration_secs >= 0) {
4810 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4811 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4812 __func__, min_duration_secs);
4813 return false;
4814 }
4815 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4816 ALOGV("%s: Offload denied by duration < default min(=%u)",
4817 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4818 return false;
4819 }
4820 }
4821
4822 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4823 // creating an offloaded track and tearing it down immediately after start when audioflinger
4824 // detects there is an active non offloadable effect.
4825 // FIXME: We should check the audio session here but we do not have it in this context.
4826 // This may prevent offloading in rare situations where effects are left active by apps
4827 // in the background.
4828 if (mEffects.isNonOffloadableEffectEnabled()) {
4829 return false;
4830 }
4831
4832 return true;
4833}
4834
4835audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4836 const audio_config_t *config) {
4837 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4838 offloadInfo.format = config->format;
4839 offloadInfo.sample_rate = config->sample_rate;
4840 offloadInfo.channel_mask = config->channel_mask;
4841 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4842 offloadInfo.has_video = false;
4843 offloadInfo.is_streaming = false;
4844 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4845
4846 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4847 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4848 audio_flags_to_audio_output_flags(attr->flags, &flags);
4849 // only retain flags that will drive compressed offload or passthrough
4850 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4851 if (offloadPossible) {
4852 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4853 }
4854 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4855
Dorin Drimusfae3c642022-03-17 18:36:30 +01004856 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004857 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4858 [this, attr](sp<DeviceDescriptor> device) {
4859 return getPreferredMixerAttributesInfo(
4860 device->getId(),
4861 mEngine->getProductStrategyForAttributes(*attr),
4862 true /*activeBitPerfectPreferred*/) != nullptr;
4863 })) {
4864 // Bit-perfect playback is active on one of the selected devices, direct output will
4865 // be rejected at this instant.
4866 return AUDIO_DIRECT_NOT_SUPPORTED;
4867 }
jiabin2b9d5a12021-12-10 01:06:29 +00004868 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004869 DeviceVector outputDevices = engineOutputDevices;
4870 // the MSD module checks for different conditions and output devices
4871 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4872 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4873 continue;
4874 }
4875 outputDevices = getMsdAudioOutDevices();
4876 }
jiabin2b9d5a12021-12-10 01:06:29 +00004877 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004878 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004879 config->sample_rate, nullptr /*updatedSamplingRate*/,
4880 config->format, nullptr /*updatedFormat*/,
4881 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004882 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004883 continue;
4884 }
4885 // reject profiles not corresponding to a device currently available
4886 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4887 continue;
4888 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004889 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4890 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004891 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004892 != AUDIO_DIRECT_NOT_SUPPORTED) {
4893 // Already reports offload gapless supported. No need to report offload support.
4894 continue;
4895 }
4896 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4897 != AUDIO_OUTPUT_FLAG_NONE) {
4898 // If offload gapless is reported, no need to report offload support.
4899 directMode = (audio_direct_mode_t) ((directMode &
4900 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4901 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4902 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004903 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004904 }
4905 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004906 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004907 }
4908 }
4909 }
4910 return directMode;
4911}
4912
Dorin Drimusf2196d82022-01-03 12:11:18 +01004913status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4914 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004915 if (mEffects.isNonOffloadableEffectEnabled()) {
4916 return OK;
4917 }
jiabinf1c73972022-04-14 16:28:52 -07004918 DeviceVector devices;
4919 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004920 if (status != OK) {
4921 return status;
4922 }
4923 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4924 if (devices.empty()) {
4925 return OK; // no output devices for the attributes
4926 }
jiabinf1c73972022-04-14 16:28:52 -07004927 return getProfilesForDevices(devices, audioProfilesVector,
4928 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004929}
4930
jiabina84c3d32022-12-02 18:59:55 +00004931status_t AudioPolicyManager::getSupportedMixerAttributes(
4932 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4933 ALOGV("%s, portId=%d", __func__, portId);
4934 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4935 if (deviceDescriptor == nullptr) {
4936 ALOGE("%s the requested device is currently unavailable", __func__);
4937 return BAD_VALUE;
4938 }
jiabin96daffc2023-05-11 17:51:55 +00004939 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4940 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4941 deviceDescriptor->type());
4942 return BAD_VALUE;
4943 }
jiabina84c3d32022-12-02 18:59:55 +00004944 for (const auto& hwModule : mHwModules) {
4945 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4946 if (curProfile->supportsDevice(deviceDescriptor)) {
4947 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4948 }
4949 }
4950 }
4951 return NO_ERROR;
4952}
4953
4954status_t AudioPolicyManager::setPreferredMixerAttributes(
4955 const audio_attributes_t *attr,
4956 audio_port_handle_t portId,
4957 uid_t uid,
4958 const audio_mixer_attributes_t *mixerAttributes) {
4959 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4960 "mixerBehavior=%d}, uid=%d, portId=%u",
4961 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4962 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4963 mixerAttributes->mixer_behavior, uid, portId);
4964 if (attr->usage != AUDIO_USAGE_MEDIA) {
4965 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4966 return BAD_VALUE;
4967 }
4968 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4969 if (deviceDescriptor == nullptr) {
4970 ALOGE("%s the requested device is currently unavailable", __func__);
4971 return BAD_VALUE;
4972 }
4973 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4974 ALOGE("%s(%d), type=%d, is not a usb output device",
4975 __func__, portId, deviceDescriptor->type());
4976 return BAD_VALUE;
4977 }
4978
4979 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4980 audio_flags_to_audio_output_flags(attr->flags, &flags);
4981 flags = (audio_output_flags_t) (flags |
4982 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4983 sp<IOProfile> profile = nullptr;
4984 DeviceVector devices(deviceDescriptor);
4985 for (const auto& hwModule : mHwModules) {
4986 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4987 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004988 && curProfile->getCompatibilityScore(
4989 devices,
4990 mixerAttributes->config.sample_rate,
4991 nullptr /*updatedSamplingRate*/,
4992 mixerAttributes->config.format,
4993 nullptr /*updatedFormat*/,
4994 mixerAttributes->config.channel_mask,
4995 nullptr /*updatedChannelMask*/,
4996 flags,
4997 false /*exactMatchRequiredForInputFlags*/)
4998 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004999 profile = curProfile;
5000 break;
5001 }
5002 }
5003 }
5004 if (profile == nullptr) {
5005 ALOGE("%s, there is no compatible profile found", __func__);
5006 return BAD_VALUE;
5007 }
5008
5009 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5010 sp<PreferredMixerAttributesInfo>::make(
5011 uid, portId, profile, flags, *mixerAttributes);
5012 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5013 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5014
5015 // If 1) there is any client from the preferred mixer configuration owner that is currently
5016 // active and matches the strategy and 2) current output is on the preferred device and the
5017 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5018 // configuration.
5019 std::vector<audio_io_handle_t> outputsToReopen;
5020 for (size_t i = 0; i < mOutputs.size(); i++) {
5021 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005022 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5023 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005024 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005025 } else {
5026 for (const auto &client: output->getActiveClients()) {
5027 if (client->uid() == uid && client->strategy() == strategy) {
5028 client->setIsInvalid();
5029 outputsToReopen.push_back(output->mIoHandle);
5030 }
jiabina84c3d32022-12-02 18:59:55 +00005031 }
5032 }
5033 }
5034 }
5035 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5036 config.sample_rate = mixerAttributes->config.sample_rate;
5037 config.channel_mask = mixerAttributes->config.channel_mask;
5038 config.format = mixerAttributes->config.format;
5039 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005040 sp<SwAudioOutputDescriptor> desc =
5041 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5042 if (desc == nullptr) {
5043 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5044 continue;
5045 }
jiabin220eea12024-05-17 17:55:20 +00005046 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005047 }
5048
5049 return NO_ERROR;
5050}
5051
5052sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005053 audio_port_handle_t devicePortId,
5054 product_strategy_t strategy,
5055 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005056 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5057 if (it == mPreferredMixerAttrInfos.end()) {
5058 return nullptr;
5059 }
jiabind9a58d32023-06-01 17:57:30 +00005060 if (activeBitPerfectPreferred) {
5061 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005062 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005063 return info;
5064 }
5065 }
jiabina84c3d32022-12-02 18:59:55 +00005066 }
jiabind9a58d32023-06-01 17:57:30 +00005067 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5068 return strategyMatchedMixerAttrInfoIt == it->second.end()
5069 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005070}
5071
5072status_t AudioPolicyManager::getPreferredMixerAttributes(
5073 const audio_attributes_t *attr,
5074 audio_port_handle_t portId,
5075 audio_mixer_attributes_t* mixerAttributes) {
5076 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5077 portId, mEngine->getProductStrategyForAttributes(*attr));
5078 if (info == nullptr) {
5079 return NAME_NOT_FOUND;
5080 }
5081 *mixerAttributes = info->getMixerAttributes();
5082 return NO_ERROR;
5083}
5084
5085status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5086 audio_port_handle_t portId,
5087 uid_t uid) {
5088 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5089 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5090 if (preferredMixerAttrInfo == nullptr) {
5091 return NAME_NOT_FOUND;
5092 }
5093 if (preferredMixerAttrInfo->getUid() != uid) {
5094 ALOGE("%s, requested uid=%d, owned uid=%d",
5095 __func__, uid, preferredMixerAttrInfo->getUid());
5096 return PERMISSION_DENIED;
5097 }
5098 mPreferredMixerAttrInfos[portId].erase(strategy);
5099 if (mPreferredMixerAttrInfos[portId].empty()) {
5100 mPreferredMixerAttrInfos.erase(portId);
5101 }
5102
5103 // Reconfig existing output
5104 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5105 for (size_t i = 0; i < mOutputs.size(); i++) {
5106 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5107 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5108 }
5109 }
5110 for (const auto output : potentialOutputsToReopen) {
5111 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5112 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5113 preferredMixerAttrInfo->getFlags())) {
5114 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5115 }
5116 }
5117 return NO_ERROR;
5118}
5119
Eric Laurent6a94d692014-05-20 11:18:06 -07005120status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5121 audio_port_type_t type,
5122 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005123 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 unsigned int *generation)
5125{
jiabin19cdba52020-11-24 11:28:58 -08005126 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5127 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005128 return BAD_VALUE;
5129 }
5130 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005131 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 *num_ports = 0;
5133 }
5134
5135 size_t portsWritten = 0;
5136 size_t portsMax = *num_ports;
5137 *num_ports = 0;
5138 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005139 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5140 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005142 for (const auto& dev : mAvailableOutputDevices) {
5143 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005144 continue;
5145 }
5146 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005147 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005148 }
5149 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005150 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005151 }
5152 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005153 for (const auto& dev : mAvailableInputDevices) {
5154 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005155 continue;
5156 }
5157 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005158 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005159 }
5160 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005161 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005162 }
5163 }
5164 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5165 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5166 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5167 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5168 }
5169 *num_ports += mInputs.size();
5170 }
5171 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005172 size_t numOutputs = 0;
5173 for (size_t i = 0; i < mOutputs.size(); i++) {
5174 if (!mOutputs[i]->isDuplicated()) {
5175 numOutputs++;
5176 if (portsWritten < portsMax) {
5177 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5178 }
5179 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 }
Eric Laurent84c70242014-06-23 08:46:27 -07005181 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 }
5183 }
jiabina84c3d32022-12-02 18:59:55 +00005184
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005186 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 return NO_ERROR;
5188}
5189
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005190status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5191 std::vector<media::AudioPortFw>* _aidl_return) {
5192 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5193 audio_port_v7 port;
5194 dev->toAudioPort(&port);
5195 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5196 _aidl_return->push_back(std::move(aidlPort));
5197 return OK;
5198 };
5199
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005200 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005201 for (const auto& dev : module->getDeclaredDevices()) {
5202 if (role == media::AudioPortRole::NONE ||
5203 ((role == media::AudioPortRole::SOURCE)
5204 == audio_is_input_device(dev->type()))) {
5205 RETURN_STATUS_IF_ERROR(pushPort(dev));
5206 }
5207 }
5208 }
5209 return OK;
5210}
5211
jiabin19cdba52020-11-24 11:28:58 -08005212status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005213{
Eric Laurent99fcae42018-05-17 16:59:18 -07005214 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5215 return BAD_VALUE;
5216 }
5217 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5218 if (dev != 0) {
5219 dev->toAudioPort(port);
5220 return NO_ERROR;
5221 }
5222 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5223 if (dev != 0) {
5224 dev->toAudioPort(port);
5225 return NO_ERROR;
5226 }
5227 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5228 if (out != 0) {
5229 out->toAudioPort(port);
5230 return NO_ERROR;
5231 }
5232 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5233 if (in != 0) {
5234 in->toAudioPort(port);
5235 return NO_ERROR;
5236 }
5237 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005238}
5239
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005240status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5241 audio_patch_handle_t *handle,
5242 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005243{
François Gaffieafd4cea2019-11-18 15:50:22 +01005244 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 if (handle == NULL || patch == NULL) {
5246 return BAD_VALUE;
5247 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005248 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005249 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005250 return BAD_VALUE;
5251 }
5252 // only one source per audio patch supported for now
5253 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 return INVALID_OPERATION;
5255 }
Eric Laurent874c42872014-08-08 15:13:39 -07005256 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 return INVALID_OPERATION;
5258 }
Eric Laurent874c42872014-08-08 15:13:39 -07005259 for (size_t i = 0; i < patch->num_sinks; i++) {
5260 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5261 return INVALID_OPERATION;
5262 }
5263 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005264
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005265 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5266 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5267 if (srcDevice == nullptr || sinkDevice == nullptr) {
5268 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5269 return BAD_VALUE;
5270 }
5271 ALOGV("%s between source %s and sink %s", __func__,
5272 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5273 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5274 // Default attributes, default volume priority, not to infer with non raw audio patches.
5275 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5276 const struct audio_port_config *source = &patch->sources[0];
5277 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005278 new SourceClientDescriptor(
5279 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5280 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005281 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005282 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005283
5284 status_t status =
5285 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5286
5287 if (status != NO_ERROR) {
5288 return INVALID_OPERATION;
5289 }
5290 mAudioSources.add(portId, sourceDesc);
5291 return NO_ERROR;
5292}
5293
5294status_t AudioPolicyManager::connectAudioSourceToSink(
5295 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5296 const struct audio_patch *patch,
5297 audio_patch_handle_t &handle,
5298 uid_t uid, uint32_t delayMs)
5299{
5300 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5301 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5302 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5303 return INVALID_OPERATION;
5304 }
5305 sourceDesc->connect(handle, sinkDevice);
5306 if (isMsdPatch(handle)) {
5307 return NO_ERROR;
5308 }
5309 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5310 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5311 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5312 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5313 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5314 goto FailurePatchAdded;
5315 }
5316 status = swOutput->start();
5317 if (status != NO_ERROR) {
5318 goto FailureSourceAdded;
5319 }
5320 swOutput->addClient(sourceDesc);
5321 status = startSource(swOutput, sourceDesc, &delayMs);
5322 if (status != NO_ERROR) {
5323 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5324 goto FailureSourceActive;
5325 }
5326 if (delayMs != 0) {
5327 usleep(delayMs * 1000);
5328 }
5329 return NO_ERROR;
5330
5331FailureSourceActive:
5332 swOutput->stop();
5333 releaseOutput(sourceDesc->portId());
5334FailureSourceAdded:
5335 sourceDesc->setSwOutput(nullptr);
5336FailurePatchAdded:
5337 releaseAudioPatchInternal(handle);
5338 return INVALID_OPERATION;
5339}
5340
5341status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5342 audio_patch_handle_t *handle,
5343 uid_t uid, uint32_t delayMs,
5344 const sp<SourceClientDescriptor>& sourceDesc)
5345{
5346 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 sp<AudioPatch> patchDesc;
5348 ssize_t index = mAudioPatches.indexOfKey(*handle);
5349
François Gaffieafd4cea2019-11-18 15:50:22 +01005350 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5351 patch->sources[0].role,
5352 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005353#if LOG_NDEBUG == 0
5354 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005355 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5356 patch->sinks[i].role,
5357 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005358 }
5359#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005360
5361 if (index >= 0) {
5362 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005363 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5364 __func__, mUidCached, patchDesc->getUid(), uid);
5365 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 return INVALID_OPERATION;
5367 }
5368 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005369 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 }
5371
5372 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005373 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005375 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 return BAD_VALUE;
5377 }
Eric Laurent84c70242014-06-23 08:46:27 -07005378 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5379 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 if (patchDesc != 0) {
5381 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005382 ALOGV("%s source id differs for patch current id %d new id %d",
5383 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 return BAD_VALUE;
5385 }
5386 }
Eric Laurent874c42872014-08-08 15:13:39 -07005387 DeviceVector devices;
5388 for (size_t i = 0; i < patch->num_sinks; i++) {
5389 // Only support mix to devices connection
5390 // TODO add support for mix to mix connection
5391 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005392 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005393 return INVALID_OPERATION;
5394 }
5395 sp<DeviceDescriptor> devDesc =
5396 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5397 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005398 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005399 return BAD_VALUE;
5400 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005401
jiabin66acc432024-02-06 00:57:36 +00005402 if (outputDesc->mProfile->getCompatibilityScore(
5403 DeviceVector(devDesc),
5404 patch->sources[0].sample_rate,
5405 nullptr, // updatedSamplingRate
5406 patch->sources[0].format,
5407 nullptr, // updatedFormat
5408 patch->sources[0].channel_mask,
5409 nullptr, // updatedChannelMask
5410 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005411 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005412 return INVALID_OPERATION;
5413 }
5414 devices.add(devDesc);
5415 }
5416 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005417 return INVALID_OPERATION;
5418 }
Eric Laurent874c42872014-08-08 15:13:39 -07005419
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005421 ALOGV("%s setting device %s on output %d",
5422 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305423 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005424 index = mAudioPatches.indexOfKey(*handle);
5425 if (index >= 0) {
5426 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005427 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 }
5429 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005430 patchDesc->setUid(uid);
5431 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005432 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005433 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005434 return INVALID_OPERATION;
5435 }
5436 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5437 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5438 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005439 // only one sink supported when connecting an input device to a mix
5440 if (patch->num_sinks > 1) {
5441 return INVALID_OPERATION;
5442 }
François Gaffie53615e22015-03-19 09:24:12 +01005443 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 if (inputDesc == NULL) {
5445 return BAD_VALUE;
5446 }
5447 if (patchDesc != 0) {
5448 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5449 return BAD_VALUE;
5450 }
5451 }
François Gaffie11d30102018-11-02 16:09:09 +01005452 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005453 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005454 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 return BAD_VALUE;
5456 }
5457
jiabin66acc432024-02-06 00:57:36 +00005458 if (inputDesc->mProfile->getCompatibilityScore(
5459 DeviceVector(device),
5460 patch->sinks[0].sample_rate,
5461 nullptr, /*updatedSampleRate*/
5462 patch->sinks[0].format,
5463 nullptr, /*updatedFormat*/
5464 patch->sinks[0].channel_mask,
5465 nullptr, /*updatedChannelMask*/
5466 // FIXME for the parameter type,
5467 // and the NONE
5468 (audio_output_flags_t)
5469 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005470 return INVALID_OPERATION;
5471 }
5472 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005473 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005474 device->toString().c_str(), inputDesc->mIoHandle);
5475 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005476 index = mAudioPatches.indexOfKey(*handle);
5477 if (index >= 0) {
5478 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005479 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005480 }
5481 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005482 patchDesc->setUid(uid);
5483 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005484 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005485 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005486 return INVALID_OPERATION;
5487 }
5488 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5489 // device to device connection
5490 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005491 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005492 return BAD_VALUE;
5493 }
5494 }
François Gaffie11d30102018-11-02 16:09:09 +01005495 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005496 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005497 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005498 return BAD_VALUE;
5499 }
Eric Laurent874c42872014-08-08 15:13:39 -07005500
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 //update source and sink with our own data as the data passed in the patch may
5502 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005503 PatchBuilder patchBuilder;
5504 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005505
5506 // if first sink is to MSD, establish single MSD patch
5507 if (getMsdAudioOutDevices().contains(
5508 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5509 ALOGV("%s patching to MSD", __FUNCTION__);
5510 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5511 goto installPatch;
5512 }
5513
François Gaffieafd4cea2019-11-18 15:50:22 +01005514 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5515 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005516
Eric Laurent874c42872014-08-08 15:13:39 -07005517 for (size_t i = 0; i < patch->num_sinks; i++) {
5518 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005519 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005520 return INVALID_OPERATION;
5521 }
François Gaffie11d30102018-11-02 16:09:09 +01005522 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005523 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005524 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005525 return BAD_VALUE;
5526 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005527 audio_port_config sinkPortConfig = {};
5528 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5529 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005530
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005531 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5532 // volume management purpose (tracking activity)
5533 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5534 // in config XML to reach the sink so that is can be declared as available.
5535 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005536 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005537 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005538 // take care of dynamic routing for SwOutput selection,
5539 audio_attributes_t attributes = sourceDesc->attributes();
5540 audio_stream_type_t stream = sourceDesc->stream();
5541 audio_attributes_t resultAttr;
5542 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5543 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005544 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5545 config.channel_mask =
5546 (audio_channel_mask_get_representation(sourceMask)
5547 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5548 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005549 config.format = sourceDesc->config().format;
5550 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5551 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5552 bool isRequestedDeviceForExclusiveUse = false;
5553 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005554 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005555 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005556 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5557 &stream, sourceDesc->uid(), &config, &flags,
5558 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005559 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005560 if (output == AUDIO_IO_HANDLE_NONE) {
5561 ALOGV("%s no output for device %s",
5562 __FUNCTION__, sinkDevice->toString().c_str());
5563 return INVALID_OPERATION;
5564 }
5565 outputDesc = mOutputs.valueFor(output);
5566 if (outputDesc->isDuplicated()) {
5567 ALOGE("%s output is duplicated", __func__);
5568 return INVALID_OPERATION;
5569 }
François Gaffie7e39df22022-04-26 12:48:49 +02005570 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5571 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005572 } else {
5573 // Same for "raw patches" aka created from createAudioPatch API
5574 SortedVector<audio_io_handle_t> outputs =
5575 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5576 // if the sink device is reachable via an opened output stream, request to
5577 // go via this output stream by adding a second source to the patch
5578 // description
5579 output = selectOutput(outputs);
5580 if (output == AUDIO_IO_HANDLE_NONE) {
5581 ALOGE("%s no output available for internal patch sink", __func__);
5582 return INVALID_OPERATION;
5583 }
5584 outputDesc = mOutputs.valueFor(output);
5585 if (outputDesc->isDuplicated()) {
5586 ALOGV("%s output for device %s is duplicated",
5587 __func__, sinkDevice->toString().c_str());
5588 return INVALID_OPERATION;
5589 }
François Gaffie7e39df22022-04-26 12:48:49 +02005590 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005591 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005592 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005593 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005594 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005595 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005596 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5597 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005598 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5599 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005600 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005601 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005602 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005603 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005604 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005605 return INVALID_OPERATION;
5606 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005607 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005608 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005609 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005610 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005611 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005612 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005613 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005614 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5615 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005616 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005617 }
Eric Laurent83b88082014-06-20 18:31:16 -07005618 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005619 }
5620 // TODO: check from routing capabilities in config file and other conflicting patches
5621
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005622installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005623 status_t status = installPatch(
5624 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005625 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005626 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005627 return INVALID_OPERATION;
5628 }
5629 } else {
5630 return BAD_VALUE;
5631 }
5632 } else {
5633 return BAD_VALUE;
5634 }
5635 return NO_ERROR;
5636}
5637
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005638status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005639{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005640 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005641 ssize_t index = mAudioPatches.indexOfKey(handle);
5642
5643 if (index < 0) {
5644 return BAD_VALUE;
5645 }
5646 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005647 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5648 __func__, mUidCached, patchDesc->getUid(), uid);
5649 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005650 return INVALID_OPERATION;
5651 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005652 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5653 for (size_t i = 0; i < mAudioSources.size(); i++) {
5654 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5655 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5656 portId = sourceDesc->portId();
5657 break;
5658 }
5659 }
5660 return portId != AUDIO_PORT_HANDLE_NONE ?
5661 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005662}
Eric Laurent6a94d692014-05-20 11:18:06 -07005663
François Gaffieafd4cea2019-11-18 15:50:22 +01005664status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005665 uint32_t delayMs,
5666 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005667{
5668 ALOGV("%s patch %d", __func__, handle);
5669 if (mAudioPatches.indexOfKey(handle) < 0) {
5670 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5671 return BAD_VALUE;
5672 }
5673 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005674 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005675 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005676 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005677 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005678 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005679 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005680 return BAD_VALUE;
5681 }
5682
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305683 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005684 getNewOutputDevices(outputDesc, true /*fromCache*/),
5685 true,
5686 0,
5687 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005688 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5689 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005690 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005691 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005692 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005693 return BAD_VALUE;
5694 }
5695 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005696 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005697 true,
5698 NULL);
5699 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005700 status_t status =
5701 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5702 ALOGV("%s patch panel returned %d patchHandle %d",
5703 __func__, status, patchDesc->getAfHandle());
5704 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005705 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005706 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005707 // SW or HW Bridge
5708 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5709 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005710 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005711 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5712 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5713 outputDesc = sourceDesc->swOutput().promote();
5714 }
5715 if (outputDesc == nullptr) {
5716 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5717 // releaseOutput has already called closeOutput in case of direct output
5718 return NO_ERROR;
5719 }
François Gaffie7e39df22022-04-26 12:48:49 +02005720 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005721 // While using a HwBridge, force reconsidering device only if not reusing an existing
5722 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005723 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005724 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5725 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5726 // Reconsider device only for cases:
5727 // 1 / Active Output
5728 // 2 / Inactive Output previously hosting HwBridge
5729 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5730 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5731 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305732 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005733 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5734 outputDesc->devices(),
5735 force,
5736 0,
5737 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005738 } else {
5739 return BAD_VALUE;
5740 }
5741 } else {
5742 return BAD_VALUE;
5743 }
5744 return NO_ERROR;
5745}
5746
5747status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5748 struct audio_patch *patches,
5749 unsigned int *generation)
5750{
François Gaffie53615e22015-03-19 09:24:12 +01005751 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005752 return BAD_VALUE;
5753 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005754 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005755 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005756}
5757
Eric Laurente1715a42014-05-20 11:30:42 -07005758status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005759{
Eric Laurente1715a42014-05-20 11:30:42 -07005760 ALOGV("setAudioPortConfig()");
5761
5762 if (config == NULL) {
5763 return BAD_VALUE;
5764 }
5765 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5766 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005767 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5768 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005769 }
5770
Eric Laurenta121f902014-06-03 13:32:54 -07005771 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005772 if (config->type == AUDIO_PORT_TYPE_MIX) {
5773 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005774 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005775 if (outputDesc == NULL) {
5776 return BAD_VALUE;
5777 }
Eric Laurent84c70242014-06-23 08:46:27 -07005778 ALOG_ASSERT(!outputDesc->isDuplicated(),
5779 "setAudioPortConfig() called on duplicated output %d",
5780 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005781 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005782 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005783 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005784 if (inputDesc == NULL) {
5785 return BAD_VALUE;
5786 }
Eric Laurenta121f902014-06-03 13:32:54 -07005787 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005788 } else {
5789 return BAD_VALUE;
5790 }
5791 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5792 sp<DeviceDescriptor> deviceDesc;
5793 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5794 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5795 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5796 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5797 } else {
5798 return BAD_VALUE;
5799 }
5800 if (deviceDesc == NULL) {
5801 return BAD_VALUE;
5802 }
Eric Laurenta121f902014-06-03 13:32:54 -07005803 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005804 } else {
5805 return BAD_VALUE;
5806 }
5807
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005808 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005809 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5810 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005811 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005812 audioPortConfig->toAudioPortConfig(&newConfig, config);
5813 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005814 }
Eric Laurenta121f902014-06-03 13:32:54 -07005815 if (status != NO_ERROR) {
5816 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005817 }
Eric Laurente1715a42014-05-20 11:30:42 -07005818
5819 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005820}
5821
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005822void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5823{
Eric Laurentd60560a2015-04-10 11:31:20 -07005824 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005825 clearAudioPatches(uid);
5826 clearSessionRoutes(uid);
5827}
5828
Eric Laurent6a94d692014-05-20 11:18:06 -07005829void AudioPolicyManager::clearAudioPatches(uid_t uid)
5830{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005831 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005832 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005833 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005834 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005835 }
5836 }
5837}
5838
François Gaffiec005e562018-11-06 15:04:49 +01005839void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005840{
François Gaffiec005e562018-11-06 15:04:49 +01005841 // Take the first attributes following the product strategy as it is used to retrieve the routed
5842 // device. All attributes wihin a strategy follows the same "routing strategy"
5843 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5844 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005845 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005846 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005847 for (size_t j = 0; j < mOutputs.size(); j++) {
5848 if (mOutputs.keyAt(j) == ouptutToSkip) {
5849 continue;
5850 }
5851 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005852 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005853 continue;
5854 }
5855 // If the default device for this strategy is on another output mix,
5856 // invalidate all tracks in this strategy to force re connection.
5857 // Otherwise select new device on the output mix.
5858 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005859 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005860 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005861 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005862 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005863 // If the device is using preferred mixer attributes, the output need to reopen
5864 // with default configuration when the new selected devices are different from
5865 // current routing devices.
5866 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5867 continue;
5868 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305869 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005870 }
5871 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005872 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005873}
5874
5875void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5876{
5877 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005878 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005879 for (size_t i = 0; i < mOutputs.size(); i++) {
5880 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005881 for (const auto& client : outputDesc->getClientIterable()) {
5882 if (client->hasPreferredDevice() && client->uid() == uid) {
5883 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005884 auto clientStrategy = client->strategy();
5885 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5886 end(affectedStrategies)) {
5887 continue;
5888 }
5889 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005890 }
5891 }
5892 }
5893 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005894 for (const auto& strategy : affectedStrategies) {
5895 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005896 }
5897
5898 // remove input routes associated with this uid
5899 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005900 for (size_t i = 0; i < mInputs.size(); i++) {
5901 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005902 for (const auto& client : inputDesc->getClientIterable()) {
5903 if (client->hasPreferredDevice() && client->uid() == uid) {
5904 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5905 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005906 }
5907 }
5908 }
5909 // reroute inputs if necessary
5910 SortedVector<audio_io_handle_t> inputsToClose;
5911 for (size_t i = 0; i < mInputs.size(); i++) {
5912 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005913 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005914 inputsToClose.add(inputDesc->mIoHandle);
5915 }
5916 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005917 for (const auto& input : inputsToClose) {
5918 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005919 }
5920}
5921
Eric Laurentd60560a2015-04-10 11:31:20 -07005922void AudioPolicyManager::clearAudioSources(uid_t uid)
5923{
5924 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005925 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5926 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005927 stopAudioSource(mAudioSources.keyAt(i));
5928 }
5929 }
5930}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005931
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005932status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5933 audio_io_handle_t *ioHandle,
5934 audio_devices_t *device)
5935{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005936 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5937 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005938 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005939 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5940 if (deviceDesc == nullptr) {
5941 return INVALID_OPERATION;
5942 }
5943 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005944
François Gaffiedf372692015-03-19 10:43:27 +01005945 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005946}
5947
Eric Laurentd60560a2015-04-10 11:31:20 -07005948status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005949 const audio_attributes_t *attributes,
5950 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005951 uid_t uid) {
5952 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005953 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005954}
5955
5956status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5957 const audio_attributes_t *attributes,
5958 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005959 uid_t uid, bool internal, bool isCallRx,
5960 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005961{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005962 ALOGV("%s", __FUNCTION__);
5963 *portId = AUDIO_PORT_HANDLE_NONE;
5964
5965 if (source == NULL || attributes == NULL || portId == NULL) {
5966 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5967 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005968 return BAD_VALUE;
5969 }
5970
Eric Laurentd60560a2015-04-10 11:31:20 -07005971 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5972 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005973 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5974 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005975 return INVALID_OPERATION;
5976 }
5977
François Gaffie11d30102018-11-02 16:09:09 +01005978 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005979 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005980 String8(source->ext.device.address),
5981 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005982 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005983 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005984 return BAD_VALUE;
5985 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005986
jiabin4ef93452019-09-10 14:29:54 -07005987 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005988
François Gaffieaaac0fd2018-11-22 17:56:39 +01005989 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005990 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005991 mEngine->getStreamTypeForAttributes(*attributes),
5992 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005993 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005994
David Lif85c5e32024-07-01 13:14:10 +00005995 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005996 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005997 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005998 }
5999 return status;
6000}
6001
David Lif85c5e32024-07-01 13:14:10 +00006002status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6003 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006004{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006005 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006006
6007 // make sure we only have one patch per source.
6008 disconnectAudioSource(sourceDesc);
6009
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006010 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006011 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6012 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6013 sourceDesc->srcDevice()->type(),
6014 String8(sourceDesc->srcDevice()->address().c_str()),
6015 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006016 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006017 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006018 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006019 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006020 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6021 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6022 return INVALID_OPERATION;
6023 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006024 PatchBuilder patchBuilder;
6025 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6026 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006027
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006028 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006029 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006030}
6031
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006032status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006033{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006034 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6035 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006036 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006037 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006038 return BAD_VALUE;
6039 }
6040 status_t status = disconnectAudioSource(sourceDesc);
6041
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006042 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006043 return status;
6044}
6045
Andy Hung2ddee192015-12-18 17:34:44 -08006046status_t AudioPolicyManager::setMasterMono(bool mono)
6047{
6048 if (mMasterMono == mono) {
6049 return NO_ERROR;
6050 }
6051 mMasterMono = mono;
6052 // if enabling mono we close all offloaded devices, which will invalidate the
6053 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6054 // for recreating the new AudioTrack as non-offloaded PCM.
6055 //
6056 // If disabling mono, we leave all tracks as is: we don't know which clients
6057 // and tracks are able to be recreated as offloaded. The next "song" should
6058 // play back offloaded.
6059 if (mMasterMono) {
6060 Vector<audio_io_handle_t> offloaded;
6061 for (size_t i = 0; i < mOutputs.size(); ++i) {
6062 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6063 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6064 offloaded.push(desc->mIoHandle);
6065 }
6066 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006067 for (const auto& handle : offloaded) {
6068 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006069 }
6070 }
6071 // update master mono for all remaining outputs
6072 for (size_t i = 0; i < mOutputs.size(); ++i) {
6073 updateMono(mOutputs.keyAt(i));
6074 }
6075 return NO_ERROR;
6076}
6077
6078status_t AudioPolicyManager::getMasterMono(bool *mono)
6079{
6080 *mono = mMasterMono;
6081 return NO_ERROR;
6082}
6083
Eric Laurentac9cef52017-06-09 15:46:26 -07006084float AudioPolicyManager::getStreamVolumeDB(
6085 audio_stream_type_t stream, int index, audio_devices_t device)
6086{
Vlad Popa9d482762024-06-21 16:40:23 -07006087 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6088 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006089}
6090
jiabin81772902018-04-02 17:52:27 -07006091status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6092 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006093 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006094{
Kriti Dang6537def2021-03-02 13:46:59 +01006095 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6096 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006097 return BAD_VALUE;
6098 }
Kriti Dang6537def2021-03-02 13:46:59 +01006099 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6100 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006101
6102 size_t formatsWritten = 0;
6103 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006104
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006105 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006106 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6107 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006108 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006109 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006110 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006111 bool formatEnabled = true;
6112 switch (forceUse) {
6113 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006114 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006115 break;
6116 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6117 formatEnabled = false;
6118 break;
6119 default: // AUTO or ALWAYS => true
6120 break;
jiabin81772902018-04-02 17:52:27 -07006121 }
6122 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6123 }
jiabin81772902018-04-02 17:52:27 -07006124 }
6125 return NO_ERROR;
6126}
6127
Kriti Dang6537def2021-03-02 13:46:59 +01006128status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6129 audio_format_t *surroundFormats) {
6130 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6131 return BAD_VALUE;
6132 }
6133 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6134 __func__, *numSurroundFormats, surroundFormats);
6135
6136 size_t formatsWritten = 0;
6137 size_t formatsMax = *numSurroundFormats;
6138 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6139
6140 // Return formats from all device profiles that have already been resolved by
6141 // checkOutputsForDevice().
6142 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6143 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6144 audio_devices_t deviceType = device->type();
6145 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6146 // returns formats reported by HDMI devices.
6147 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6148 continue;
6149 }
6150 // Formats reported by sink devices
6151 std::unordered_set<audio_format_t> formatset;
6152 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6153 formatset.insert(it->second.begin(), it->second.end());
6154 }
6155
6156 // Formats hard-coded in the in policy configuration file (if any).
6157 FormatVector encodedFormats = device->encodedFormats();
6158 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6159 // Filter the formats which are supported by the vendor hardware.
6160 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006161 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006162 formats.insert(*it);
6163 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006164 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006165 if (pair.second.count(*it) != 0) {
6166 formats.insert(pair.first);
6167 break;
6168 }
6169 }
6170 }
6171 }
6172 }
6173 *numSurroundFormats = formats.size();
6174 for (const auto& format: formats) {
6175 if (formatsWritten < formatsMax) {
6176 surroundFormats[formatsWritten++] = format;
6177 }
6178 }
6179 return NO_ERROR;
6180}
6181
jiabin81772902018-04-02 17:52:27 -07006182status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6183{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006184 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006185 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6186 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006187 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006188 return BAD_VALUE;
6189 }
6190
Mikhail Naganov100f0122018-11-29 11:22:16 -08006191 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6192 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006193 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006194 return INVALID_OPERATION;
6195 }
6196
Mikhail Naganov100f0122018-11-29 11:22:16 -08006197 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006198 return NO_ERROR;
6199 }
6200
Mikhail Naganov100f0122018-11-29 11:22:16 -08006201 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006202 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006203 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006204 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006205 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006206 }
6207 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006208 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006209 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006210 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006211 }
6212 }
6213
6214 sp<SwAudioOutputDescriptor> outputDesc;
6215 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006216 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6217 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006218 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6219 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006220 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006221 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006222 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6223 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6224 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006225 name.c_str(),
6226 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006227 if (status != NO_ERROR) {
6228 continue;
6229 }
6230 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6231 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6232 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006233 name.c_str(),
6234 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006235 profileUpdated |= (status == NO_ERROR);
6236 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006237 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006238 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006239 AUDIO_DEVICE_IN_HDMI);
6240 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6241 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006242 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006243 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006244 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6245 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6246 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006247 name.c_str(),
6248 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006249 if (status != NO_ERROR) {
6250 continue;
6251 }
6252 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6253 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6254 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006255 name.c_str(),
6256 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006257 profileUpdated |= (status == NO_ERROR);
6258 }
6259
jiabin81772902018-04-02 17:52:27 -07006260 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006261 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006262 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006263 }
6264
6265 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6266}
6267
Eric Laurent5ada82e2019-08-29 17:53:54 -07006268void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006269{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006270 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006271 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006272 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006273 }
6274}
6275
jiabin6012f912018-11-02 17:06:30 -07006276bool AudioPolicyManager::isHapticPlaybackSupported()
6277{
6278 for (const auto& hwModule : mHwModules) {
6279 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6280 for (const auto &outProfile : outputProfiles) {
6281 struct audio_port audioPort;
6282 outProfile->toAudioPort(&audioPort);
6283 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6284 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6285 return true;
6286 }
6287 }
6288 }
6289 }
6290 return false;
6291}
6292
Carter Hsu325a8eb2022-01-19 19:56:51 +08006293bool AudioPolicyManager::isUltrasoundSupported()
6294{
6295 bool hasUltrasoundOutput = false;
6296 bool hasUltrasoundInput = false;
6297 for (const auto& hwModule : mHwModules) {
6298 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6299 if (!hasUltrasoundOutput) {
6300 for (const auto &outProfile : outputProfiles) {
6301 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6302 hasUltrasoundOutput = true;
6303 break;
6304 }
6305 }
6306 }
6307
6308 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6309 if (!hasUltrasoundInput) {
6310 for (const auto &inputProfile : inputProfiles) {
6311 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6312 hasUltrasoundInput = true;
6313 break;
6314 }
6315 }
6316 }
6317
6318 if (hasUltrasoundOutput && hasUltrasoundInput)
6319 return true;
6320 }
6321 return false;
6322}
6323
Atneya Nair698f5ef2022-12-15 16:15:09 -08006324bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6325{
6326 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6327 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6328 for (const auto& hwModule : mHwModules) {
6329 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6330 for (const auto &inputProfile : inputProfiles) {
6331 if ((inputProfile->getFlags() & mask) == mask) {
6332 return true;
6333 }
6334 }
6335 }
6336 return false;
6337}
6338
Eric Laurent8340e672019-11-06 11:01:08 -08006339bool AudioPolicyManager::isCallScreenModeSupported()
6340{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006341 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006342}
6343
6344
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006345status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006346{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006347 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006348 if (!sourceDesc->isConnected()) {
6349 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6350 return NO_ERROR;
6351 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006352 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6353 if (swOutput != 0) {
6354 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006355 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006356 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006357 }
jiabinbce0c1d2020-10-05 11:20:18 -07006358 if (releaseOutput(sourceDesc->portId())) {
6359 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6360 // no need to release audio patch here but just return NO_ERROR.
6361 return NO_ERROR;
6362 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006363 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006364 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006365 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006366 // close Hwoutput and remove from mHwOutputs
6367 } else {
6368 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6369 }
6370 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006371 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006372 sourceDesc->disconnect();
6373 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006374}
6375
François Gaffiec005e562018-11-06 15:04:49 +01006376sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6377 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006378{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006379 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006380 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006381 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006382 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006383 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6384 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006385 source = sourceDesc;
6386 break;
6387 }
6388 }
6389 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006390}
6391
Eric Laurentb4f42a92022-01-17 17:37:31 +01006392bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006393 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006394 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006395{
6396 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6397 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006398 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006399 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006400 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6401 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6402 return false;
6403 }
6404 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6405 return false;
6406 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006407 }
6408
Eric Laurentd332bc82023-08-04 11:45:23 +02006409 // The caller can have the audio config criteria ignored by either passing a null ptr or
6410 // the AUDIO_CONFIG_INITIALIZER value.
6411 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006412 // some positional channel masks and PCM format and for stereo if low latency performance
6413 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006414
6415 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006416 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006417 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6418 ? audio_channel_mask_contains_stereo(config->channel_mask)
6419 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006420 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006421 return false;
6422 }
6423 if (!audio_is_linear_pcm(config->format)) {
6424 return false;
6425 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006426 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6427 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6428 return false;
6429 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006430 }
6431
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006432 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006433 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006434 if (profile == nullptr) {
6435 return false;
6436 }
6437
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006438 return true;
6439}
6440
Shunkai Yao4c3af932024-04-26 04:12:21 +00006441// The Spatializer output is compatible with Haptic use cases if:
6442// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6443// with client if client haptic channel bits were set, or
6444// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6445// including the haptic bits or creating the HapticGenerator effect for same session.
6446bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6447 const audio_config_t* config, audio_session_t sessionId) const {
6448 const auto clientHapticChannel =
6449 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6450 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6451 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6452
6453 if (threadOutputHapticChannel) {
6454 // check format and sampleRate match if client haptic channel mask exist
6455 if (clientHapticChannel) {
6456 return mSpatializerOutput->getFormat() == config->format &&
6457 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6458 }
6459 return true;
6460 } else {
6461 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6462 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6463 // HapticGenerator effect for this session) are not supported.
6464 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006465 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006466 }
6467}
6468
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006469void AudioPolicyManager::checkVirtualizerClientRoutes() {
6470 std::set<audio_stream_type_t> streamsToInvalidate;
6471 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006472 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6473 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006474 audio_attributes_t attr = client->attributes();
6475 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6476 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6477 audio_config_base_t clientConfig = client->config();
6478 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006479 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006480 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006481 streamsToInvalidate.insert(client->stream());
6482 }
6483 }
6484 }
6485
jiabinc44b3462022-12-08 12:52:31 -08006486 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006487}
6488
Eric Laurente191d1b2022-04-15 11:59:25 +02006489
6490bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6491 const sp<SwAudioOutputDescriptor>& outputDesc) {
6492 if (outputDesc->isDuplicated()) {
6493 return false;
6494 }
6495 DeviceVector devices = outputDesc->supportedDevices();
6496 for (size_t i = 0; i < mOutputs.size(); i++) {
6497 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6498 if (desc == outputDesc || desc->isDuplicated()) {
6499 continue;
6500 }
6501 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6502 if (!sharedDevices.isEmpty()
6503 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6504 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6505 return false;
6506 }
6507 }
6508 return true;
6509}
6510
6511
Eric Laurentfa0f6742021-08-17 18:39:44 +02006512status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006513 const audio_attributes_t *attr,
6514 audio_io_handle_t *output) {
6515 *output = AUDIO_IO_HANDLE_NONE;
6516
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006517 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6518 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6519 audio_config_t *configPtr = nullptr;
6520 audio_config_t config;
6521 if (mixerConfig != nullptr) {
6522 config = audio_config_initializer(mixerConfig);
6523 configPtr = &config;
6524 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006525 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006526 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006527 return BAD_VALUE;
6528 }
6529
6530 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006531 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006532 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006533 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006534 return BAD_VALUE;
6535 }
6536
Eric Laurente191d1b2022-04-15 11:59:25 +02006537 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006538 for (size_t i = 0; i < mOutputs.size(); i++) {
6539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006540 if (!desc->isDuplicated()
6541 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6542 spatializerOutputs.push_back(desc);
6543 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006544 }
6545 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006546 mSpatializerOutput.clear();
6547 bool outputsChanged = false;
6548 for (const auto& desc : spatializerOutputs) {
6549 if (desc->mProfile == profile
6550 && (configPtr == nullptr
6551 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6552 mSpatializerOutput = desc;
6553 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6554 } else {
6555 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6556 " and devices %s", __func__, desc->mIoHandle,
6557 configPtr != nullptr ? configPtr->channel_mask : 0,
6558 devices.toString().c_str());
6559 closeOutput(desc->mIoHandle);
6560 outputsChanged = true;
6561 }
Eric Laurent39095982021-08-24 18:29:27 +02006562 }
6563
Eric Laurente191d1b2022-04-15 11:59:25 +02006564 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006565 sp<SwAudioOutputDescriptor> desc =
6566 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006567 if (desc != nullptr) {
6568 mSpatializerOutput = desc;
6569 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006570 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006571 }
6572
6573 checkVirtualizerClientRoutes();
6574
Eric Laurente191d1b2022-04-15 11:59:25 +02006575 if (outputsChanged) {
6576 mPreviousOutputs = mOutputs;
6577 mpClientInterface->onAudioPortListUpdate();
6578 }
6579
6580 if (mSpatializerOutput == nullptr) {
6581 ALOGV("%s could not open spatializer output with requested config", __func__);
6582 return BAD_VALUE;
6583 }
Eric Laurent39095982021-08-24 18:29:27 +02006584 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006585 ALOGV("%s returning new spatializer output %d", __func__, *output);
6586 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006587}
6588
Eric Laurentfa0f6742021-08-17 18:39:44 +02006589status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6590 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006591 return INVALID_OPERATION;
6592 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006593 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006594 return BAD_VALUE;
6595 }
Eric Laurent39095982021-08-24 18:29:27 +02006596
Eric Laurente191d1b2022-04-15 11:59:25 +02006597 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6598 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6599 closeOutput(mSpatializerOutput->mIoHandle);
6600 //from now on mSpatializerOutput is null
6601 checkVirtualizerClientRoutes();
6602 }
Eric Laurent39095982021-08-24 18:29:27 +02006603
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006604 return NO_ERROR;
6605}
6606
Eric Laurente552edb2014-03-10 17:42:56 -07006607// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006608// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006609// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006610uint32_t AudioPolicyManager::nextAudioPortGeneration()
6611{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006612 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006613}
6614
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006615AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006616 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006617 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006618 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006619 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006620 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006621 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006622 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006623 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006624 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006625 mAudioPortGeneration(1),
6626 mBeaconMuteRefCount(0),
6627 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006628 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006629 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006630 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006631 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006632{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006633}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006634
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006635status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006636 if (mEngine == nullptr) {
6637 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006638 }
6639 mEngine->setObserver(this);
6640 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006641 if (status != NO_ERROR) {
6642 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6643 return status;
6644 }
François Gaffie2110e042015-03-24 08:41:51 +01006645
jiabin29230182023-04-04 21:02:36 +00006646 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6647 // at the end of this function.
6648 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006649 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6650 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6651
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006652 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006653 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006654 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006655
Eric Laurent3a4311c2014-03-17 12:00:47 -07006656 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006657 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6658 defaultOutputDevice == nullptr ||
6659 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6660 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6661 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006662 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006663 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006664 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006665
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006666 // Silence ALOGV statements
6667 property_set("log.tag." LOG_TAG, "D");
6668
Eric Laurente552edb2014-03-10 17:42:56 -07006669 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006670 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006671}
6672
Eric Laurente0720872014-03-11 09:30:41 -07006673AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006674{
Eric Laurente552edb2014-03-10 17:42:56 -07006675 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006676 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006677 }
6678 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006679 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006680 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006681 mAvailableOutputDevices.clear();
6682 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006683 mOutputs.clear();
6684 mInputs.clear();
6685 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006686 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006687 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006688}
6689
Eric Laurente0720872014-03-11 09:30:41 -07006690status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006691{
Eric Laurent87ffa392015-05-22 10:32:38 -07006692 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006693}
6694
Eric Laurente552edb2014-03-10 17:42:56 -07006695// ---
6696
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006697void AudioPolicyManager::onNewAudioModulesAvailable()
6698{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006699 DeviceVector newDevices;
6700 onNewAudioModulesAvailableInt(&newDevices);
6701 if (!newDevices.empty()) {
6702 nextAudioPortGeneration();
6703 mpClientInterface->onAudioPortListUpdate();
6704 }
6705}
6706
6707void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6708{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006709 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006710 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6711 continue;
6712 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006713 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006714 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6715 handle != AUDIO_MODULE_HANDLE_NONE) {
6716 hwModule->setHandle(handle);
6717 } else {
6718 ALOGW("could not load HW module %s", hwModule->getName());
6719 continue;
6720 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006721 }
6722 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006723 // open all output streams needed to access attached devices.
6724 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006725 // This also validates mAvailableOutputDevices list
6726 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6727 if (!outProfile->canOpenNewIo()) {
6728 ALOGE("Invalid Output profile max open count %u for profile %s",
6729 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6730 continue;
6731 }
6732 if (!outProfile->hasSupportedDevices()) {
6733 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6734 continue;
6735 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006736 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6737 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006738 mTtsOutputAvailable = true;
6739 }
6740
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006741 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006742 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006743 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006744 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6745 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006746 } else {
6747 // choose first device present in profile's SupportedDevices also part of
6748 // mAvailableOutputDevices.
6749 if (availProfileDevices.isEmpty()) {
6750 continue;
6751 }
6752 supportedDevice = availProfileDevices.itemAt(0);
6753 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006754 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006755 continue;
6756 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306757
6758 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6759 && availProfileDevices.areAllDevicesAttached()) {
6760 ALOGV("%s skip opening output for mmap profile %s", __func__,
6761 outProfile->getTagName().c_str());
6762 continue;
6763 }
6764
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006765 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6766 mpClientInterface);
6767 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006768 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006769 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6770 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006771 AUDIO_STREAM_DEFAULT,
Haofan Wangf6e304f2024-07-09 23:06:58 -07006772 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006773 if (status != NO_ERROR) {
6774 ALOGW("Cannot open output stream for devices %s on hw module %s",
6775 supportedDevice->toString().c_str(), hwModule->getName());
6776 continue;
6777 }
6778 for (const auto &device : availProfileDevices) {
6779 // give a valid ID to an attached device once confirmed it is reachable
6780 if (!device->isAttached()) {
6781 device->attach(hwModule);
6782 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006783 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006784 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006785 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6786 }
6787 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006788 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006789 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6790 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006791 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006792 }
Eric Laurent39095982021-08-24 18:29:27 +02006793 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006794 outputDesc->close();
6795 } else {
6796 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306797 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006798 DeviceVector(supportedDevice),
6799 true,
6800 0,
6801 NULL);
6802 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006803 }
6804 // open input streams needed to access attached devices to validate
6805 // mAvailableInputDevices list
6806 for (const auto& inProfile : hwModule->getInputProfiles()) {
6807 if (!inProfile->canOpenNewIo()) {
6808 ALOGE("Invalid Input profile max open count %u for profile %s",
6809 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6810 continue;
6811 }
6812 if (!inProfile->hasSupportedDevices()) {
6813 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6814 continue;
6815 }
6816 // chose first device present in profile's SupportedDevices also part of
6817 // available input devices
6818 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006819 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006820 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006821 ALOGV("%s: Input device list is empty! for profile %s",
6822 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006823 continue;
6824 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306825
6826 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6827 && availProfileDevices.areAllDevicesAttached()) {
6828 ALOGV("%s skip opening input for mmap profile %s", __func__,
6829 inProfile->getTagName().c_str());
6830 continue;
6831 }
6832
Eric Laurentc71b11b2024-06-03 12:54:53 +00006833 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6834 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006835
6836 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6837 status_t status = inputDesc->open(nullptr,
6838 availProfileDevices.itemAt(0),
6839 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306840 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006841 &input);
6842 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306843 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6844 __func__, availProfileDevices.toString().c_str(),
6845 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006846 continue;
6847 }
6848 for (const auto &device : availProfileDevices) {
6849 // give a valid ID to an attached device once confirmed it is reachable
6850 if (!device->isAttached()) {
6851 device->attach(hwModule);
6852 device->importAudioPortAndPickAudioProfile(inProfile, true);
6853 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006854 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006855 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6856 }
6857 }
6858 inputDesc->close();
6859 }
6860 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006861
6862 // Check if spatializer outputs can be closed until used.
6863 // mOutputs vector never contains duplicated outputs at this point.
6864 std::vector<audio_io_handle_t> outputsClosed;
6865 for (size_t i = 0; i < mOutputs.size(); i++) {
6866 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6867 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6868 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6869 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006870 nextAudioPortGeneration();
6871 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6872 if (index >= 0) {
6873 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6874 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6875 patchDesc->getAfHandle(), 0);
6876 mAudioPatches.removeItemsAt(index);
6877 mpClientInterface->onAudioPatchListUpdate();
6878 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006879 desc->close();
6880 }
6881 }
6882 for (auto output : outputsClosed) {
6883 removeOutput(output);
6884 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006885}
6886
Eric Laurent98e38192018-02-15 18:31:53 -08006887void AudioPolicyManager::addOutput(audio_io_handle_t output,
6888 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006889{
Eric Laurent1c333e22014-05-20 10:48:17 -07006890 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006891 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006892 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006893 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006894 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006895}
6896
François Gaffie53615e22015-03-19 09:24:12 +01006897void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6898{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006899 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6900 ALOGV("%s: removing primary output", __func__);
6901 mPrimaryOutput = nullptr;
6902 }
François Gaffie53615e22015-03-19 09:24:12 +01006903 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006904 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006905}
6906
Eric Laurent98e38192018-02-15 18:31:53 -08006907void AudioPolicyManager::addInput(audio_io_handle_t input,
6908 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006909{
Eric Laurent1c333e22014-05-20 10:48:17 -07006910 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006911 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006912}
Eric Laurente552edb2014-03-10 17:42:56 -07006913
François Gaffie11d30102018-11-02 16:09:09 +01006914status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006915 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006916 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006917{
François Gaffie11d30102018-11-02 16:09:09 +01006918 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006919 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006920 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006921
François Gaffie11d30102018-11-02 16:09:09 +01006922 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006923 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006924 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006925 }
Eric Laurente552edb2014-03-10 17:42:56 -07006926
Eric Laurent3b73df72014-03-11 09:06:29 -07006927 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006928 // first call getAudioPort to get the supported attributes from the HAL
6929 struct audio_port_v7 port = {};
6930 device->toAudioPort(&port);
6931 status_t status = mpClientInterface->getAudioPort(&port);
6932 if (status == NO_ERROR) {
6933 device->importAudioPort(port);
6934 }
6935
6936 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006937 for (size_t i = 0; i < mOutputs.size(); i++) {
6938 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006939 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006940 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006941 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6942 mOutputs.keyAt(i), device->toString().c_str());
6943 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006944 }
6945 }
6946 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006947 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006948 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006949 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6950 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006951 if (profile->supportsDevice(device)) {
6952 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306953 ALOGV("%s(): adding profile %s from module %s",
6954 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006955 }
6956 }
6957 }
6958
Eric Laurent7b279bb2015-12-14 10:18:23 -08006959 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006960
Eric Laurente552edb2014-03-10 17:42:56 -07006961 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006962 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006963 return BAD_VALUE;
6964 }
6965
6966 // open outputs for matching profiles if needed. Direct outputs are also opened to
6967 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6968 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006969 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006970
6971 // nothing to do if one output is already opened for this profile
6972 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006973 for (j = 0; j < outputs.size(); j++) {
6974 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006975 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006976 // matching profile: save the sample rates, format and channel masks supported
6977 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006978 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006979 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006980 }
Eric Laurente552edb2014-03-10 17:42:56 -07006981 break;
6982 }
6983 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006984 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006985 continue;
6986 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306987 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6988 ALOGV("%s skip opening output for mmap profile %s",
6989 __func__, profile->getTagName().c_str());
6990 continue;
6991 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006992 if (!profile->canOpenNewIo()) {
6993 ALOGW("Max Output number %u already opened for this profile %s",
6994 profile->maxOpenCount, profile->getTagName().c_str());
6995 continue;
6996 }
6997
Eric Laurent83efe1c2017-07-09 16:51:08 -07006998 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006999 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007000 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7001 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007002 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007003 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007004 profiles.removeAt(profile_index);
7005 profile_index--;
7006 } else {
7007 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007008 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007009 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007010 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7011 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007012 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007013 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007014
François Gaffie11d30102018-11-02 16:09:09 +01007015 if (device_distinguishes_on_address(deviceType)) {
7016 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7017 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307018 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7019 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007020 }
Eric Laurente552edb2014-03-10 17:42:56 -07007021 ALOGV("checkOutputsForDevice(): adding output %d", output);
7022 }
7023 }
7024
7025 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007026 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007027 return BAD_VALUE;
7028 }
Eric Laurentd4692962014-05-05 18:13:44 -07007029 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007030 // check if one opened output is not needed any more after disconnecting one device
7031 for (size_t i = 0; i < mOutputs.size(); i++) {
7032 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007033 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007034 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007035 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007036 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007037 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007038 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007039 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7040 mOutputs.keyAt(i));
7041 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007042 }
Eric Laurente552edb2014-03-10 17:42:56 -07007043 }
7044 }
Eric Laurentd4692962014-05-05 18:13:44 -07007045 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007046 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007047 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7048 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007049 if (!profile->supportsDevice(device)) {
7050 continue;
7051 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307052 ALOGV("%s(): clearing direct output profile %s on module %s",
7053 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007054 profile->clearAudioProfiles();
7055 if (!profile->hasDynamicAudioProfile()) {
7056 continue;
7057 }
7058 // When a device is disconnected, if there is an IOProfile that contains dynamic
7059 // profiles and supports the disconnected device, call getAudioPort to repopulate
7060 // the capabilities of the devices that is supported by the IOProfile.
7061 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7062 if (supportedDevice == device ||
7063 !mAvailableOutputDevices.contains(supportedDevice)) {
7064 continue;
7065 }
7066 struct audio_port_v7 port;
7067 supportedDevice->toAudioPort(&port);
7068 status_t status = mpClientInterface->getAudioPort(&port);
7069 if (status == NO_ERROR) {
7070 supportedDevice->importAudioPort(port);
7071 }
Eric Laurente552edb2014-03-10 17:42:56 -07007072 }
7073 }
7074 }
7075 }
7076 return NO_ERROR;
7077}
7078
François Gaffie11d30102018-11-02 16:09:09 +01007079status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007080 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007081{
François Gaffie11d30102018-11-02 16:09:09 +01007082 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007083 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007084 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007085 }
7086
Eric Laurentd4692962014-05-05 18:13:44 -07007087 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007088 sp<AudioInputDescriptor> desc;
7089
jiabinbf5f4262023-04-12 21:48:34 +00007090 // first call getAudioPort to get the supported attributes from the HAL
7091 struct audio_port_v7 port = {};
7092 device->toAudioPort(&port);
7093 status_t status = mpClientInterface->getAudioPort(&port);
7094 if (status == NO_ERROR) {
7095 device->importAudioPort(port);
7096 }
7097
Eric Laurent0dd51852019-04-19 18:18:58 -07007098 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007099 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007100 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007101 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007102 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007103 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007104 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007105
François Gaffie11d30102018-11-02 16:09:09 +01007106 if (profile->supportsDevice(device)) {
7107 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307108 ALOGV("%s : adding profile %s from module %s", __func__,
7109 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007110 }
7111 }
7112 }
7113
Eric Laurent0dd51852019-04-19 18:18:58 -07007114 if (profiles.isEmpty()) {
7115 ALOGW("%s: No input profile available for device %s",
7116 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007117 return BAD_VALUE;
7118 }
7119
7120 // open inputs for matching profiles if needed. Direct inputs are also opened to
7121 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7122 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7123
Eric Laurent1c333e22014-05-20 10:48:17 -07007124 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007125
Eric Laurentd4692962014-05-05 18:13:44 -07007126 // nothing to do if one input is already opened for this profile
7127 size_t input_index;
7128 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7129 desc = mInputs.valueAt(input_index);
7130 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007131 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007132 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007133 }
Eric Laurentd4692962014-05-05 18:13:44 -07007134 break;
7135 }
7136 }
7137 if (input_index != mInputs.size()) {
7138 continue;
7139 }
7140
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307141 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7142 ALOGV("%s skip opening input for mmap profile %s",
7143 __func__, profile->getTagName().c_str());
7144 continue;
7145 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007146 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307147 ALOGW("%s Max Input number %u already opened for this profile %s",
7148 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007149 continue;
7150 }
7151
Eric Laurentc71b11b2024-06-03 12:54:53 +00007152 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007153 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307154 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307155 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7156 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007157
Eric Laurentcf2c0212014-07-25 16:20:43 -07007158 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007159 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007160 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007161 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007162 mpClientInterface->setParameters(input, String8(param));
7163 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007164 }
jiabin12537fc2023-10-12 17:56:08 +00007165 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007166 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307167 ALOGW("%s direct input missing param for profile %s", __func__,
7168 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007169 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007170 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007171 }
7172
Eric Laurent0dd51852019-04-19 18:18:58 -07007173 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007174 addInput(input, desc);
7175 }
7176 } // endif input != 0
7177
Eric Laurentcf2c0212014-07-25 16:20:43 -07007178 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307179 ALOGW("%s could not open input for device %s on profile %s", __func__,
7180 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007181 profiles.removeAt(profile_index);
7182 profile_index--;
7183 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007184 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007185 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007186 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307187 ALOGV("%s: adding input %d for profile %s", __func__,
7188 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007189
7190 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307191 ALOGV("%s: closing input %d for profile %s", __func__,
7192 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007193 closeInput(input);
7194 }
Eric Laurentd4692962014-05-05 18:13:44 -07007195 }
7196 } // end scan profiles
7197
7198 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007199 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007200 return BAD_VALUE;
7201 }
7202 } else {
7203 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007204 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007205 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007206 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007207 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007208 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007209 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007210 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307211 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7212 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007213 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007214 }
7215 }
7216 }
7217 } // end disconnect
7218
7219 return NO_ERROR;
7220}
7221
7222
Eric Laurente0720872014-03-11 09:30:41 -07007223void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007224{
7225 ALOGV("closeOutput(%d)", output);
7226
François Gaffie1c878552018-11-22 16:53:21 +01007227 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7228 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007229 ALOGW("closeOutput() unknown output %d", output);
7230 return;
7231 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007232 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007233 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007234
Eric Laurente552edb2014-03-10 17:42:56 -07007235 // look for duplicated outputs connected to the output being removed.
7236 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007237 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7238 if (dupOutput->isDuplicated() &&
7239 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7240 sp<SwAudioOutputDescriptor> remainingOutput =
7241 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007242 // As all active tracks on duplicated output will be deleted,
7243 // and as they were also referenced on the other output, the reference
7244 // count for their stream type must be adjusted accordingly on
7245 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007246 const bool wasActive = remainingOutput->isActive();
7247 // Note: no-op on the closing output where all clients has already been set inactive
7248 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007249 // stop() will be a no op if the output is still active but is needed in case all
7250 // active streams refcounts where cleared above
7251 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007252 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007253 }
Eric Laurente552edb2014-03-10 17:42:56 -07007254 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7255 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7256
7257 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007258 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007259 }
7260 }
7261
Eric Laurent05b90f82014-08-27 15:32:29 -07007262 nextAudioPortGeneration();
7263
François Gaffie1c878552018-11-22 16:53:21 +01007264 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007265 if (index >= 0) {
7266 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007267 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7268 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007269 mAudioPatches.removeItemsAt(index);
7270 mpClientInterface->onAudioPatchListUpdate();
7271 }
7272
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007273 if (closingOutputWasActive) {
7274 closingOutput->stop();
7275 }
François Gaffie1c878552018-11-22 16:53:21 +01007276 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007277 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007278 for (const auto device : closingOutput->devices()) {
7279 device->setPreferredConfig(nullptr);
7280 }
7281 }
Eric Laurente552edb2014-03-10 17:42:56 -07007282
François Gaffie53615e22015-03-19 09:24:12 +01007283 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007284 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007285 if (closingOutput == mSpatializerOutput) {
7286 mSpatializerOutput.clear();
7287 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007288
7289 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7290 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007291 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007292 bool directOutputOpen = false;
7293 for (size_t i = 0; i < mOutputs.size(); i++) {
7294 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7295 directOutputOpen = true;
7296 break;
7297 }
7298 }
7299 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007300 ALOGV("no direct outputs open, reset MSD patches");
7301 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7302 // how output devices for patching are resolved. Avoid by caching and reusing the
7303 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7304 // devices to patch to. This may be complicated by the fact that devices may become
7305 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007306 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007307 }
7308 }
jiabin220eea12024-05-17 17:55:20 +00007309
7310 if (closingOutput->mPreferredAttrInfo != nullptr) {
7311 closingOutput->mPreferredAttrInfo->resetActiveClient();
7312 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007313}
7314
7315void AudioPolicyManager::closeInput(audio_io_handle_t input)
7316{
7317 ALOGV("closeInput(%d)", input);
7318
7319 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7320 if (inputDesc == NULL) {
7321 ALOGW("closeInput() unknown input %d", input);
7322 return;
7323 }
7324
Eric Laurent6a94d692014-05-20 11:18:06 -07007325 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007326
François Gaffie11d30102018-11-02 16:09:09 +01007327 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007328 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007329 if (index >= 0) {
7330 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007331 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7332 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007333 mAudioPatches.removeItemsAt(index);
7334 mpClientInterface->onAudioPatchListUpdate();
7335 }
7336
François Gaffie6ebbce02023-07-19 13:27:53 +02007337 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007338 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007339 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007340
François Gaffie11d30102018-11-02 16:09:09 +01007341 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7342 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007343 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007344 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007345 }
Eric Laurente552edb2014-03-10 17:42:56 -07007346}
7347
François Gaffie11d30102018-11-02 16:09:09 +01007348SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7349 const DeviceVector &devices,
7350 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007351{
7352 SortedVector<audio_io_handle_t> outputs;
7353
François Gaffie11d30102018-11-02 16:09:09 +01007354 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007355 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007356 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007357 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007358 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007359 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007360 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007361 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007362 outputs.add(openOutputs.keyAt(i));
7363 }
7364 }
7365 return outputs;
7366}
7367
Mikhail Naganov37977152018-07-11 15:54:44 -07007368void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7369{
7370 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7371 // output is suspended before any tracks are moved to it
7372 checkA2dpSuspend();
7373 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007374 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007375 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007376 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007377 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007378 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7379 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7380 // configuration changes will ultimately be rerouted correctly. We can still avoid
7381 // unnecessary rerouting by caching and reusing the arguments to
7382 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7383 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007384 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007385 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007386 // an event that changed routing likely occurred, inform upper layers
7387 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007388}
7389
François Gaffiec005e562018-11-06 15:04:49 +01007390bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7391 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007392{
François Gaffiec005e562018-11-06 15:04:49 +01007393 return mEngine->getProductStrategyForAttributes(lAttr) ==
7394 mEngine->getProductStrategyForAttributes(rAttr);
7395}
7396
Francois Gaffieff1eb522020-05-06 18:37:04 +02007397void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7398{
7399 for (size_t i = 0; i < mAudioSources.size(); i++) {
7400 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7401 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007402 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007403 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007404 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007405 }
7406 }
7407}
7408
7409void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7410{
7411 for (size_t i = 0; i < mAudioSources.size(); i++) {
7412 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7413 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7414 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7415 disconnectAudioSource(sourceDesc);
7416 }
7417 }
7418}
7419
François Gaffiec005e562018-11-06 15:04:49 +01007420void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7421{
7422 auto psId = mEngine->getProductStrategyForAttributes(attr);
7423
7424 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7425 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007426
François Gaffie11d30102018-11-02 16:09:09 +01007427 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7428 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007429
Eric Laurentc209fe42020-06-05 18:11:23 -07007430 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007431 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007432 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007433 // take into account dynamic audio policies related changes: if a client is now associated
7434 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007435 // invalidate clients on outputs that do not support all the newly selected devices for the
7436 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007437 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007438 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007439 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007440 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007441 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007442
Eric Laurentc209fe42020-06-05 18:11:23 -07007443 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7444 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7445 continue;
7446 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007447 if (!desc->supportsAllDevices(newDevices)) {
7448 invalidatedOutputs.push_back(desc);
7449 break;
7450 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007451 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007452 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007453 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7454 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7455 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007456 if (status == OK) {
7457 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7458 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7459 maxLatency = desc->latency();
7460 }
7461 invalidatedOutputs.push_back(desc);
7462 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007463 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007464 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007465 }
7466 }
7467
Eric Laurent56ed8842022-11-15 16:04:41 +01007468 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007469 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7470 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007471 for (audio_io_handle_t srcOut : srcOutputs) {
7472 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007473 if (desc == nullptr) continue;
7474
7475 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007476 maxLatency = desc->latency();
7477 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007478
Eric Laurent56ed8842022-11-15 16:04:41 +01007479 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007480 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007481 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007482 // a client on a non direct outputs has necessarily a linear PCM format
7483 // so we can call selectOutput() safely
7484 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7485 client->flags(),
7486 client->config().format,
7487 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007488 client->config().sample_rate,
7489 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007490 if (newOutput != srcOut) {
7491 invalidate = true;
7492 break;
7493 }
7494 } else {
7495 sp<IOProfile> profile = getProfileForOutput(newDevices,
7496 client->config().sample_rate,
7497 client->config().format,
7498 client->config().channel_mask,
7499 client->flags(),
7500 true /* directOnly */);
7501 if (profile != desc->mProfile) {
7502 invalidate = true;
7503 break;
7504 }
7505 }
7506 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007507 // mute strategy while moving tracks from one output to another
7508 if (invalidate) {
7509 invalidatedOutputs.push_back(desc);
7510 if (desc->isStrategyActive(psId)) {
7511 setStrategyMute(psId, true, desc);
7512 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7513 newDevices.types());
7514 }
Eric Laurente552edb2014-03-10 17:42:56 -07007515 }
François Gaffiec005e562018-11-06 15:04:49 +01007516 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007517 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007518 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007519 }
Eric Laurente552edb2014-03-10 17:42:56 -07007520 }
7521
Eric Laurent56ed8842022-11-15 16:04:41 +01007522 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7523 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7524 std::to_string(srcOutputs[0]).c_str(),
7525 std::to_string(dstOutputs[0]).c_str());
7526
François Gaffiec005e562018-11-06 15:04:49 +01007527 // Move effects associated to this stream from previous output to new output
7528 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007529 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007530 }
François Gaffiec005e562018-11-06 15:04:49 +01007531 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007532 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007533 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007534 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007535 desc->setTracksInvalidatedStatusByStrategy(psId);
7536 }
Eric Laurente552edb2014-03-10 17:42:56 -07007537 }
7538 }
7539}
7540
Eric Laurente0720872014-03-11 09:30:41 -07007541void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007542{
François Gaffiec005e562018-11-06 15:04:49 +01007543 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7544 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7545 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007546 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007547 }
Eric Laurente552edb2014-03-10 17:42:56 -07007548}
7549
Kevin Rocard153f92d2018-12-18 18:33:28 -08007550void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007551 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007552 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007553 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007554 for (size_t i = 0; i < mOutputs.size(); i++) {
7555 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7556 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007557 sp<AudioPolicyMix> primaryMix;
7558 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007559 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007560 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7561 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7562 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007563 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7564 for (auto &secondaryMix : secondaryMixes) {
7565 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7566 if (outputDesc != nullptr &&
7567 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7568 secondaryDescs.push_back(outputDesc);
7569 }
7570 }
7571
jiabinc44b3462022-12-08 12:52:31 -08007572 if (status != OK &&
7573 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7574 // When it failed to query secondary output, only invalidate the client that is not
7575 // MMAP. The reason is that MMAP stream will not support secondary output.
7576 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007577 } else if (!std::equal(
7578 client->getSecondaryOutputs().begin(),
7579 client->getSecondaryOutputs().end(),
7580 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007581 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7582 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007583 // If the format is not PCM, the tracks should be invalidated to get correct
7584 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007585 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007586 } else {
7587 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7588 std::vector<audio_io_handle_t> secondaryOutputIds;
7589 for (const auto &secondaryDesc: secondaryDescs) {
7590 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7591 weakSecondaryDescs.push_back(secondaryDesc);
7592 }
7593 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7594 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007595 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007596 }
7597 }
7598 }
jiabin10a03f12021-05-07 23:46:28 +00007599 if (!trackSecondaryOutputs.empty()) {
7600 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7601 }
jiabinc44b3462022-12-08 12:52:31 -08007602 if (!clientsToInvalidate.empty()) {
7603 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7604 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007605 }
7606}
7607
Eric Laurent2517af32020-11-25 15:31:27 +01007608bool AudioPolicyManager::isScoRequestedForComm() const {
7609 AudioDeviceTypeAddrVector devices;
7610 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7611 for (const auto &device : devices) {
7612 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7613 return true;
7614 }
7615 }
7616 return false;
7617}
7618
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007619bool AudioPolicyManager::isHearingAidUsedForComm() const {
7620 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7621 true /*fromCache*/);
7622 for (const auto &device : devices) {
7623 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7624 return true;
7625 }
7626 }
7627 return false;
7628}
7629
7630
Eric Laurente0720872014-03-11 09:30:41 -07007631void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007632{
François Gaffie53615e22015-03-19 09:24:12 +01007633 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007634 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007635 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007636 return;
7637 }
7638
Eric Laurent3a4311c2014-03-17 12:00:47 -07007639 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007640 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7641 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007642 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007643
7644 // if suspended, restore A2DP output if:
7645 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007646 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007647 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007648 //
Eric Laurentf732e072016-08-03 19:30:28 -07007649 // if not suspended, suspend A2DP output if:
7650 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007651 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007652 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007653 //
7654 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007655 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007656 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007657 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007658 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007659
7660 mpClientInterface->restoreOutput(a2dpOutput);
7661 mA2dpSuspended = false;
7662 }
7663 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007664 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007665 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007666 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007667 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007668
7669 mpClientInterface->suspendOutput(a2dpOutput);
7670 mA2dpSuspended = true;
7671 }
7672 }
7673}
7674
François Gaffie11d30102018-11-02 16:09:09 +01007675DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7676 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007677{
François Gaffiedb1755b2023-09-01 11:50:35 +02007678 if (outputDesc == nullptr) {
7679 return DeviceVector{};
7680 }
François Gaffie11d30102018-11-02 16:09:09 +01007681
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007682 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007683 if (index >= 0) {
7684 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007685 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007686 ALOGV("%s device %s forced by patch %d", __func__,
7687 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7688 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007689 }
7690 }
7691
Dean Wheatley514b4312020-06-17 21:45:00 +10007692 // Do not retrieve engine device for outputs through MSD
7693 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7694 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7695 return outputDesc->devices();
7696 }
7697
Eric Laurent97ac8712018-07-27 18:59:02 -07007698 // Honor explicit routing requests only if no client using default routing is active on this
7699 // input: a specific app can not force routing for other apps by setting a preferred device.
7700 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007701 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007702 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007703 if (device != nullptr) {
7704 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007705 }
7706
François Gaffiea807ef92018-11-05 10:44:33 +01007707 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7708 // of setForceUse / Default Bus device here
7709 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7710 if (device != nullptr) {
7711 return DeviceVector(device);
7712 }
7713
François Gaffiedb1755b2023-09-01 11:50:35 +02007714 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007715 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7716 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307717 auto hasStreamActive = [&](auto stream) {
7718 return hasStream(streams, stream) && isStreamActive(stream, 0);
7719 };
Eric Laurent484e9272018-06-07 17:29:23 -07007720
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307721 auto doGetOutputDevicesForVoice = [&]() {
7722 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007723 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307724 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007725 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7726 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307727 };
7728
7729 // With low-latency playing on speaker, music on WFD, when the first low-latency
7730 // output is stopped, getNewOutputDevices checks for a product strategy
7731 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007732 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307733 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7734 // stream is associated to the output descriptor.
7735 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7736 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7737 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7738 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007739 // Retrieval of devices for voice DL is done on primary output profile, cannot
7740 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007741 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007742 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7743 break;
7744 }
Eric Laurente552edb2014-03-10 17:42:56 -07007745 }
François Gaffiec005e562018-11-06 15:04:49 +01007746 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007747 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007748}
7749
François Gaffie11d30102018-11-02 16:09:09 +01007750sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7751 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007752{
François Gaffie11d30102018-11-02 16:09:09 +01007753 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007754
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007755 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007756 if (index >= 0) {
7757 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007758 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007759 ALOGV("getNewInputDevice() device %s forced by patch %d",
7760 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7761 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007762 }
7763 }
7764
Eric Laurent97ac8712018-07-27 18:59:02 -07007765 // Honor explicit routing requests only if no client using default routing is active on this
7766 // input: a specific app can not force routing for other apps by setting a preferred device.
7767 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007768 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7769 if (device != nullptr) {
7770 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007771 }
7772
Eric Laurentdc95a252018-04-12 12:46:56 -07007773 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007774 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007775 audio_attributes_t attributes;
7776 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007777 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007778 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7779 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007780 attributes = topClient->attributes();
7781 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007782 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007783 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007784 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7785 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007786 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007787 }
7788
Francois Gaffie716e1432019-01-14 16:58:59 +01007789 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7790 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007791 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007792 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007793 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007794 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007795
Eric Laurente552edb2014-03-10 17:42:56 -07007796 return device;
7797}
7798
Eric Laurent794fde22016-03-11 09:50:45 -08007799bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7800 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007801 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007802}
7803
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007804status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007805 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007806 if (devices == nullptr) {
7807 return BAD_VALUE;
7808 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007809
Andy Hung6d23c0f2022-02-16 09:37:15 -08007810 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007811 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7812 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007813 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007814 for (const auto& device : curDevices) {
7815 devices->push_back(device->getDeviceTypeAddr());
7816 }
7817 return NO_ERROR;
7818}
7819
Eric Laurente0720872014-03-11 09:30:41 -07007820void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007821 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007822 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007823 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007824 updateDevicesAndOutputs();
7825 break;
7826 default:
7827 break;
7828 }
7829}
7830
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007831uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007832
7833 // skip beacon mute management if a dedicated TTS output is available
7834 if (mTtsOutputAvailable) {
7835 return 0;
7836 }
7837
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007838 switch(event) {
7839 case STARTING_OUTPUT:
7840 mBeaconMuteRefCount++;
7841 break;
7842 case STOPPING_OUTPUT:
7843 if (mBeaconMuteRefCount > 0) {
7844 mBeaconMuteRefCount--;
7845 }
7846 break;
7847 case STARTING_BEACON:
7848 mBeaconPlayingRefCount++;
7849 break;
7850 case STOPPING_BEACON:
7851 if (mBeaconPlayingRefCount > 0) {
7852 mBeaconPlayingRefCount--;
7853 }
7854 break;
7855 }
7856
7857 if (mBeaconMuteRefCount > 0) {
7858 // any playback causes beacon to be muted
7859 return setBeaconMute(true);
7860 } else {
7861 // no other playback: unmute when beacon starts playing, mute when it stops
7862 return setBeaconMute(mBeaconPlayingRefCount == 0);
7863 }
7864}
7865
7866uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7867 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7868 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7869 // keep track of muted state to avoid repeating mute/unmute operations
7870 if (mBeaconMuted != mute) {
7871 // mute/unmute AUDIO_STREAM_TTS on all outputs
7872 ALOGV("\t muting %d", mute);
7873 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007874 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7875 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7876 ALOGV("\t no tts volume source available");
7877 return 0;
7878 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007879 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007880 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007881 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007882 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007883 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007884 maxLatency = latency;
7885 }
7886 }
7887 mBeaconMuted = mute;
7888 return maxLatency;
7889 }
7890 return 0;
7891}
7892
Eric Laurente0720872014-03-11 09:30:41 -07007893void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007894{
François Gaffiec005e562018-11-06 15:04:49 +01007895 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007896 mPreviousOutputs = mOutputs;
7897}
7898
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007899uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007900 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007901 uint32_t delayMs)
7902{
7903 // mute/unmute strategies using an incompatible device combination
7904 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7905 // if unmuting, unmute only after the specified delay
7906 if (outputDesc->isDuplicated()) {
7907 return 0;
7908 }
7909
7910 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007911 DeviceVector devices = outputDesc->devices();
7912 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007913
François Gaffiec005e562018-11-06 15:04:49 +01007914 auto productStrategies = mEngine->getOrderedProductStrategies();
7915 for (const auto &productStrategy : productStrategies) {
7916 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7917 DeviceVector curDevices =
7918 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7919 curDevices = curDevices.filter(outputDesc->supportedDevices());
7920 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007921 bool doMute = false;
7922
François Gaffiec005e562018-11-06 15:04:49 +01007923 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007924 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007925 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7926 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007927 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007928 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007929 }
Eric Laurent99401132014-05-07 19:48:15 -07007930 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007931 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007932 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007933 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007934 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007935 continue;
7936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307937 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007938 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7939 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7940 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007941 if (mute) {
7942 // FIXME: should not need to double latency if volume could be applied
7943 // immediately by the audioflinger mixer. We must account for the delay
7944 // between now and the next time the audioflinger thread for this output
7945 // will process a buffer (which corresponds to one buffer size,
7946 // usually 1/2 or 1/4 of the latency).
7947 if (muteWaitMs < desc->latency() * 2) {
7948 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007949 }
7950 }
7951 }
7952 }
7953 }
7954 }
7955
Eric Laurent99401132014-05-07 19:48:15 -07007956 // temporary mute output if device selection changes to avoid volume bursts due to
7957 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007958 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007959 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007960
Eric Laurentdc462862016-07-19 12:29:53 -07007961 if (muteWaitMs < tempMuteWaitMs) {
7962 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007963 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007964
7965 // If recommended duration is defined, replace temporary mute duration to avoid
7966 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7967 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7968 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7969 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7970 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7971
François Gaffieaaac0fd2018-11-22 17:56:39 +01007972 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7973 // make sure that we do not start the temporary mute period too early in case of
7974 // delayed device change
7975 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7976 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007977 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007978 }
7979 }
7980
Eric Laurente552edb2014-03-10 17:42:56 -07007981 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7982 if (muteWaitMs > delayMs) {
7983 muteWaitMs -= delayMs;
7984 usleep(muteWaitMs * 1000);
7985 return muteWaitMs;
7986 }
7987 return 0;
7988}
7989
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307990uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7991 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007992 const DeviceVector &devices,
7993 bool force,
7994 int delayMs,
7995 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007996 bool requiresMuteCheck, bool requiresVolumeCheck,
7997 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007998{
jiabin3ff8d7d2022-12-13 06:27:44 +00007999 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308000 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8001 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8002 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008003 uint32_t muteWaitMs;
8004
8005 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308006 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008007 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308008 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008009 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008010 return muteWaitMs;
8011 }
Eric Laurente552edb2014-03-10 17:42:56 -07008012
8013 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008014 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008015 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008016 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008017
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308018 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8019 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008020
8021 if (!filteredDevices.isEmpty()) {
8022 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008023 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008024
8025 // if the outputs are not materially active, there is no need to mute.
8026 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008027 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008028 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308029 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8030 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008031 muteWaitMs = 0;
8032 }
Eric Laurente552edb2014-03-10 17:42:56 -07008033
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008034 bool outputRouted = outputDesc->isRouted();
8035
Eric Laurent79ea9582020-06-11 18:49:24 -07008036 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8037 // output profile or if new device is not supported AND previous device(s) is(are) still
8038 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008039 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308040 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8041 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008042 // restore previous device after evaluating strategy mute state
8043 outputDesc->setDevices(prevDevices);
8044 return muteWaitMs;
8045 }
8046
Eric Laurente552edb2014-03-10 17:42:56 -07008047 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008048 // the requested device is AUDIO_DEVICE_NONE
8049 // OR the requested device is the same as current device
8050 // AND force is not specified
8051 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008052 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008053 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308054 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8055 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8056 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008057 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308058 ALOGV("%s %s setting same device on routed output, force apply volumes",
8059 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008060 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8061 }
Eric Laurente552edb2014-03-10 17:42:56 -07008062 return muteWaitMs;
8063 }
8064
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308065 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8066 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008067
Eric Laurente552edb2014-03-10 17:42:56 -07008068 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008069 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008070 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008071 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008072 PatchBuilder patchBuilder;
8073 patchBuilder.addSource(outputDesc);
8074 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8075 for (const auto &filteredDevice : filteredDevices) {
8076 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008077 }
8078
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008079 // Add half reported latency to delayMs when muteWaitMs is null in order
8080 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008081 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8082 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8083 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008084 }
Eric Laurente552edb2014-03-10 17:42:56 -07008085
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008086 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8087 if (!skipMuteDelay) {
8088 // update stream volumes according to new device
8089 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8090 }
Eric Laurente552edb2014-03-10 17:42:56 -07008091
8092 return muteWaitMs;
8093}
8094
Eric Laurentc75307b2015-03-17 15:29:32 -07008095status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008096 int delayMs,
8097 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008098{
Eric Laurent6a94d692014-05-20 11:18:06 -07008099 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008100 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8101 return INVALID_OPERATION;
8102 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008103 if (patchHandle) {
8104 index = mAudioPatches.indexOfKey(*patchHandle);
8105 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008106 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008107 }
8108 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008109 return INVALID_OPERATION;
8110 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008111 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008112 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008113 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008114 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008115 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008116 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008117 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008118 return status;
8119}
8120
8121status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008122 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008123 bool force,
8124 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008125{
8126 status_t status = NO_ERROR;
8127
Eric Laurent1f2f2232014-06-02 12:01:23 -07008128 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008129 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8130 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008131
François Gaffie11d30102018-11-02 16:09:09 +01008132 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008133 PatchBuilder patchBuilder;
8134 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008135 // AUDIO_SOURCE_HOTWORD is for internal use only:
8136 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008137 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8138 auto result = usecase;
8139 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8140 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8141 }
8142 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008143 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008144 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008145 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008146 }
8147 }
8148 return status;
8149}
8150
Eric Laurent6a94d692014-05-20 11:18:06 -07008151status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8152 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008153{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008154 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008155 ssize_t index;
8156 if (patchHandle) {
8157 index = mAudioPatches.indexOfKey(*patchHandle);
8158 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008159 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008160 }
8161 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008162 return INVALID_OPERATION;
8163 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008164 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008165 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008166 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008167 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008168 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008169 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008170 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008171 return status;
8172}
8173
François Gaffie11d30102018-11-02 16:09:09 +01008174sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008175 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008176 audio_format_t& format,
8177 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008178 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008179{
8180 // Choose an input profile based on the requested capture parameters: select the first available
8181 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008182 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008183
Atneya Nair0f0a8032022-12-12 16:20:12 -08008184 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8185 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8186 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8187
8188 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008189
jiabin2fd710d2022-05-02 23:20:22 +00008190 for (;;) {
8191 sp<IOProfile> firstInexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008192 uint32_t inexactSamplingRate = 0;
8193 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8194 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008195 uint32_t updatedSamplingRate = 0;
8196 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8197 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8198 for (const auto& hwModule : mHwModules) {
8199 for (const auto& profile : hwModule->getInputProfiles()) {
8200 // profile->log();
8201 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008202 if (profile->getCompatibilityScore(
8203 DeviceVector(device),
8204 samplingRate,
8205 &updatedSamplingRate,
8206 format,
8207 &updatedFormat,
8208 channelMask,
8209 &updatedChannelMask,
8210 // FIXME ugly cast
8211 (audio_output_flags_t) flags,
8212 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8213 samplingRate = updatedSamplingRate;
8214 format = updatedFormat;
8215 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008216 return profile;
8217 }
jiabin66acc432024-02-06 00:57:36 +00008218 if (firstInexact == nullptr
8219 && profile->getCompatibilityScore(
8220 DeviceVector(device),
8221 samplingRate,
8222 &updatedSamplingRate,
8223 format,
8224 &updatedFormat,
8225 channelMask,
8226 &updatedChannelMask,
8227 // FIXME ugly cast
8228 (audio_output_flags_t) flags,
8229 false /*exactMatchRequiredForInputFlags*/)
8230 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008231 firstInexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008232 inexactSamplingRate = updatedSamplingRate;
8233 inexactFormat = updatedFormat;
8234 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008235 }
8236 }
8237 }
8238
8239 if (firstInexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008240 samplingRate = inexactSamplingRate;
8241 format = inexactFormat;
8242 channelMask = inexactChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008243 return firstInexact;
8244 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8245 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8246 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8247 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8248 flags = AUDIO_INPUT_FLAG_NONE;
8249 } else { // fail
8250 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8251 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8252 samplingRate, format, channelMask, oriFlags);
8253 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008254 }
8255 }
jiabin2fd710d2022-05-02 23:20:22 +00008256
8257 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008258}
8259
Vlad Popa87e0e582024-05-20 18:49:20 -07008260float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8261 VolumeSource volumeSource,
8262 int index,
8263 const DeviceTypeSet &deviceTypes)
8264{
8265 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8266 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8267 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8268
8269 if (com_android_media_audio_abs_volume_index_fix()) {
8270 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8271 mAbsoluteVolumeDrivingStreams.end()) {
8272 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8273 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8274 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8275 ALOGD("%s: no group matching with %s", __FUNCTION__,
8276 toString(attributesToDriveAbs).c_str());
8277 return volumeDb;
8278 }
8279
8280 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8281 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8282 if (vsToDriveAbs == volumeSource) {
8283 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008284 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008285 } else {
8286 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8287 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8288 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8289 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8290 curvesAbs.getVolumeIndexMax());
8291 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8292 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8293 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8294 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8295 return newVolumeDb;
8296 }
8297 }
8298 return volumeDb;
8299 } else {
8300 return volumeDb;
8301 }
8302}
8303
François Gaffieaaac0fd2018-11-22 17:56:39 +01008304float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8305 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008306 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008307 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008308 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008309 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008310{
Vlad Popa9d482762024-06-21 16:40:23 -07008311 float volumeDb;
8312 if (adjustAttenuation) {
8313 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8314 } else {
8315 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8316 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008317 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8318 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8319
8320 if (!computeInternalInteraction) {
8321 return volumeDb;
8322 }
8323
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008324 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8325 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8326 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8327 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008328 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8329 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8330 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8331 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8332 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008333 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008334 mOutputs.isActive(ringVolumeSrc, 0)) {
8335 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008336 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008337 adjustAttenuation,
8338 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008339 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008340 }
8341
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008342 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008343 if ((volumeSource != callVolumeSrc && (isInCall() ||
8344 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008345 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008346 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8347 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008348 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8349 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8350 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008351 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008352 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008353 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008354 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008355 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008356 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008357 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008358 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8359 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8360 // programmatically muted.
8361 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8362 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8363 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008364 bool exemptFromCapping =
8365 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8366 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008367 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8368 volumeSource, volumeDb);
8369 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008370 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8371 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8372 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008373 }
8374 }
Eric Laurente552edb2014-03-10 17:42:56 -07008375 // if a headset is connected, apply the following rules to ring tones and notifications
8376 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008377 // - always attenuate notifications volume by 6dB
8378 // - attenuate ring tones volume by 6dB unless music is not playing and
8379 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008380 // - if music is playing, always limit the volume to current music volume,
8381 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008382 if (!Intersection(deviceTypes,
8383 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8384 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008385 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8386 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008387 ((volumeSource == alarmVolumeSrc ||
8388 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008389 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8390 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8391 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008392 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8393 curves.canBeMuted()) {
8394
Eric Laurente552edb2014-03-10 17:42:56 -07008395 // when the phone is ringing we must consider that music could have been paused just before
8396 // by the music application and behave as if music was active if the last music track was
8397 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008398 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8399 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008400 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008401 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008402 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8403 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008404 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008405 float musicVolDb = computeVolume(musicCurves,
8406 musicVolumeSrc,
8407 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008408 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008409 adjustAttenuation,
8410 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008411 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8412 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8413 if (volumeDb > minVolDb) {
8414 volumeDb = minVolDb;
8415 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008416 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008417 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8418 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008419 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8420 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8421 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8422 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008423 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008424 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008425 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8426 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008427 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8428 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008429 }
8430 }
jiabin9a3361e2019-10-01 09:38:30 -07008431 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008432 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008433 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008434 }
8435 }
8436
François Gaffie43c73442018-11-08 08:21:55 +01008437 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008438}
8439
Eric Laurent3839bc02018-07-10 18:33:34 -07008440int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008441 VolumeSource fromVolumeSource,
8442 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008443{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008444 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008445 return srcIndex;
8446 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008447 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8448 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008449 float minSrc = (float)srcCurves.getVolumeIndexMin();
8450 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8451 float minDst = (float)dstCurves.getVolumeIndexMin();
8452 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008453
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008454 // preserve mute request or correct range
8455 if (srcIndex < minSrc) {
8456 if (srcIndex == 0) {
8457 return 0;
8458 }
8459 srcIndex = minSrc;
8460 } else if (srcIndex > maxSrc) {
8461 srcIndex = maxSrc;
8462 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008463 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8464}
8465
François Gaffieaaac0fd2018-11-22 17:56:39 +01008466status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8467 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008468 int index,
8469 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008470 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008471 int delayMs,
8472 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008473{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008474 // APM is single threaded, and single instance.
8475 static std::set<IVolumeCurves*> invalidCurvesReported;
8476
François Gaffieaaac0fd2018-11-22 17:56:39 +01008477 // do not change actual attributes volume if the attributes is muted
8478 if (outputDesc->isMuted(volumeSource)) {
8479 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8480 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008481 return NO_ERROR;
8482 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008483
Eric Laurentae6e88c2024-01-10 14:42:57 +01008484 bool isVoiceVolSrc;
8485 bool isBtScoVolSrc;
8486 if (!isVolumeConsistentForCalls(
8487 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008488 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008489 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008490 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008491 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008492
jiabin9a3361e2019-10-01 09:38:30 -07008493 if (deviceTypes.empty()) {
8494 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008495 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008496 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008497 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008498 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008499
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008500 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008501 if (!invalidCurvesReported.count(&curves)) {
8502 invalidCurvesReported.insert(&curves);
8503 String8 dump;
8504 curves.dump(&dump);
8505 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8506 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008507 return BAD_VALUE;
8508 }
8509
jiabin9a3361e2019-10-01 09:38:30 -07008510 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8511 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008512 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008513 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008514 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8515 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008516 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008517 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008518 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008519 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8520 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008521
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008522 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008523 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8524 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8525 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008526 }
Eric Laurente552edb2014-03-10 17:42:56 -07008527 return NO_ERROR;
8528}
8529
Eric Laurentae6e88c2024-01-10 14:42:57 +01008530void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008531 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008532 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008533 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008534 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008535 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008536 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8537 } else {
8538 voiceVolume = index == 0 ? 0.0 : 1.0;
8539 }
8540 if (voiceVolume != mLastVoiceVolume) {
8541 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8542 mLastVoiceVolume = voiceVolume;
8543 }
8544}
8545
8546bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8547 const DeviceTypeSet& deviceTypes,
8548 bool& isVoiceVolSrc,
8549 bool& isBtScoVolSrc,
8550 const char* caller) {
8551 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008552 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8553
Eric Laurentae6e88c2024-01-10 14:42:57 +01008554 const bool isScoRequested = isScoRequestedForComm();
8555 const bool isHAUsed = isHearingAidUsedForComm();
8556
Vlad Popa695b76b2024-06-14 16:49:25 -07008557 if (com_android_media_audio_replace_stream_bt_sco()) {
8558 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8559 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8560 (isScoRequested || isHAUsed);
8561 return true;
8562 }
8563
8564 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008565 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8566
8567 if ((callVolSrc != btScoVolSrc) &&
8568 ((isVoiceVolSrc && isScoRequested) ||
8569 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8570 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8571 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8572 volumeSource, isScoRequested ? " " : " not ");
8573 return false;
8574 }
8575 return true;
8576}
8577
Eric Laurentc75307b2015-03-17 15:29:32 -07008578void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008579 const DeviceTypeSet& deviceTypes,
8580 int delayMs,
8581 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008582{
jiabincd510522020-01-22 09:40:55 -08008583 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008584 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8585 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8586 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008587 curves.getVolumeIndex(deviceTypes),
8588 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008589 }
8590}
8591
François Gaffiec005e562018-11-06 15:04:49 +01008592void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8593 bool on,
8594 const sp<AudioOutputDescriptor>& outputDesc,
8595 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008596 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008597{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008598 std::vector<VolumeSource> sourcesToMute;
8599 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8600 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8601 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008602 VolumeSource source = toVolumeSource(attributes, false);
8603 if ((source != VOLUME_SOURCE_NONE) &&
8604 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8605 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008606 sourcesToMute.push_back(source);
8607 }
Eric Laurente552edb2014-03-10 17:42:56 -07008608 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008609 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008610 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008611 }
8612
Eric Laurente552edb2014-03-10 17:42:56 -07008613}
8614
François Gaffieaaac0fd2018-11-22 17:56:39 +01008615void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8616 bool on,
8617 const sp<AudioOutputDescriptor>& outputDesc,
8618 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008619 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008620{
jiabin9a3361e2019-10-01 09:38:30 -07008621 if (deviceTypes.empty()) {
8622 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008623 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008624 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008625 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008626 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008627 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008628 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008629 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8630 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008631 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008632 }
8633 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008634 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8635 // ignored
8636 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008637 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008638 if (!outputDesc->isMuted(volumeSource)) {
8639 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008640 return;
8641 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008642 if (outputDesc->decMuteCount(volumeSource) == 0) {
8643 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008644 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008645 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008646 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008647 delayMs);
8648 }
8649 }
8650}
8651
François Gaffie53615e22015-03-19 09:24:12 +01008652bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8653{
François Gaffiec005e562018-11-06 15:04:49 +01008654 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008655 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8656 return true;
8657 }
8658
8659 // has known usage?
8660 switch (paa->usage) {
8661 case AUDIO_USAGE_UNKNOWN:
8662 case AUDIO_USAGE_MEDIA:
8663 case AUDIO_USAGE_VOICE_COMMUNICATION:
8664 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8665 case AUDIO_USAGE_ALARM:
8666 case AUDIO_USAGE_NOTIFICATION:
8667 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8668 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8669 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8670 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8671 case AUDIO_USAGE_NOTIFICATION_EVENT:
8672 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8673 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8674 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8675 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008676 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008677 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008678 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008679 case AUDIO_USAGE_EMERGENCY:
8680 case AUDIO_USAGE_SAFETY:
8681 case AUDIO_USAGE_VEHICLE_STATUS:
8682 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008683 break;
8684 default:
8685 return false;
8686 }
8687 return true;
8688}
8689
François Gaffie2110e042015-03-24 08:41:51 +01008690audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8691{
8692 return mEngine->getForceUse(usage);
8693}
8694
Eric Laurent96d1dda2022-03-14 17:14:19 +01008695bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008696 return isStateInCall(mEngine->getPhoneState());
8697}
8698
Eric Laurent96d1dda2022-03-14 17:14:19 +01008699bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008700 return is_state_in_call(state);
8701}
8702
Eric Laurentf9cccec2022-11-16 19:12:00 +01008703bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008704 audio_mode_t mode = mEngine->getPhoneState();
8705 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008706 || (mode == AUDIO_MODE_CALL_SCREEN)
8707 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008708}
8709
Eric Laurentf9cccec2022-11-16 19:12:00 +01008710bool AudioPolicyManager::isInCallOrScreening() const {
8711 audio_mode_t mode = mEngine->getPhoneState();
8712 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8713}
8714
Eric Laurentd60560a2015-04-10 11:31:20 -07008715void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8716{
8717 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008718 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008719 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008720 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008721 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008722 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008723 }
8724 }
8725
8726 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8727 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8728 bool release = false;
8729 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8730 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8731 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8732 source->ext.device.type == deviceDesc->type()) {
8733 release = true;
8734 }
8735 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008736 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008737 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8738 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8739 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008740 sink->ext.device.type == deviceDesc->type() &&
8741 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8742 || strncmp(sink->ext.device.address, address,
8743 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008744 release = true;
8745 }
8746 }
8747 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008748 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8749 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008750 }
8751 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008752
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008753 mInputs.clearSessionRoutesForDevice(deviceDesc);
8754
Francois Gaffie716e1432019-01-14 16:58:59 +01008755 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008756}
8757
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008758void AudioPolicyManager::modifySurroundFormats(
8759 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008760 std::unordered_set<audio_format_t> enforcedSurround(
8761 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008762 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008763 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008764 allSurround.insert(pair.first);
8765 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8766 }
Phil Burk09bc4612016-02-24 15:58:15 -08008767
8768 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8769 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008770 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008771 // This is the resulting set of formats depending on the surround mode:
8772 // 'all surround' = allSurround
8773 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8774 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8775 // 'manual surround' = mManualSurroundFormats
8776 // AUTO: formats v 'enforced surround'
8777 // ALWAYS: formats v 'all surround' v 'enforced surround'
8778 // NEVER: formats ^ 'non-surround'
8779 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008780
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008781 std::unordered_set<audio_format_t> formatSet;
8782 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8783 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008784 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008785 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008786 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008787 formatSet.insert(*formatIter);
8788 }
8789 }
8790 } else {
8791 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8792 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008793 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008794
jiabin81772902018-04-02 17:52:27 -07008795 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008796 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008797 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8798 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8799 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008800 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008801 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8802 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8803 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008804 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008805 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008806 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008807 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008808 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008809 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008810}
8811
jiabin06e4bab2019-07-29 10:13:34 -07008812void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8813 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008814 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8815 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8816
8817 // If NEVER, then remove support for channelMasks > stereo.
8818 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008819 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8820 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008821 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008822 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008823 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008824 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008825 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008826 }
8827 }
jiabin81772902018-04-02 17:52:27 -07008828 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8829 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8830 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008831 bool supports5dot1 = false;
8832 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008833 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008834 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8835 supports5dot1 = true;
8836 break;
8837 }
8838 }
8839 // If not then add 5.1 support.
8840 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008841 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008842 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008843 }
Phil Burk09bc4612016-02-24 15:58:15 -08008844 }
8845}
8846
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008847void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008848 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008849 const sp<IOProfile>& profile) {
8850 if (!profile->hasDynamicAudioProfile()) {
8851 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008852 }
François Gaffie112b0af2015-11-19 16:13:25 +01008853
jiabin12537fc2023-10-12 17:56:08 +00008854 audio_port_v7 devicePort;
8855 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008856
jiabin12537fc2023-10-12 17:56:08 +00008857 audio_port_v7 mixPort;
8858 profile->toAudioPort(&mixPort);
8859 mixPort.ext.mix.handle = ioHandle;
8860
8861 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8862 if (status != NO_ERROR) {
8863 ALOGE("%s failed to query the attributes of the mix port", __func__);
8864 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008865 }
jiabin12537fc2023-10-12 17:56:08 +00008866
8867 std::set<audio_format_t> supportedFormats;
8868 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8869 supportedFormats.insert(mixPort.audio_profiles[i].format);
8870 }
8871 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8872 mReportedFormatsMap[devDesc] = formats;
8873
8874 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8875 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8876 modifySurroundFormats(devDesc, &formats);
8877 size_t modifiedNumProfiles = 0;
8878 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8879 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8880 formats.end()) {
8881 // Skip the format that is not present after modifying surround formats.
8882 continue;
8883 }
8884 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8885 sizeof(struct audio_profile));
8886 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8887 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8888 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8889 modifySurroundChannelMasks(&channels);
8890 std::copy(channels.begin(), channels.end(),
8891 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8892 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8893 }
8894 mixPort.num_audio_profiles = modifiedNumProfiles;
8895 }
8896 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008897}
Eric Laurentd60560a2015-04-10 11:31:20 -07008898
Mikhail Naganovdc769682018-05-04 15:34:08 -07008899status_t AudioPolicyManager::installPatch(const char *caller,
8900 audio_patch_handle_t *patchHandle,
8901 AudioIODescriptorInterface *ioDescriptor,
8902 const struct audio_patch *patch,
8903 int delayMs)
8904{
8905 ssize_t index = mAudioPatches.indexOfKey(
8906 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8907 *patchHandle : ioDescriptor->getPatchHandle());
8908 sp<AudioPatch> patchDesc;
8909 status_t status = installPatch(
8910 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8911 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008912 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008913 }
8914 return status;
8915}
8916
8917status_t AudioPolicyManager::installPatch(const char *caller,
8918 ssize_t index,
8919 audio_patch_handle_t *patchHandle,
8920 const struct audio_patch *patch,
8921 int delayMs,
8922 uid_t uid,
8923 sp<AudioPatch> *patchDescPtr)
8924{
8925 sp<AudioPatch> patchDesc;
8926 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8927 if (index >= 0) {
8928 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008929 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008930 }
8931
8932 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8933 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8934 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8935 if (status == NO_ERROR) {
8936 if (index < 0) {
8937 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008938 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008939 } else {
8940 patchDesc->mPatch = *patch;
8941 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008942 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008943 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008944 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008945 }
8946 nextAudioPortGeneration();
8947 mpClientInterface->onAudioPatchListUpdate();
8948 }
8949 if (patchDescPtr) *patchDescPtr = patchDesc;
8950 return status;
8951}
8952
jiabinbce0c1d2020-10-05 11:20:18 -07008953bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8954{
8955 const TrackClientVector activeClients = output->getActiveClients();
8956 if (activeClients.empty()) {
8957 return true;
8958 }
8959 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8960 if (index < 0) {
8961 ALOGE("%s, no audio patch found while there are active clients on output %d",
8962 __func__, output->getId());
8963 return false;
8964 }
8965 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8966 DeviceVector routedDevices;
8967 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8968 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8969 patchDesc->mPatch.sinks[i].id);
8970 if (device == nullptr) {
8971 ALOGE("%s, no audio device found with id(%d)",
8972 __func__, patchDesc->mPatch.sinks[i].id);
8973 return false;
8974 }
8975 routedDevices.add(device);
8976 }
8977 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008978 if (client->isInvalid()) {
8979 // No need to take care about invalidated clients.
8980 continue;
8981 }
jiabinbce0c1d2020-10-05 11:20:18 -07008982 sp<DeviceDescriptor> preferredDevice =
8983 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8984 if (mEngine->getOutputDevicesForAttributes(
8985 client->attributes(), preferredDevice, false) == routedDevices) {
8986 return false;
8987 }
8988 }
8989 return true;
8990}
8991
8992sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008993 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008994 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8995 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008996{
8997 for (const auto& device : devices) {
8998 // TODO: This should be checking if the profile supports the device combo.
8999 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009000 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9001 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009002 return nullptr;
9003 }
9004 }
9005 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9006 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009007 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009008 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009009 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009010 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009011 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009012 return nullptr;
9013 }
jiabin14b50cc2023-12-13 19:01:52 +00009014 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9015 auto portConfig = desc->getConfig();
9016 for (const auto& device : devices) {
9017 device->setPreferredConfig(&portConfig);
9018 }
9019 }
jiabinbce0c1d2020-10-05 11:20:18 -07009020
9021 // Here is where the out_set_parameters() for card & device gets called
9022 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9023 const audio_devices_t deviceType = device->type();
9024 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009025 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009026 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9027 mpClientInterface->setParameters(output, String8(param));
9028 free(param);
9029 }
jiabin12537fc2023-10-12 17:56:08 +00009030 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009031 if (!profile->hasValidAudioProfile()) {
9032 ALOGW("%s() missing param", __func__);
9033 desc->close();
9034 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009035 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9036 // Reopen the output with the best audio profile picked by APM when the profile supports
9037 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009038 desc->close();
9039 output = AUDIO_IO_HANDLE_NONE;
9040 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9041 profile->pickAudioProfile(
9042 config.sample_rate, config.channel_mask, config.format);
9043 config.offload_info.sample_rate = config.sample_rate;
9044 config.offload_info.channel_mask = config.channel_mask;
9045 config.offload_info.format = config.format;
9046
Haofan Wangf6e304f2024-07-09 23:06:58 -07009047 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
9048 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009049 if (status != NO_ERROR) {
9050 return nullptr;
9051 }
9052 }
9053
9054 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00009055 setOutputDevices(__func__, desc,
9056 devices,
9057 true,
9058 0,
9059 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00009060 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9061 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9062
jiabinbce0c1d2020-10-05 11:20:18 -07009063 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9064 sp<AudioPolicyMix> policyMix;
9065 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9066 policyMix->setOutput(desc);
9067 desc->mPolicyMix = policyMix;
9068 } else {
9069 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009070 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009071 }
9072
baek.kim -61c20122022-07-27 10:05:32 +00009073 } else if (hasPrimaryOutput() && speaker != nullptr
9074 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009075 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9076 // no duplicated output for:
9077 // - direct outputs
9078 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009079 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009080 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9081
9082 //TODO: configure audio effect output stage here
9083
9084 // open a duplicating output thread for the new output and the primary output
9085 sp<SwAudioOutputDescriptor> dupOutputDesc =
9086 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9087 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9088 if (status == NO_ERROR) {
9089 // add duplicated output descriptor
9090 addOutput(duplicatedOutput, dupOutputDesc);
9091 } else {
9092 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9093 mPrimaryOutput->mIoHandle, output);
9094 desc->close();
9095 removeOutput(output);
9096 nextAudioPortGeneration();
9097 return nullptr;
9098 }
9099 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009100 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9101 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9102 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009103 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009104 }
jiabinbce0c1d2020-10-05 11:20:18 -07009105 return desc;
9106}
9107
jiabinf1c73972022-04-14 16:28:52 -07009108status_t AudioPolicyManager::getDevicesForAttributes(
9109 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009110 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9111 // over any usage or content type also present in attr.
9112 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9113 attr.source != AUDIO_SOURCE_INVALID) {
9114 return getInputDevicesForAttributes(attr, devices);
9115 }
9116
jiabinf1c73972022-04-14 16:28:52 -07009117 // Devices are determined in the following precedence:
9118 //
9119 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9120 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9121 //
9122 // If no such dynamic policy then
9123 // 2) Devices containing an active client using setPreferredDevice
9124 // with same strategy as the attributes.
9125 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9126 //
9127 // If no corresponding active client with setPreferredDevice then
9128 // 3) Devices associated with the strategy determined by the attributes
9129 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9130 //
9131 // See related getOutputForAttrInt().
9132
9133 // check dynamic policies but only for primary descriptors (secondary not used for audible
9134 // audio routing, only used for duplication for playback capture)
9135 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009136 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009137 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009138 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9139 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9140 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009141 if (status != OK) {
9142 return status;
9143 }
9144
9145 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9146 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9147 // as they are unaffected by device/stream volume
9148 // (per SwAudioOutputDescriptor::isFixedVolume()).
9149 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9150 ) {
9151 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9152 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9153 devices.add(deviceDesc);
9154 } else {
9155 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9156 // which selects setPreferredDevice if active. This means forVolume call
9157 // will take an active setPreferredDevice, if such exists.
9158
9159 devices = mEngine->getOutputDevicesForAttributes(
9160 attr, nullptr /* preferredDevice */, false /* fromCache */);
9161 }
9162
9163 if (forVolume) {
9164 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9165 // for single volume control in AudioService (such relationship should exist if
9166 // SPEAKER_SAFE is present).
9167 //
9168 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9169 DeviceVector speakerSafeDevices =
9170 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9171 if (!speakerSafeDevices.isEmpty()) {
9172 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9173 devices.remove(speakerSafeDevices);
9174 }
9175 }
9176
9177 return NO_ERROR;
9178}
9179
wenyu zhang8558a332024-09-09 15:12:48 +00009180status_t AudioPolicyManager::getInputDevicesForAttributes(
9181 const audio_attributes_t &attr, DeviceVector &devices) {
9182 devices = DeviceVector(
9183 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9184 AUDIO_SESSION_NONE,
9185 nullptr /* mix */));
9186 return NO_ERROR;
9187}
9188
jiabinf1c73972022-04-14 16:28:52 -07009189status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9190 AudioProfileVector& audioProfiles,
9191 uint32_t flags,
9192 bool isInput) {
9193 for (const auto& hwModule : mHwModules) {
9194 // the MSD module checks for different conditions
9195 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9196 continue;
9197 }
9198 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9199 : hwModule->getOutputProfiles();
9200 for (const auto& profile : ioProfiles) {
9201 if (!profile->areAllDevicesSupported(devices) ||
9202 !profile->isCompatibleProfileForFlags(
9203 flags, false /*exactMatchRequiredForInputFlags*/)) {
9204 continue;
9205 }
9206 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9207 }
9208 }
9209
9210 if (!isInput) {
9211 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9212 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9213 if (msdModule != nullptr) {
9214 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9215 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9216 for (const auto &profile: msdModule->getOutputProfiles()) {
9217 if (!profile->asAudioPort()->isDirectOutput()) {
9218 continue;
9219 }
9220 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9221 }
9222 } else {
9223 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9224 }
9225 }
9226 }
9227
9228 return NO_ERROR;
9229}
9230
jiabin3ff8d7d2022-12-13 06:27:44 +00009231sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9232 const audio_config_t *config,
9233 audio_output_flags_t flags,
9234 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009235 closeOutput(outputDesc->mIoHandle);
9236 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9237 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9238 if (preferredOutput == nullptr) {
9239 ALOGE("%s failed to reopen output device=%d, caller=%s",
9240 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009241 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009242 return preferredOutput;
9243}
9244
9245void AudioPolicyManager::reopenOutputsWithDevices(
9246 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9247 for (const auto& [output, devices] : outputsToReopen) {
9248 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9249 closeOutput(output);
9250 openOutputWithProfileAndDevice(desc->mProfile, devices);
9251 }
jiabina84c3d32022-12-02 18:59:55 +00009252}
9253
jiabinc44b3462022-12-08 12:52:31 -08009254PortHandleVector AudioPolicyManager::getClientsForStream(
9255 audio_stream_type_t streamType) const {
9256 PortHandleVector clients;
9257 for (size_t i = 0; i < mOutputs.size(); ++i) {
9258 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9259 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9260 }
9261 return clients;
9262}
9263
9264void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9265 PortHandleVector clients;
9266 for (auto stream : streams) {
9267 PortHandleVector clientsForStream = getClientsForStream(stream);
9268 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9269 }
9270 mpClientInterface->invalidateTracks(clients);
9271}
9272
jiabin220eea12024-05-17 17:55:20 +00009273void AudioPolicyManager::updateClientsInternalMute(
9274 const sp<android::SwAudioOutputDescriptor> &desc) {
9275 if (!desc->isBitPerfect() ||
9276 !com::android::media::audioserver::
9277 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9278 // This is only used for bit perfect output now.
9279 return;
9280 }
9281 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9282 bool bitPerfectClientInternalMute = false;
9283 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9284 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9285 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9286 bitPerfectClient = client;
9287 continue;
9288 }
9289 bool muted = false;
9290 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9291 // System sound is muted.
9292 muted = true;
9293 } else {
9294 bitPerfectClientInternalMute = true;
9295 }
9296 if (client->setInternalMute(muted)) {
9297 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9298 if (!result.ok()) {
9299 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9300 continue;
9301 }
9302 media::TrackInternalMuteInfo info;
9303 info.portId = result.value();
9304 info.muted = client->getInternalMute();
9305 clientsInternalMute.push_back(std::move(info));
9306 }
9307 }
9308 if (bitPerfectClient != nullptr &&
9309 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9310 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9311 if (result.ok()) {
9312 media::TrackInternalMuteInfo info;
9313 info.portId = result.value();
9314 info.muted = bitPerfectClient->getInternalMute();
9315 clientsInternalMute.push_back(std::move(info));
9316 } else {
9317 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9318 __func__, bitPerfectClient->portId());
9319 }
9320 }
9321 if (!clientsInternalMute.empty()) {
9322 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9323 status != NO_ERROR) {
9324 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9325 }
9326 }
9327}
9328
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009329} // namespace android