blob: 2998d043476062c468fdbe8f853fd7f9093f2e2a [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 }
jiabin220eea12024-05-17 17:55:20 +00001410 if (com::android::media::audioserver::
1411 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1412 if (info != nullptr && info->getUid() == uid &&
1413 info->configMatches(*config) &&
1414 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1415 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1416 [this, &outputDevices](audio_usage_t usage) {
1417 return mOutputs.isUsageActiveOnDevice(
1418 usage, outputDevices[0]); }))) {
1419 // Bit-perfect request is not allowed when the phone mode is not normal or
1420 // there is any higher priority user case active.
1421 return INVALID_OPERATION;
1422 }
1423 }
jiabina84c3d32022-12-02 18:59:55 +00001424 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001425 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001426 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001427 // The client will be active if the client is currently preferred mixer owner and the
1428 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001429 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001430 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001431 && info->getUid() == uid
1432 && *output != AUDIO_IO_HANDLE_NONE
1433 // When bit-perfect output is selected for the preferred mixer attributes owner,
1434 // only need to consider the config matches.
1435 && mOutputs.valueFor(*output)->isConfigurationMatched(
1436 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001437
1438 if (*isBitPerfect) {
1439 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1440 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001442 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001443 AudioProfileVector profiles;
1444 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1445 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001446 const auto channels = profiles[0]->getChannels();
1447 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1448 config->channel_mask = *channels.begin();
1449 }
1450 const auto sampleRates = profiles[0]->getSampleRates();
1451 if (!sampleRates.empty() &&
1452 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1453 config->sample_rate = *sampleRates.begin();
1454 }
jiabinf1c73972022-04-14 16:28:52 -07001455 config->format = profiles[0]->getFormat();
1456 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001457 return INVALID_OPERATION;
1458 }
Paul McLeanaa981192015-03-21 09:55:15 -07001459
François Gaffiec005e562018-11-06 15:04:49 +01001460 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001461 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001462 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001463 *selectedDeviceId = outputDevice->getId();
1464 break;
1465 }
1466 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001467
Eric Laurent8a1095a2019-11-08 14:44:16 -08001468 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1469 *outputType = API_OUTPUT_TELEPHONY_TX;
1470 } else {
1471 *outputType = API_OUTPUT_LEGACY;
1472 }
1473
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001474 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1475
1476 return NO_ERROR;
1477}
1478
1479status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1480 audio_io_handle_t *output,
1481 audio_session_t session,
1482 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001483 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001484 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001485 audio_output_flags_t *flags,
1486 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001487 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001488 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001489 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001490 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001491 bool *isBitPerfect,
1492 float *volume)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001493{
1494 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1495 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1496 return INVALID_OPERATION;
1497 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001498 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001499 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001500 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001501 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001502 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001503 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001504 const sp<DeviceDescriptor> requestedDevice =
1505 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1506
1507 // Prevent from storing invalid requested device id in clients
1508 const audio_port_handle_t sanitizedRequestedPortId =
1509 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1510 *selectedDeviceId = sanitizedRequestedPortId;
1511
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001512 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001513 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001514 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1515 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001516 if (status != NO_ERROR) {
1517 return status;
1518 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001519 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001520 if (secondaryOutputs != nullptr) {
1521 for (auto &secondaryMix : secondaryMixes) {
1522 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1523 if (outputDesc != nullptr &&
1524 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1525 secondaryOutputs->push_back(outputDesc->mIoHandle);
1526 weakSecondaryOutputDescs.push_back(outputDesc);
1527 }
1528 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001529 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001530
Eric Laurent8fc147b2018-07-22 19:13:55 -07001531 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001532 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001533 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001534 };
jiabin4ef93452019-09-10 14:29:54 -07001535 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001536
Eric Laurentc209fe42020-06-05 18:11:23 -07001537 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001538 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001539 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001540 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001541 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001542 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001543 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001544 std::move(weakSecondaryOutputDescs),
1545 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001546 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001547
Andy Hung6b137d12024-08-27 22:35:17 +00001548 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
1549
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001550 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1551 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001552
Eric Laurente83b55d2014-11-14 10:06:21 -08001553 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001554}
1555
Eric Laurentc529cf62020-04-17 18:19:10 -07001556status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1557 audio_session_t session,
1558 const audio_config_t *config,
1559 audio_output_flags_t flags,
1560 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001561 audio_io_handle_t *output,
1562 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001563
1564 *output = AUDIO_IO_HANDLE_NONE;
1565
1566 // skip direct output selection if the request can obviously be attached to a mixed output
1567 // and not explicitly requested
1568 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1569 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1570 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1571 return NAME_NOT_FOUND;
1572 }
1573
Mikhail Naganov806170e2024-09-05 17:26:50 -07001574 // Reject flag combinations that do not make sense. Note that the requested flags might not
1575 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1576 // combine the requested flags with its own flags, yielding an unsupported combination.
1577 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1578 return NAME_NOT_FOUND;
1579 }
1580
Eric Laurentc529cf62020-04-17 18:19:10 -07001581 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1582 // This prevents creating an offloaded track and tearing it down immediately after start
1583 // when audioflinger detects there is an active non offloadable effect.
1584 // FIXME: We should check the audio session here but we do not have it in this context.
1585 // This may prevent offloading in rare situations where effects are left active by apps
1586 // in the background.
1587 sp<IOProfile> profile;
1588 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1589 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1590 profile = getProfileForOutput(
1591 devices, config->sample_rate, config->format, config->channel_mask,
1592 flags, true /* directOnly */);
1593 }
1594
1595 if (profile == nullptr) {
1596 return NAME_NOT_FOUND;
1597 }
1598
1599 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1600 for (size_t i = 0; i < mOutputs.size(); i++) {
1601 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1602 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1603 // reuse direct output if currently open by the same client
1604 // and configured with same parameters
1605 if ((config->sample_rate == desc->getSamplingRate()) &&
1606 (config->format == desc->getFormat()) &&
1607 (config->channel_mask == desc->getChannelMask()) &&
1608 (session == desc->mDirectClientSession)) {
1609 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301610 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001611 mOutputs.keyAt(i), session);
1612 *output = mOutputs.keyAt(i);
1613 return NO_ERROR;
1614 }
1615 }
1616 }
1617
1618 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001619 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301620 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1621 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001622 return NAME_NOT_FOUND;
1623 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1624 // MMAP gracefully handles lack of an exclusive track resource by mixing
1625 // above the audio framework. For AAudio to know that the limit is reached,
1626 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301627 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1628 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001629 return NAME_NOT_FOUND;
1630 } else {
1631 // Close outputs on this profile, if available, to free resources for this request
1632 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1633 const auto desc = mOutputs.valueAt(i);
1634 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301635 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1636 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001637 closeOutput(desc->mIoHandle);
1638 }
1639 }
1640 }
1641 }
1642
1643 // Unable to close streams to find free resources for this request
1644 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301645 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1646 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001647 return NAME_NOT_FOUND;
1648 }
1649
Atneya Nairb16666a2023-12-11 20:18:33 -08001650 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001651
Michael Chan6fb34492020-12-08 15:44:49 +11001652 // An MSD patch may be using the only output stream that can service this request. Release
1653 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001654 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001655
Eric Laurentf1f22e72021-07-13 14:04:14 +02001656 status_t status =
Haofan Wangf6e304f2024-07-09 23:06:58 -07001657 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1658 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001659
1660 // only accept an output with the requested parameters
1661 if (status != NO_ERROR ||
1662 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1663 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1664 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1665 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1666 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1667 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1668 config->channel_mask, outputDesc->getChannelMask());
1669 if (*output != AUDIO_IO_HANDLE_NONE) {
1670 outputDesc->close();
1671 }
1672 // fall back to mixer output if possible when the direct output could not be open
1673 if (audio_is_linear_pcm(config->format) &&
1674 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1675 return NAME_NOT_FOUND;
1676 }
1677 *output = AUDIO_IO_HANDLE_NONE;
1678 return BAD_VALUE;
1679 }
1680 outputDesc->mDirectOpenCount = 1;
1681 outputDesc->mDirectClientSession = session;
1682
1683 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001684 setOutputDevices(__func__, outputDesc,
1685 devices,
1686 true,
1687 0,
1688 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001689 mPreviousOutputs = mOutputs;
1690 ALOGV("%s returns new direct output %d", __func__, *output);
1691 mpClientInterface->onAudioPortListUpdate();
1692 return NO_ERROR;
1693}
1694
François Gaffie11d30102018-11-02 16:09:09 +01001695audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1696 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001697 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001698 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001699 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001700 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001701 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001702 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001703 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001704{
Andy Hungc88b0642018-04-27 15:42:35 -07001705 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001706
jiabine375d412019-02-26 12:54:53 -08001707 // Discard haptic channel mask when forcing muting haptic channels.
1708 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001709 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1710 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001711
Eric Laurente552edb2014-03-10 17:42:56 -07001712 // open a direct output if required by specified parameters
1713 //force direct flag if offload flag is set: offloading implies a direct output stream
1714 // and all common behaviors are driven by checking only the direct flag
1715 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001716 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1717 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001718 }
Nadav Bar766fb022018-01-07 12:18:03 +02001719 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1720 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001721 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001722
1723 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1724
Eric Laurente83b55d2014-11-14 10:06:21 -08001725 // only allow deep buffering for music stream type
1726 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001727 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001728 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001729 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001730 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001731 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001732 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001733 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001734 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001735 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001736 audio_is_linear_pcm(config->format) &&
1737 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001738 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001739 AUDIO_OUTPUT_FLAG_DIRECT);
1740 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001741 }
Eric Laurente552edb2014-03-10 17:42:56 -07001742
Carter Hsua3abb402021-10-26 11:11:20 +08001743 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1744 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1745 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1746 }
1747
Eric Laurentf9230d52024-01-26 18:49:09 +01001748 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001749 // was specified and offload or direct playback is not explicitly requested, and there is no
1750 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001751 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001752 if (mSpatializerOutput != nullptr &&
1753 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1754 prefMixerConfigInfo == nullptr &&
1755 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1756 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001757 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001758 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001759 }
1760
Eric Laurentc529cf62020-04-17 18:19:10 -07001761 audio_config_t directConfig = *config;
1762 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001763
1764 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1765 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001766 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001767 return output;
1768 }
1769
Eric Laurent14cbfca2016-03-17 09:42:16 -07001770 // A request for HW A/V sync cannot fallback to a mixed output because time
1771 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001772 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001773 return AUDIO_IO_HANDLE_NONE;
1774 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001775 // A request for Tuner cannot fallback to a mixed output
1776 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1777 return AUDIO_IO_HANDLE_NONE;
1778 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001779
Eric Laurente552edb2014-03-10 17:42:56 -07001780 // ignoring channel mask due to downmix capability in mixer
1781
1782 // open a non direct output
1783
1784 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001785 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001786 // get which output is suitable for the specified stream. The actual
1787 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001788 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001789 if (prefMixerConfigInfo != nullptr) {
1790 for (audio_io_handle_t outputHandle : outputs) {
1791 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1792 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1793 output = outputHandle;
1794 break;
1795 }
1796 }
1797 if (output == AUDIO_IO_HANDLE_NONE) {
1798 // No output open with the preferred profile. Open a new one.
1799 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1800 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1801 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1802 config.format = prefMixerConfigInfo->getConfigBase().format;
1803 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1804 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1805 &config, prefMixerConfigInfo->getFlags());
1806 if (preferredOutput == nullptr) {
1807 ALOGE("%s failed to open output with preferred mixer config", __func__);
1808 } else {
1809 output = preferredOutput->mIoHandle;
1810 }
1811 }
1812 } else {
1813 // at this stage we should ignore the DIRECT flag as no direct output could be
1814 // found earlier
1815 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001816 if (com::android::media::audioserver::
1817 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1818 // If the preferred mixer attributes is null, do not select the bit-perfect output
1819 // unless the bit-perfect output is the only output.
1820 // The bit-perfect output can exist while the passed in preferred mixer attributes
1821 // info is null when it is a high priority client. The high priority clients are
1822 // ringtone or alarm, which is not a bit-perfect use case.
1823 size_t i = 0;
1824 while (i < outputs.size() && outputs.size() > 1) {
1825 auto desc = mOutputs.valueFor(outputs[i]);
1826 // The output descriptor must not be null here.
1827 if (desc->isBitPerfect()) {
1828 outputs.removeItemsAt(i);
1829 } else {
1830 i += 1;
1831 }
1832 }
1833 }
jiabina84c3d32022-12-02 18:59:55 +00001834 output = selectOutput(
1835 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1836 }
Eric Laurente552edb2014-03-10 17:42:56 -07001837 }
François Gaffie11d30102018-11-02 16:09:09 +01001838 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001839 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001840 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001841
Eric Laurente552edb2014-03-10 17:42:56 -07001842 return output;
1843}
1844
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001845sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001846 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1847 mAvailableInputDevices);
1848 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1849}
1850
1851DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1852 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1853 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854}
1855
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001856const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001857 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001858 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1859 if (msdModule != 0) {
1860 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1861 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1862 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1863 const struct audio_port_config *source = &patch->mPatch.sources[j];
1864 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1865 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001866 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001867 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001868 }
1869 }
1870 }
1871 return msdPatches;
1872}
1873
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001874bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1875 ssize_t index = mAudioPatches.indexOfKey(handle);
1876 if (index < 0) {
1877 return false;
1878 }
1879 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1880 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1881 if (msdModule == nullptr) {
1882 return false;
1883 }
1884 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1885 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1886 return true;
1887 }
1888 index = getMsdOutputPatches().indexOfKey(handle);
1889 if (index < 0) {
1890 return false;
1891 }
1892 return true;
1893}
1894
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001895status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1896 const InputProfileCollection &inputProfiles,
1897 const OutputProfileCollection &outputProfiles,
1898 const sp<DeviceDescriptor> &sourceDevice,
1899 const sp<DeviceDescriptor> &sinkDevice,
1900 AudioProfileVector& sourceProfiles,
1901 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001902 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 return NO_INIT;
1905 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001906 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001907 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001908 return NO_INIT;
1909 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001910 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001911 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1912 inProfile->supportsDevice(sourceDevice)) {
1913 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001914 }
1915 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001916 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001917 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001918 outProfile->supportsDevice(sinkDevice)) {
1919 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001920 }
1921 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922 return NO_ERROR;
1923}
1924
1925status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1926 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1927 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1928{
Dean Wheatley16809da2022-12-09 14:55:46 +11001929 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1930 static const std::vector<audio_format_t> formatsOrder = {{
1931 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001932 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1933 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001934 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1935 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1936 // preferred).
1937 std::vector<audio_channel_mask_t> masks = {{
1938 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1939 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1940 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1941 // insert index masks (higher counts most preferred) as preferred over position masks
1942 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1943 masks.insert(
1944 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1945 }
1946 return masks;
1947 }();
1948
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001949 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001950 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1951 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1954 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001955 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001956 }
1957 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1958 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1959 sinkConfig->format = bestSinkConfig.format;
1960 // For encoded streams force direct flag to prevent downstream mixing.
1961 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1962 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001963 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1964 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001965 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001966 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1967 // raw and IEC61937 framed streams.
1968 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1969 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1970 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001971 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1972 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001973 sourceConfig->channel_mask =
1974 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1975 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1976 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001977 sourceConfig->format = bestSinkConfig.format;
1978 // Copy input stream directly without any processing (e.g. resampling).
1979 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1980 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1981 if (hwAvSync) {
1982 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1983 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1984 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1985 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1986 }
1987 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1988 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1989 sinkConfig->config_mask |= config_mask;
1990 sourceConfig->config_mask |= config_mask;
1991 return NO_ERROR;
1992}
1993
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001994PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1995 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001996{
1997 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001998 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1999 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2000 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2001 if (deviceModule == nullptr) {
2002 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2003 return patchBuilder;
2004 }
2005 const InputProfileCollection inputProfiles = msdIsSource ?
2006 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2007 const OutputProfileCollection outputProfiles = msdIsSource ?
2008 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2009
2010 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2011 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2012 device : getMsdAudioOutDevices().itemAt(0);
2013 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2014
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002015 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2016 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002017 AudioProfileVector sourceProfiles;
2018 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002019 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2020 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002021 for (auto hwAvSync : { true, false }) {
2022 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2023 sourceProfiles, sinkProfiles) != NO_ERROR) {
2024 continue;
2025 }
2026 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2027 &sinkConfig) == NO_ERROR) {
2028 // Found a matching config. Re-create PatchBuilder with this config.
2029 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2030 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002031 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002032 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002033 " supporting PCM format conversion.", __func__);
2034 return patchBuilder;
2035}
2036
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002037status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002038 DeviceVector devices;
2039 if (outputDevices != nullptr && outputDevices->size() > 0) {
2040 devices.add(*outputDevices);
2041 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002042 // Use media strategy for unspecified output device. This should only
2043 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2044 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002045 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002046 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002047 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002048 }
Michael Chan6fb34492020-12-08 15:44:49 +11002049 std::vector<PatchBuilder> patchesToCreate;
2050 for (auto i = 0u; i < devices.size(); ++i) {
2051 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002052 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002053 }
2054 // Retain only the MSD patches associated with outputDevices request.
2055 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002056 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002057 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2058 auto retainedPatch = false;
2059 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2060 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2061 patchesToRemove.removeItemsAt(i);
2062 retainedPatch = true;
2063 break;
2064 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002065 }
Michael Chan6fb34492020-12-08 15:44:49 +11002066 if (retainedPatch) {
2067 it = patchesToCreate.erase(it);
2068 continue;
2069 }
2070 ++it;
2071 }
2072 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2073 return NO_ERROR;
2074 }
2075 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2076 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002077 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002078 }
Michael Chan6fb34492020-12-08 15:44:49 +11002079 status_t status = NO_ERROR;
2080 for (const auto &p : patchesToCreate) {
2081 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2082 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2083 char message[256];
2084 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2085 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2086 currStatus == NO_ERROR ? "Success" : "Error",
2087 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2088 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2089 if (currStatus == NO_ERROR) {
2090 ALOGD("%s", message);
2091 } else {
2092 ALOGE("%s", message);
2093 if (status == NO_ERROR) {
2094 status = currStatus;
2095 }
2096 }
2097 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002098 return status;
2099}
2100
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002101void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2102 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002103 for (size_t i = 0; i < msdPatches.size(); i++) {
2104 const auto& patch = msdPatches[i];
2105 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2106 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2107 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2108 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2109 releaseAudioPatch(patch->getHandle(), mUidCached);
2110 break;
2111 }
2112 }
2113 }
2114}
2115
Dorin Drimus94d94412022-02-02 09:05:02 +01002116bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002117 DeviceVector devicesToCheck =
2118 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002119 AudioPatchCollection msdPatches = getMsdOutputPatches();
2120 for (size_t i = 0; i < msdPatches.size(); i++) {
2121 const auto& patch = msdPatches[i];
2122 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2123 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2124 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2125 const auto& foundDevice = devicesToCheck.getDevice(
2126 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2127 if (foundDevice != nullptr) {
2128 devicesToCheck.remove(foundDevice);
2129 if (devicesToCheck.isEmpty()) {
2130 return true;
2131 }
2132 }
2133 }
2134 }
2135 }
2136 return false;
2137}
2138
Eric Laurente0720872014-03-11 09:30:41 -07002139audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002140 audio_output_flags_t flags,
2141 audio_format_t format,
2142 audio_channel_mask_t channelMask,
2143 uint32_t samplingRate,
2144 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002145{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002146 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2147 "%s called with format %#x", __func__, format);
2148
jiabinebb6af42020-06-09 17:31:17 -07002149 // Return the output that haptic-generating attached to when 1) session id is specified,
2150 // 2) haptic-generating effect exists for given session id and 3) the output that
2151 // haptic-generating effect attached to is in given outputs.
2152 if (sessionId != AUDIO_SESSION_NONE) {
2153 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2154 sessionId, FX_IID_HAPTICGENERATOR);
2155 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2156 return hapticGeneratingOutput;
2157 }
2158 }
2159
Eric Laurent16c66dd2019-05-01 17:54:10 -07002160 // Flags disqualifying an output: the match must happen before calling selectOutput()
2161 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2162 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2163
2164 // Flags expressing a functional request: must be honored in priority over
2165 // other criteria
2166 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2167 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002168 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2169 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 // Flags expressing a performance request: have lower priority than serving
2171 // requested sampling rate or channel mask
2172 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2173 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2174 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2175
2176 const audio_output_flags_t functionalFlags =
2177 (audio_output_flags_t)(flags & kFunctionalFlags);
2178 const audio_output_flags_t performanceFlags =
2179 (audio_output_flags_t)(flags & kPerformanceFlags);
2180
2181 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2182
Eric Laurente552edb2014-03-10 17:42:56 -07002183 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002184 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002185 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002186 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002187 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002188 // with tiebreak preferring the minimum number of extra functional flags
2189 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 // 3: the output supporting the exact channel mask
2191 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002192 // 5: the output with the highest sampling rate if the requested sample rate is
2193 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002194 // 6: the output with the highest number of requested performance flags
2195 // 7: the output with the bit depth the closest to the requested one
2196 // 8: the primary output
2197 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002198
Eric Laurent16c66dd2019-05-01 17:54:10 -07002199 // matching criteria values in priority order for best matching output so far
2200 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002201
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002202 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2204 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2205 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002206
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002207 for (audio_io_handle_t output : outputs) {
2208 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002209 // matching criteria values in priority order for current output
2210 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002211
Eric Laurent16c66dd2019-05-01 17:54:10 -07002212 if (outputDesc->isDuplicated()) {
2213 continue;
2214 }
2215 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2216 continue;
2217 }
Eric Laurent8838a382014-09-08 16:44:28 -07002218
Eric Laurent16c66dd2019-05-01 17:54:10 -07002219 // If haptic channel is specified, use the haptic output if present.
2220 // When using haptic output, same audio format and sample rate are required.
2221 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002222 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002223 // skip if haptic channel specified but output does not support it, or output support haptic
2224 // but there is no haptic channel requested AND no orphan haptic effect exist
2225 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2226 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002227 continue;
2228 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002229 // In the case of audio-coupled-haptic playback, there is no format conversion and
2230 // resampling in the framework, same format/channel/sampleRate for client and the output
2231 // thread is required. In the case of HapticGenerator effect, do not require format
2232 // matching.
2233 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2234 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002235 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002236 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002237 }
2238
2239 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002240 const int matchingFunctionalFlags =
2241 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2242 const int totalFunctionalFlags =
2243 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2244 // Prefer matching functional flags, but subtract unnecessary functional flags.
2245 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002246
2247 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002248 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2249 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002250 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2251 channelCount <= outputChannelCount) {
2252 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002253 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2254 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002255 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002256 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002257 currentMatchCriteria[3] = outputChannelCount;
2258 }
2259
2260 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002261 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002262 int diff; // avoid unsigned integer overflow.
2263 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2264
2265 // prefer the closest output sampling rate greater than or equal to target
2266 // if none exists, prefer the closest output sampling rate less than target.
2267 //
2268 // criteria is offset to make non-negative.
2269 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002270 }
2271
2272 // performance flags match
2273 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2274
2275 // format match
2276 if (format != AUDIO_FORMAT_INVALID) {
2277 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002278 PolicyAudioPort::kFormatDistanceMax -
2279 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002280 }
2281
2282 // primary output match
2283 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2284
2285 // compare match criteria by priority then value
2286 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2287 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2288 bestMatchCriteria = currentMatchCriteria;
2289 bestOutput = output;
2290
2291 std::stringstream result;
2292 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2293 std::ostream_iterator<int>(result, " "));
2294 ALOGV("%s new bestOutput %d criteria %s",
2295 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002296 }
2297 }
2298
Eric Laurent16c66dd2019-05-01 17:54:10 -07002299 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002300}
2301
Eric Laurent8fc147b2018-07-22 19:13:55 -07002302status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002303{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002304 ALOGV("%s portId %d", __FUNCTION__, portId);
2305
2306 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2307 if (outputDesc == 0) {
2308 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002309 return BAD_VALUE;
2310 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002311 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002312
Eric Laurent8fc147b2018-07-22 19:13:55 -07002313 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002314 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002315
jiabin220eea12024-05-17 17:55:20 +00002316 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2317 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2318 && outputDesc->isBitPerfect()) {
2319 // Usually, APM selects bit-perfect output for high priority use cases only when
2320 // bit-perfect output is the only output that can be routed to the selected device.
2321 // However, here is no need to play high priority use cases such as ringtone and alarm
2322 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2323 // can attach to new output.
2324 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2325 __func__, client->stream());
2326 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2327 return DEAD_OBJECT;
2328 }
2329
Eric Laurent733ce942017-12-07 12:18:25 -08002330 status_t status = outputDesc->start();
2331 if (status != NO_ERROR) {
2332 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002333 }
2334
Eric Laurent97ac8712018-07-27 18:59:02 -07002335 uint32_t delayMs;
2336 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002337
2338 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002339 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002340 if (status == DEAD_OBJECT) {
2341 sp<SwAudioOutputDescriptor> desc =
2342 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2343 if (desc == nullptr) {
2344 // This is not common, it may indicate something wrong with the HAL.
2345 ALOGE("%s unable to open output with default config", __func__);
2346 return status;
2347 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002348 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002349 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002350 }
jiabina84c3d32022-12-02 18:59:55 +00002351
2352 // If the client is the first one active on preferred mixer parameters, reopen the output
2353 // if the current mixer parameters doesn't match the preferred one.
2354 if (outputDesc->devices().size() == 1) {
2355 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2356 outputDesc->devices()[0]->getId(), client->strategy());
2357 if (info != nullptr && info->getUid() == client->uid()) {
2358 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2359 info->getConfigBase(), info->getFlags())) {
2360 stopSource(outputDesc, client);
2361 outputDesc->stop();
2362 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2363 config.channel_mask = info->getConfigBase().channel_mask;
2364 config.sample_rate = info->getConfigBase().sample_rate;
2365 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002366 sp<SwAudioOutputDescriptor> desc =
2367 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2368 if (desc == nullptr) {
2369 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002370 }
jiabin220eea12024-05-17 17:55:20 +00002371 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002372 // Intentionally return error to let the client side resending request for
2373 // creating and starting.
2374 return DEAD_OBJECT;
2375 }
2376 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002377 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002378 // If it is first bit-perfect client, reroute all clients that will be routed to
2379 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2380 PortHandleVector clientsToInvalidate;
2381 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002382 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2383 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002384 continue;
2385 }
2386 for (const auto& c : mOutputs[i]->getClientIterable()) {
2387 clientsToInvalidate.push_back(c->portId());
2388 }
2389 }
2390 if (!clientsToInvalidate.empty()) {
2391 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2392 __func__);
2393 mpClientInterface->invalidateTracks(clientsToInvalidate);
2394 }
2395 }
jiabina84c3d32022-12-02 18:59:55 +00002396 }
2397 }
2398
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002399 if (client->hasPreferredDevice()) {
2400 // playback activity with preferred device impacts routing occurred, inform upper layers
2401 mpClientInterface->onRoutingUpdated();
2402 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002403 if (delayMs != 0) {
2404 usleep(delayMs * 1000);
2405 }
2406
jiabin220eea12024-05-17 17:55:20 +00002407 if (status == NO_ERROR &&
2408 outputDesc->mPreferredAttrInfo != nullptr &&
2409 outputDesc->isBitPerfect() &&
2410 com::android::media::audioserver::
2411 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2412 // A new client is started on bit-perfect output, update all clients internal mute.
2413 updateClientsInternalMute(outputDesc);
2414 }
2415
Eric Laurentc75307b2015-03-17 15:29:32 -07002416 return status;
2417}
2418
Eric Laurent96d1dda2022-03-14 17:14:19 +01002419bool AudioPolicyManager::isLeUnicastActive() const {
2420 if (isInCall()) {
2421 return true;
2422 }
2423 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2424}
2425
2426bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2427 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2428 return false;
2429 }
2430 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2431 ALOGV("%s active %d", __func__, active);
2432 return active;
2433}
2434
Eric Laurent97ac8712018-07-27 18:59:02 -07002435status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2436 const sp<TrackClientDescriptor>& client,
2437 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002438{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002439 // cannot start playback of STREAM_TTS if any other output is being used
2440 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002441
2442 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002443 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002444 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002445 auto clientStrategy = client->strategy();
2446 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002447 if (stream == AUDIO_STREAM_TTS) {
2448 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002449 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002450 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002451 return INVALID_OPERATION;
2452 } else {
2453 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2454 }
2455 } else {
2456 // some playback other than beacon starts
2457 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2458 }
2459
Eric Laurent77305a62016-07-25 16:39:22 -07002460 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002461 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002462 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002463
François Gaffie11d30102018-11-02 16:09:09 +01002464 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002465 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002467 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002468 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002469 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002470 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002471 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002472 } else {
2473 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002474 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002475 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2476 AUDIO_FORMAT_DEFAULT);
2477 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2478 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002479 }
2480
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002481 // requiresMuteCheck is false when we can bypass mute strategy.
2482 // It covers a common case when there is no materially active audio
2483 // and muting would result in unnecessary delay and dropped audio.
2484 const uint32_t outputLatencyMs = outputDesc->latency();
2485 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002486 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002487
Eric Laurente552edb2014-03-10 17:42:56 -07002488 // increment usage count for this stream on the requested output:
2489 // NOTE that the usage count is the same for duplicated output and hardware output which is
2490 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002491 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002492
2493 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002494 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002495 // Preferred device may be exclusive, use only if no other active clients on this output
2496 devices = DeviceVector(
2497 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2498 } else {
2499 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2500 }
François Gaffie11d30102018-11-02 16:09:09 +01002501 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002502 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002503 }
2504 }
Eric Laurente552edb2014-03-10 17:42:56 -07002505
François Gaffiec005e562018-11-06 15:04:49 +01002506 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002507 selectOutputForMusicEffects();
2508 }
2509
François Gaffie1c878552018-11-22 16:53:21 +01002510 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002511 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002512 if (devices.isEmpty()) {
2513 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002514 }
François Gaffiec005e562018-11-06 15:04:49 +01002515 bool shouldWait =
2516 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2517 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2518 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002519 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002520 const bool needToCloseBitPerfectOutput =
2521 (com::android::media::audioserver::
2522 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2523 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2524 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002525 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002526 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002527 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002528 // An output has a shared device if
2529 // - managed by the same hw module
2530 // - supports the currently selected device
2531 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002532 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002533
Eric Laurent77305a62016-07-25 16:39:22 -07002534 // force a device change if any other output is:
2535 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002536 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002537 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002538 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002539 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002540 // change the device currently selected by the other output.
2541 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002542 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002543 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002544 force = true;
2545 }
2546 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002547 // a notification so that audio focus effect can propagate, or that a mute/unmute
2548 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002549 const uint32_t latencyMs = desc->latency();
2550 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2551
2552 if (shouldWait && isActive && (waitMs < latencyMs)) {
2553 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002554 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002555
2556 // Require mute check if another output is on a shared device
2557 // and currently active to have proper drain and avoid pops.
2558 // Note restoring AudioTracks onto this output needs to invoke
2559 // a volume ramp if there is no mute.
2560 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002561
2562 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2563 outputsToReopen.push_back(desc);
2564 }
Eric Laurente552edb2014-03-10 17:42:56 -07002565 }
2566 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002567
jiabin220eea12024-05-17 17:55:20 +00002568 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002569 // If the output is open with preferred mixer attributes, but the routed device is
2570 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2571 // changed.
2572 return DEAD_OBJECT;
2573 }
jiabin220eea12024-05-17 17:55:20 +00002574 for (auto& outputToReopen : outputsToReopen) {
2575 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2576 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002577 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302578 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2579 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002580
Eric Laurente552edb2014-03-10 17:42:56 -07002581 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002582 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002583 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002584 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002585 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002586 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002587 outputDesc->useHwGain() /*force*/)) {
2588 // request AudioService to reinitialize the volume curves asynchronously
2589 ALOGE("checkAndSetVolume failed, requesting volume range init");
2590 mpClientInterface->onVolumeRangeInitRequest();
2591 };
Eric Laurente552edb2014-03-10 17:42:56 -07002592
2593 // update the outputs if starting an output with a stream that can affect notification
2594 // routing
2595 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002596
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002597 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002598 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002599 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002600 }
Eric Laurentdc462862016-07-19 12:29:53 -07002601
2602 if (waitMs > muteWaitMs) {
2603 *delayMs = waitMs - muteWaitMs;
2604 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002605
2606 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2607 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2608 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2609 // change occurs after the MixerThread starts and causes a stream volume
2610 // glitch.
2611 //
2612 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002613 }
Eric Laurentdc462862016-07-19 12:29:53 -07002614
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002615 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002616 mEngine->getForceUse(
2617 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002618 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002619 }
2620
Eric Laurent97ac8712018-07-27 18:59:02 -07002621 // Automatically enable the remote submix input when output is started on a re routing mix
2622 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002623 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2624 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2627 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002628 "remote-submix",
2629 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002630 }
2631
Eric Laurent96d1dda2022-03-14 17:14:19 +01002632 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2633
Eric Laurente552edb2014-03-10 17:42:56 -07002634 return NO_ERROR;
2635}
2636
Eric Laurent96d1dda2022-03-14 17:14:19 +01002637void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2638 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2639 bool isUnicastActive = isLeUnicastActive();
2640
2641 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002642 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002643 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2644 for (size_t i = 0; i < mOutputs.size(); i++) {
2645 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2646 if (desc != ignoredOutput && desc->isActive()
2647 && ((isUnicastActive &&
2648 !desc->devices().
2649 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2650 || (wasUnicastActive &&
2651 !desc->devices().getDevicesFromTypes(
2652 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2653 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2654 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002655 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002656 // If the device is using preferred mixer attributes, the output need to reopen
2657 // with default configuration when the new selected devices are different from
2658 // current routing devices.
2659 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2660 continue;
2661 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302662 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002663 // re-apply device specific volume if not done by setOutputDevice()
2664 if (!force) {
2665 applyStreamVolumes(desc, newDevices.types(), delayMs);
2666 }
2667 }
2668 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002669 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002670 }
2671}
2672
Eric Laurent8fc147b2018-07-22 19:13:55 -07002673status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002674{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002675 ALOGV("%s portId %d", __FUNCTION__, portId);
2676
2677 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2678 if (outputDesc == 0) {
2679 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002680 return BAD_VALUE;
2681 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002682 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002683
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002684 if (client->hasPreferredDevice(true)) {
2685 // playback activity with preferred device impacts routing occurred, inform upper layers
2686 mpClientInterface->onRoutingUpdated();
2687 }
2688
Eric Laurent97ac8712018-07-27 18:59:02 -07002689 ALOGV("stopOutput() output %d, stream %d, session %d",
2690 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002691
Eric Laurent97ac8712018-07-27 18:59:02 -07002692 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002693
Eric Laurent733ce942017-12-07 12:18:25 -08002694 if (status == NO_ERROR ) {
2695 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002696 } else {
2697 return status;
2698 }
2699
2700 if (outputDesc->devices().size() == 1) {
2701 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2702 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002703 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002704 if (info != nullptr && info->getUid() == client->uid()) {
2705 info->decreaseActiveClient();
2706 if (info->getActiveClientCount() == 0) {
2707 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002708 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002709 }
2710 }
jiabin220eea12024-05-17 17:55:20 +00002711 if (com::android::media::audioserver::
2712 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2713 !outputReopened && outputDesc->isBitPerfect()) {
2714 // Only need to update the clients' internal mute when the output is bit-perfect and it
2715 // is not reopened.
2716 updateClientsInternalMute(outputDesc);
2717 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002718 }
2719 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002720}
2721
Eric Laurent97ac8712018-07-27 18:59:02 -07002722status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2723 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002724{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002725 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002726 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002727 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002728 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002729
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002730 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2731
François Gaffie1c878552018-11-22 16:53:21 +01002732 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2733 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002734 // Automatically disable the remote submix input when output is stopped on a
2735 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002736 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002737 if (isSingleDeviceType(
2738 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002739 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002740 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002741 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2742 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002743 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002744 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002745 }
2746 }
2747 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002748 if (client->hasPreferredDevice(true) &&
2749 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002750 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002751 forceDeviceUpdate = true;
2752 }
2753
Eric Laurente552edb2014-03-10 17:42:56 -07002754 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002755 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002756
Eric Laurente552edb2014-03-10 17:42:56 -07002757 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002758 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002759 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002760 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002761
2762 // If the routing does not change, if an output is routed on a device using HwGain
2763 // (aka setAudioPortConfig) and there are still active clients following different
2764 // volume group(s), force reapply volume
2765 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2766 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2767
Eric Laurente552edb2014-03-10 17:42:56 -07002768 // delay the device switch by twice the latency because stopOutput() is executed when
2769 // the track stop() command is received and at that time the audio track buffer can
2770 // still contain data that needs to be drained. The latency only covers the audio HAL
2771 // and kernel buffers. Also the latency does not always include additional delay in the
2772 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302773 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002774 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002775
2776 // force restoring the device selection on other active outputs if it differs from the
2777 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002778 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002779 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002780 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002781 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002782 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002783 desc->isActive() &&
2784 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002785 (newDevices != desc->devices())) {
2786 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2787 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002788
jiabin220eea12024-05-17 17:55:20 +00002789 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002790 // If the device is using preferred mixer attributes, the output need to
2791 // reopen with default configuration when the new selected devices are
2792 // different from current routing devices.
2793 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2794 continue;
2795 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302796 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002797
Eric Laurent57de36c2016-09-28 16:59:11 -07002798 // re-apply device specific volume if not done by setOutputDevice()
2799 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002800 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002801 }
Eric Laurente552edb2014-03-10 17:42:56 -07002802 }
2803 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002804 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002805 // update the outputs if stopping one with a stream that can affect notification routing
2806 handleNotificationRoutingForStream(stream);
2807 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002808
2809 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2810 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002811 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002812 }
2813
François Gaffiec005e562018-11-06 15:04:49 +01002814 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002815 selectOutputForMusicEffects();
2816 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002817
2818 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2819
Eric Laurente552edb2014-03-10 17:42:56 -07002820 return NO_ERROR;
2821 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002822 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002823 return INVALID_OPERATION;
2824 }
2825}
2826
jiabinbce0c1d2020-10-05 11:20:18 -07002827bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002828{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002829 ALOGV("%s portId %d", __FUNCTION__, portId);
2830
2831 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2832 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002833 // If an output descriptor is closed due to a device routing change,
2834 // then there are race conditions with releaseOutput from tracks
2835 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2836 // destroyed shortly thereafter.
2837 //
2838 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002839 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002840 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002841 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002842
2843 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002844
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302845 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2846 if (outputDesc->isClientActive(client)) {
2847 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2848 stopOutput(portId);
2849 }
2850
Eric Laurent8fc147b2018-07-22 19:13:55 -07002851 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2852 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002853 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002854 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002855 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002856 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002857 if (--outputDesc->mDirectOpenCount == 0) {
2858 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002859 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002860 }
2861 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302862
Andy Hung39efb7a2018-09-26 15:39:28 -07002863 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002864 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2865 // The output is pending reopened to query dynamic profiles and
2866 // there is no active clients
2867 closeOutput(outputDesc->mIoHandle);
2868 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2869 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2870 if (newOutputDesc == nullptr) {
2871 ALOGE("%s failed to open output", __func__);
2872 }
2873 return true;
2874 }
2875 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002876}
2877
Eric Laurentcaf7f482014-11-25 17:50:47 -08002878status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2879 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002880 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002881 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002882 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002883 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002884 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002885 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002886 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002887 audio_port_handle_t *portId,
2888 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002889{
François Gaffiec005e562018-11-06 15:04:49 +01002890 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002891 "flags %#x attributes=%s requested device ID %d",
2892 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2893 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002894
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002896 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002897 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002898 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002899 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002900 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901 sp<RecordClientDescriptor> clientDesc;
2902 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002903 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905
2906 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2907 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2908 return INVALID_OPERATION;
2909 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002910
Francois Gaffie716e1432019-01-14 16:58:59 +01002911 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2912 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002913 }
2914
Paul McLean466dc8e2015-04-17 13:15:36 -06002915 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002916 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002917 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002918
Eric Laurentad2e7b92017-09-14 20:06:42 -07002919 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2920 // possible
2921 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2922 *input != AUDIO_IO_HANDLE_NONE) {
2923 ssize_t index = mInputs.indexOfKey(*input);
2924 if (index < 0) {
2925 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2926 status = BAD_VALUE;
2927 goto error;
2928 }
2929 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002930 RecordClientVector clients = inputDesc->getClientsForSession(session);
2931 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002932 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2933 status = BAD_VALUE;
2934 goto error;
2935 }
2936 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2937 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002938 // corresponds to a new client and is only permitted from the same UID.
2939 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940 if (clients.size() > 1) {
2941 for (const auto& client : clients) {
2942 // The client map is ordered by key values (portId) and portIds are allocated
2943 // incrementaly. So the first client in this list is the one opened by audio flinger
2944 // when the mmap stream is created and should be ignored as it does not correspond
2945 // to an actual client
2946 if (client == *clients.cbegin()) {
2947 continue;
2948 }
2949 if (uid != client->uid() && !client->isSilenced()) {
2950 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2951 uid, client->portId(), client->uid());
2952 status = INVALID_OPERATION;
2953 goto error;
2954 }
Eric Laurent331679c2018-04-16 17:03:16 -07002955 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002956 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002957 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002958 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002959
Eric Laurentfecbceb2021-02-09 14:46:43 +01002960 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002961 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002962 }
2963
2964 *input = AUDIO_IO_HANDLE_NONE;
2965 *inputType = API_INPUT_INVALID;
2966
Francois Gaffie716e1432019-01-14 16:58:59 +01002967 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002968 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002969 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002970 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002971 ALOGW("%s could not find input mix for attr %s",
2972 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002973 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002974 }
jiabinc1de2df2019-05-07 14:26:40 -07002975 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2976 String8(attr->tags + strlen("addr=")),
2977 AUDIO_FORMAT_DEFAULT);
2978 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002979 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002980 __func__, attributes.source, attributes.tags);
2981 status = BAD_VALUE;
2982 goto error;
2983 }
2984
Kevin Rocard25f9b052019-02-27 15:08:54 -08002985 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2986 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2987 } else {
2988 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2989 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002990 if (virtualDeviceId) {
2991 *virtualDeviceId = policyMix->mVirtualDeviceId;
2992 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002993 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002994 if (explicitRoutingDevice != nullptr) {
2995 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002996 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002997 // Prevent from storing invalid requested device id in clients
2998 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002999 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003000 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3001 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003002 }
François Gaffie11d30102018-11-02 16:09:09 +01003003 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003004 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003005 status = BAD_VALUE;
3006 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003007 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003008 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3009 *inputType = API_INPUT_MIX_CAPTURE;
3010 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003011 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3012 // there is an external policy, but this input is attached to a mix of recorders,
3013 // meaning it receives audio injected into the framework, so the recorder doesn't
3014 // know about it and is therefore considered "legacy"
3015 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003016
3017 if (virtualDeviceId) {
3018 *virtualDeviceId = policyMix->mVirtualDeviceId;
3019 }
François Gaffie11d30102018-11-02 16:09:09 +01003020 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003021 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003022 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003023 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003024 } else {
3025 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003026 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003027
Eric Laurent599c7582015-12-07 18:05:55 -08003028 }
3029
François Gaffiec005e562018-11-06 15:04:49 +01003030 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003031 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003032 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003033 AudioProfileVector profiles;
3034 status_t ret = getProfilesForDevices(
3035 DeviceVector(device), profiles, flags, true /*isInput*/);
3036 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003037 const auto channels = profiles[0]->getChannels();
3038 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3039 config->channel_mask = *channels.begin();
3040 }
3041 const auto sampleRates = profiles[0]->getSampleRates();
3042 if (!sampleRates.empty() &&
3043 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3044 config->sample_rate = *sampleRates.begin();
3045 }
jiabinf1c73972022-04-14 16:28:52 -07003046 config->format = profiles[0]->getFormat();
3047 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003048 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003049 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003050
Marvin Ramine5a122d2023-12-07 13:57:59 +01003051
3052 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3053 *virtualDeviceId = policyMix->mVirtualDeviceId;
3054 }
3055
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056exit:
3057
François Gaffiec005e562018-11-06 15:04:49 +01003058 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3059 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003060
Francois Gaffie716e1432019-01-14 16:58:59 +01003061 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003062 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003063 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003064
Mikhail Naganov2996f672019-04-18 12:29:59 -07003065 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003066 requestedDeviceId, attributes.source, flags,
3067 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003068 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003069 // Move (if found) effect for the client session to its input
3070 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003071 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003072
3073 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3074 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003075
Eric Laurent599c7582015-12-07 18:05:55 -08003076 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003077
3078error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003079 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003080}
3081
3082
François Gaffie11d30102018-11-02 16:09:09 +01003083audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003084 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003085 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003086 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003087 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003088 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003089{
3090 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003091 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003092 bool isSoundTrigger = false;
3093
François Gaffiec005e562018-11-06 15:04:49 +01003094 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003095 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3096 if (index >= 0) {
3097 input = mSoundTriggerSessions.valueFor(session);
3098 isSoundTrigger = true;
3099 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3100 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3101 } else {
3102 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003103 }
François Gaffiec005e562018-11-06 15:04:49 +01003104 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003105 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003106 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003107 }
3108
Carter Hsua3abb402021-10-26 11:11:20 +08003109 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3110 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3111 }
3112
Eric Laurentfe231122017-11-17 17:48:06 -08003113 // sampling rate and flags may be updated by getInputProfile
3114 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3115 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003116 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003117 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003118 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003119 // find a compatible input profile (not necessarily identical in parameters)
3120 sp<IOProfile> profile = getInputProfile(
3121 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3122 if (profile == nullptr) {
3123 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003124 }
jiabin2fd710d2022-05-02 23:20:22 +00003125
Glenn Kasten05ddca52016-02-11 08:17:12 -08003126 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003127 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003128 if (samplingRate == 0) {
3129 samplingRate = profileSamplingRate;
3130 }
Eric Laurente552edb2014-03-10 17:42:56 -07003131
Eric Laurent322b4d22015-04-03 15:57:54 -07003132 if (profile->getModuleHandle() == 0) {
3133 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003134 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003135 }
3136
Eric Laurentec376dc2021-04-08 20:41:22 +02003137 // Reuse an already opened input if a client with the same session ID already exists
3138 // on that input
3139 for (size_t i = 0; i < mInputs.size(); i++) {
3140 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3141 if (desc->mProfile != profile) {
3142 continue;
3143 }
3144 RecordClientVector clients = desc->clientsList();
3145 for (const auto &client : clients) {
3146 if (session == client->session()) {
3147 return desc->mIoHandle;
3148 }
3149 }
3150 }
3151
Eric Laurentc71b11b2024-06-03 12:54:53 +00003152 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003153 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003154 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3155 // First pick best candidate for preemption (there may not be any):
3156 // - Preempt and input if:
3157 // - It has only strictly lower priority use cases than the new client
3158 // - It has equal priority use cases than the new client, was not
3159 // opened thanks to preemption or has been active since opened.
3160 // - Order the preemption candidates by inactive first and priority second
3161 sp<AudioInputDescriptor> closeCandidate;
3162 int leastCloseRank = INT_MAX;
3163 static const int sCloseActive = 0x100;
3164
3165 for (size_t i = 0; i < mInputs.size(); i++) {
3166 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3167 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003168 continue;
3169 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003170 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3171 if (topPrioClient == nullptr) {
3172 continue;
3173 }
3174 int topPrio = source_priority(topPrioClient->source());
3175 if (topPrio < source_priority(attributes.source)
3176 || (topPrio == source_priority(attributes.source)
3177 && !desc->isPreemptor())) {
3178 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3179 if (closeRank < leastCloseRank) {
3180 leastCloseRank = closeRank;
3181 closeCandidate = desc;
3182 }
3183 }
3184 }
3185
3186 if (closeCandidate != nullptr) {
3187 closeInput(closeCandidate->mIoHandle);
3188 // Mark the new input as being issued from a preemption
3189 // so that is will not be preempted later
3190 isPreemptor = true;
3191 } else {
3192 // Then pick the best reusable input (There is always one)
3193 // The order of preference is:
3194 // 1) active inputs with same use case as the new client
3195 // 2) inactive inputs with same use case
3196 // 3) active inputs with different use cases
3197 // 4) inactive inputs with different use cases
3198 sp<AudioInputDescriptor> reuseCandidate;
3199 int leastReuseRank = INT_MAX;
3200 static const int sReuseDifferentUseCase = 0x100;
3201
3202 for (size_t i = 0; i < mInputs.size(); i++) {
3203 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3204 if (desc->mProfile != profile) {
3205 continue;
3206 }
3207 int reuseRank = sReuseDifferentUseCase;
3208 for (const auto& client: desc->getClientIterable()) {
3209 if (client->source() == attributes.source) {
3210 reuseRank = 0;
3211 break;
3212 }
3213 }
3214 reuseRank += desc->isActive() ? 0 : 1;
3215 if (reuseRank < leastReuseRank) {
3216 leastReuseRank = reuseRank;
3217 reuseCandidate = desc;
3218 }
3219 }
3220 return reuseCandidate->mIoHandle;
3221 }
3222 } else { // fix_input_sharing_logic()
3223 for (size_t i = 0; i < mInputs.size(); ) {
3224 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3225 if (desc->mProfile != profile) {
3226 i++;
3227 continue;
3228 }
3229 // if sound trigger, reuse input if used by other sound trigger on same session
3230 // else
3231 // reuse input if active client app is not in IDLE state
3232 //
3233 RecordClientVector clients = desc->clientsList();
3234 bool doClose = false;
3235 for (const auto& client : clients) {
3236 if (isSoundTrigger != client->isSoundTrigger()) {
3237 continue;
3238 }
3239 if (client->isSoundTrigger()) {
3240 if (session == client->session()) {
3241 return desc->mIoHandle;
3242 }
3243 continue;
3244 }
3245 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003246 return desc->mIoHandle;
3247 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003248 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003249 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003250 if (doClose) {
3251 closeInput(desc->mIoHandle);
3252 } else {
3253 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003254 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003255 }
3256 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003257 }
3258
Eric Laurentc71b11b2024-06-03 12:54:53 +00003259 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3260 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003261
Eric Laurentfe231122017-11-17 17:48:06 -08003262 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3263 lConfig.sample_rate = profileSamplingRate;
3264 lConfig.channel_mask = profileChannelMask;
3265 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003266
François Gaffie11d30102018-11-02 16:09:09 +01003267 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003268
3269 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003270 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003271 (profileSamplingRate != lConfig.sample_rate) ||
3272 !audio_formats_match(profileFormat, lConfig.format) ||
3273 (profileChannelMask != lConfig.channel_mask)) {
3274 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003275 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003276 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003277 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003278 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003279 }
Eric Laurent599c7582015-12-07 18:05:55 -08003280 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003281 }
3282
Eric Laurentc722f302014-12-10 11:21:49 -08003283 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003284
Eric Laurent599c7582015-12-07 18:05:55 -08003285 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003286 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003287
Eric Laurent599c7582015-12-07 18:05:55 -08003288 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003289}
3290
Eric Laurent4eb58f12018-12-07 16:41:02 -08003291status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003292{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003293 ALOGV("%s portId %d", __FUNCTION__, portId);
3294
3295 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3296 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003297 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003298 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003299 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003300 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003301 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 if (client->active()) {
3303 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3304 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003305 }
3306
Eric Laurent8f42ea12018-08-08 09:08:25 -07003307 audio_session_t session = client->session();
3308
Eric Laurent4eb58f12018-12-07 16:41:02 -08003309 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310
Eric Laurent4eb58f12018-12-07 16:41:02 -08003311 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003312
Eric Laurent4eb58f12018-12-07 16:41:02 -08003313 status_t status = inputDesc->start();
3314 if (status != NO_ERROR) {
3315 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003316 }
Eric Laurente552edb2014-03-10 17:42:56 -07003317
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003318 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003319 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003320 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003321
Eric Laurent8f42ea12018-08-08 09:08:25 -07003322 // indicate active capture to sound trigger service if starting capture from a mic on
3323 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003324 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003325 if (device != nullptr) {
3326 status = setInputDevice(input, device, true /* force */);
3327 } else {
3328 ALOGW("%s no new input device can be found for descriptor %d",
3329 __FUNCTION__, inputDesc->getId());
3330 status = BAD_VALUE;
3331 }
Eric Laurente552edb2014-03-10 17:42:56 -07003332
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003333 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003334 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003335 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003336 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003337 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3338 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003339 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003340 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003341
François Gaffie11d30102018-11-02 16:09:09 +01003342 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3343 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003344 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003345 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003347
Eric Laurent8f42ea12018-08-08 09:08:25 -07003348 // automatically enable the remote submix output when input is started if not
3349 // used by a policy mix of type MIX_TYPE_RECORDERS
3350 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003351 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003353 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003354 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003355 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3356 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003357 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003358 if (address != "") {
3359 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3360 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003361 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003362 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003363 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003364 } else if (status != NO_ERROR) {
3365 // Restore client activity state.
3366 inputDesc->setClientActive(client, false);
3367 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003368 }
3369
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003370 ALOGV("%s input %d source = %d status = %d exit",
3371 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003372
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003373 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003374}
3375
Eric Laurent8fc147b2018-07-22 19:13:55 -07003376status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003377{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003378 ALOGV("%s portId %d", __FUNCTION__, portId);
3379
3380 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3381 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003382 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003383 return BAD_VALUE;
3384 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003385 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003386 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387 if (!client->active()) {
3388 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003389 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003390 }
Carter Hsue6139d52021-07-08 10:30:20 +08003391 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003392 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003393
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 inputDesc->stop();
3395 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003396 auto current_source = inputDesc->source();
3397 setInputDevice(input, getNewInputDevice(inputDesc),
3398 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003399 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003400 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003401 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003402 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003403 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3404 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003405 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003406 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003407
3408 // automatically disable the remote submix output when input is stopped if not
3409 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003410 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003411 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003412 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003413 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003414 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3415 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003416 }
3417 if (address != "") {
3418 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3419 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003420 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003421 }
3422 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003423 resetInputDevice(input);
3424
3425 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3426 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003427 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3428 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003429 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003430 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003431 }
3432 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003433 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003434 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003435}
3436
Eric Laurent8fc147b2018-07-22 19:13:55 -07003437void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003438{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003439 ALOGV("%s portId %d", __FUNCTION__, portId);
3440
3441 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3442 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003443 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003444 return;
3445 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003446 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003447 audio_io_handle_t input = inputDesc->mIoHandle;
3448
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003450
Andy Hung39efb7a2018-09-26 15:39:28 -07003451 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003452
3453 // If no more clients are present in this session, park effects to an orphan chain
3454 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3455 if (clientsOnSession.size() == 0) {
3456 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3457 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003458 if (inputDesc->getClientCount() > 0) {
3459 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003460 return;
3461 }
3462
Eric Laurent05b90f82014-08-27 15:32:29 -07003463 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003464 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003465 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003466}
3467
Eric Laurent8f42ea12018-08-08 09:08:25 -07003468void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003469{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003470 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003471
3472 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003473 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003474 }
3475}
3476
Eric Laurent8f42ea12018-08-08 09:08:25 -07003477void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3478{
3479 stopInput(portId);
3480 releaseInput(portId);
3481}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003482
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003483bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3484 if (input->clientsList().size() == 0
3485 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3486 return true;
3487 }
3488 for (const auto& client : input->clientsList()) {
3489 sp<DeviceDescriptor> device =
3490 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3491 client->session());
3492 if (!input->supportedDevices().contains(device)) {
3493 return true;
3494 }
3495 }
3496 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3497 return false;
3498}
3499
Eric Laurent0dd51852019-04-19 18:18:58 -07003500void AudioPolicyManager::checkCloseInputs() {
3501 // After connecting or disconnecting an input device, close input if:
3502 // - it has no client (was just opened to check profile) OR
3503 // - none of its supported devices are connected anymore OR
3504 // - one of its clients cannot be routed to one of its supported
3505 // devices anymore. Otherwise update device selection
3506 std::vector<audio_io_handle_t> inputsToClose;
3507 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003508 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003509 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003510 }
3511 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003512 for (const audio_io_handle_t handle : inputsToClose) {
3513 ALOGV("%s closing input %d", __func__, handle);
3514 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003515 }
Eric Laurentd4692962014-05-05 18:13:44 -07003516}
3517
Vlad Popa87e0e582024-05-20 18:49:20 -07003518status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3519 const char *address __unused,
3520 bool enabled,
3521 audio_stream_type_t streamToDriveAbs)
3522{
Vlad Popaa536eb32024-07-18 16:00:35 -07003523 if (!enabled) {
3524 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3525 return NO_ERROR;
3526 }
3527
Vlad Popa87e0e582024-05-20 18:49:20 -07003528 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3529 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3530 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3531 toString(streamToDriveAbs).c_str());
3532 return BAD_VALUE;
3533 }
3534
Vlad Popaa536eb32024-07-18 16:00:35 -07003535 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003536 return NO_ERROR;
3537}
3538
François Gaffie251c7f02018-11-07 10:41:08 +01003539void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003540{
3541 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003542 if (indexMin < 0 || indexMax < 0) {
3543 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3544 return;
3545 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003546 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003547
3548 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003549 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3550 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003551 continue;
3552 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003553 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003554 }
Eric Laurente552edb2014-03-10 17:42:56 -07003555}
3556
Eric Laurente0720872014-03-11 09:30:41 -07003557status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003558 int index,
3559 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003560{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003561 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003562 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3563 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3564 return NO_ERROR;
3565 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303566 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3567 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003568 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003569}
3570
Eric Laurente0720872014-03-11 09:30:41 -07003571status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003572 int *index,
3573 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003574{
François Gaffiec005e562018-11-06 15:04:49 +01003575 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3576 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003577 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003578 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003579 deviceTypes = mEngine->getOutputDevicesForStream(
3580 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003581 }
jiabin9a3361e2019-10-01 09:38:30 -07003582 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003583}
3584
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003585status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003586 int index,
3587 audio_devices_t device)
3588{
3589 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003590 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3591 if (group == VOLUME_GROUP_NONE) {
3592 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003593 return BAD_VALUE;
3594 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003595 ALOGV("%s: group %d matching with %s index %d",
3596 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003597 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003598 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003599 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003600 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3601 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3602 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3603 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003604 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3605
3606 status = setVolumeCurveIndex(index, device, curves);
3607 if (status != NO_ERROR) {
3608 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3609 return status;
3610 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003611
jiabin9a3361e2019-10-01 09:38:30 -07003612 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003613 auto curCurvAttrs = curves.getAttributes();
3614 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3615 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003616 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003617 } else if (!curves.getStreamTypes().empty()) {
3618 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003619 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003620 } else {
3621 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3622 return BAD_VALUE;
3623 }
jiabin9a3361e2019-10-01 09:38:30 -07003624 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3625 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003626
François Gaffiecfe17322018-11-07 13:41:29 +01003627 // update volume on all outputs and streams matching the following:
3628 // - The requested stream (or a stream matching for volume control) is active on the output
3629 // - The device (or devices) selected by the engine for this stream includes
3630 // the requested device
3631 // - For non default requested device, currently selected device on the output is either the
3632 // requested device or one of the devices selected by the engine for this stream
3633 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3634 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003635 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003636 for (size_t i = 0; i < mOutputs.size(); i++) {
3637 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003638 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639
jiabin9a3361e2019-10-01 09:38:30 -07003640 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3641 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003642 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003643
3644 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003645 continue;
3646 }
3647 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3648 curDevices.find(device) == curDevices.end()) {
3649 continue;
3650 }
3651 bool applyVolume = false;
3652 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3653 curSrcDevices.insert(device);
3654 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003655 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3656 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003657 } else {
3658 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3659 }
3660 if (!applyVolume) {
3661 continue; // next output
3662 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003663 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3664 // If a higher priority strategy is active, and the output is routed to a device with a
3665 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003666 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003667 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003668 // If the volume source is active with higher priority source, ensure at least Sw Muted
3669 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003670 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3671 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3672 false /*preferredDevice*/);
3673 if (activeClients.empty()) {
3674 continue;
3675 }
3676 bool isPreempted = false;
3677 bool isHigherPriority = productStrategy < strategy;
3678 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003679 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003680 ALOGV("%s: Strategy=%d (\nrequester:\n"
3681 " group %d, volumeGroup=%d attributes=%s)\n"
3682 " higher priority source active:\n"
3683 " volumeGroup=%d attributes=%s) \n"
3684 " on output %zu, bailing out", __func__, productStrategy,
3685 group, group, toString(attributes).c_str(),
3686 client->volumeSource(), toString(client->attributes()).c_str(), i);
3687 applyVolume = false;
3688 isPreempted = true;
3689 break;
3690 }
3691 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003692 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003693 applyVolume = true;
3694 }
3695 }
3696 if (isPreempted || applyVolume) {
3697 break;
3698 }
3699 }
3700 if (!applyVolume) {
3701 continue; // next output
3702 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003703 }
François Gaffieed91f582020-01-31 10:35:37 +01003704 //FIXME: workaround for truncated touch sounds
3705 // delayed volume change for system stream to be removed when the problem is
3706 // handled by system UI
3707 status_t volStatus = checkAndSetVolume(
3708 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003709 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003710 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3711 if (volStatus != NO_ERROR) {
3712 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003713 }
3714 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003715
3716 // update voice volume if the an active call route exists
3717 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3718 && (curSrcDevices.find(
3719 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3720 != curSrcDevices.end())) {
3721 bool isVoiceVolSrc;
3722 bool isBtScoVolSrc;
3723 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3724 isVoiceVolSrc, isBtScoVolSrc, __func__)
3725 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003726 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3727 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3728 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003729 }
3730 }
3731
François Gaffiecfe17322018-11-07 13:41:29 +01003732 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3733 return status;
3734}
3735
François Gaffieaaac0fd2018-11-22 17:56:39 +01003736status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003737 audio_devices_t device,
3738 IVolumeCurves &volumeCurves)
3739{
3740 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3741 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003742 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3743 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003744 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303745 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3746 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003747 return BAD_VALUE;
3748 }
3749 if (!audio_is_output_device(device)) {
3750 return BAD_VALUE;
3751 }
3752
3753 // Force max volume if stream cannot be muted
3754 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3755
François Gaffieaaac0fd2018-11-22 17:56:39 +01003756 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003757 volumeCurves.addCurrentVolumeIndex(device, index);
3758 return NO_ERROR;
3759}
3760
3761status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3762 int &index,
3763 audio_devices_t device)
3764{
3765 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3766 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003767 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003768 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003769 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003770 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003771 }
jiabin9a3361e2019-10-01 09:38:30 -07003772 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003773}
3774
3775status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3776 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003777 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003778{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003779 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003780 return BAD_VALUE;
3781 }
jiabin9a3361e2019-10-01 09:38:30 -07003782 index = curves.getVolumeIndex(deviceTypes);
3783 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003784 return NO_ERROR;
3785}
3786
3787status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3788 int &index)
3789{
3790 index = getVolumeCurves(attr).getVolumeIndexMin();
3791 return NO_ERROR;
3792}
3793
3794status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3795 int &index)
3796{
3797 index = getVolumeCurves(attr).getVolumeIndexMax();
3798 return NO_ERROR;
3799}
3800
Eric Laurent36829f92017-04-07 19:04:42 -07003801audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003802{
3803 // select one output among several suitable for global effects.
3804 // The priority is as follows:
3805 // 1: An offloaded output. If the effect ends up not being offloadable,
3806 // AudioFlinger will invalidate the track and the offloaded output
3807 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003808 // 2: Spatializer output if the stereo spatializer feature enabled
3809 // 3: A deep buffer output
3810 // 4: The primary output
3811 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003812
François Gaffiec005e562018-11-06 15:04:49 +01003813 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3814 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003815 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003816
Eric Laurent36829f92017-04-07 19:04:42 -07003817 if (outputs.size() == 0) {
3818 return AUDIO_IO_HANDLE_NONE;
3819 }
Eric Laurente552edb2014-03-10 17:42:56 -07003820
Eric Laurent36829f92017-04-07 19:04:42 -07003821 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3822 bool activeOnly = true;
3823
3824 while (output == AUDIO_IO_HANDLE_NONE) {
3825 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003826 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003827 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3828 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3829
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003830 for (audio_io_handle_t outputLoop : outputs) {
3831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003832 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003833 continue;
3834 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003835 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003836 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003837 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003838 outputOffloaded = outputLoop;
3839 }
3840 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3841 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3842 outputSpatializer = outputLoop;
3843 }
Eric Laurent36829f92017-04-07 19:04:42 -07003844 }
3845 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003846 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003847 }
3848 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003849 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003850 }
3851 }
3852 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3853 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003854 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3855 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003856 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3857 output = outputDeepBuffer;
3858 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3859 output = outputPrimary;
3860 } else {
3861 output = outputs[0];
3862 }
3863 activeOnly = false;
3864 }
3865
3866 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003867 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3868 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003869 mMusicEffectOutput = output;
3870 }
3871
3872 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003873 return output;
3874}
3875
Eric Laurent36829f92017-04-07 19:04:42 -07003876audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3877{
3878 return selectOutputForMusicEffects();
3879}
3880
Eric Laurente0720872014-03-11 09:30:41 -07003881status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003882 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003883 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003884 int session,
3885 int id)
3886{
Shunkai Yao29d10572024-03-19 04:31:47 +00003887 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003888 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003889 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003890 index = mInputs.indexOfKey(io);
3891 if (index < 0) {
3892 ALOGW("registerEffect() unknown io %d", io);
3893 return INVALID_OPERATION;
3894 }
Eric Laurente552edb2014-03-10 17:42:56 -07003895 }
3896 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003897 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3898 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3899 || strategy == PRODUCT_STRATEGY_NONE));
3900 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003901}
3902
Eric Laurentc241b0d2018-11-28 09:08:49 -08003903status_t AudioPolicyManager::unregisterEffect(int id)
3904{
3905 if (mEffects.getEffect(id) == nullptr) {
3906 return INVALID_OPERATION;
3907 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003908 if (mEffects.isEffectEnabled(id)) {
3909 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3910 setEffectEnabled(id, false);
3911 }
3912 return mEffects.unregisterEffect(id);
3913}
3914
3915status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3916{
3917 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3918 if (effect == nullptr) {
3919 return INVALID_OPERATION;
3920 }
3921
3922 status_t status = mEffects.setEffectEnabled(id, enabled);
3923 if (status == NO_ERROR) {
3924 mInputs.trackEffectEnabled(effect, enabled);
3925 }
3926 return status;
3927}
3928
Eric Laurent6c796322019-04-09 14:13:17 -07003929
3930status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3931{
3932 mEffects.moveEffects(ids, io);
3933 return NO_ERROR;
3934}
3935
Eric Laurentc75307b2015-03-17 15:29:32 -07003936bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3937{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003938 auto vs = toVolumeSource(stream, false);
3939 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003940}
3941
3942bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3943{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003944 auto vs = toVolumeSource(stream, false);
3945 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003946}
3947
Eric Laurente0720872014-03-11 09:30:41 -07003948bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003949{
3950 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003951 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003952 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003953 return true;
3954 }
3955 }
3956 return false;
3957}
3958
Eric Laurent275e8e92014-11-30 15:14:47 -08003959// Register a list of custom mixes with their attributes and format.
3960// When a mix is registered, corresponding input and output profiles are
3961// added to the remote submix hw module. The profile contains only the
3962// parameters (sampling rate, format...) specified by the mix.
3963// The corresponding input remote submix device is also connected.
3964//
3965// When a remote submix device is connected, the address is checked to select the
3966// appropriate profile and the corresponding input or output stream is opened.
3967//
3968// When capture starts, getInputForAttr() will:
3969// - 1 look for a mix matching the address passed in attribtutes tags if any
3970// - 2 if none found, getDeviceForInputSource() will:
3971// - 2.1 look for a mix matching the attributes source
3972// - 2.2 if none found, default to device selection by policy rules
3973// At this time, the corresponding output remote submix device is also connected
3974// and active playback use cases can be transferred to this mix if needed when reconnecting
3975// after AudioTracks are invalidated
3976//
3977// When playback starts, getOutputForAttr() will:
3978// - 1 look for a mix matching the address passed in attribtutes tags if any
3979// - 2 if none found, look for a mix matching the attributes usage
3980// - 3 if none found, default to device and output selection by policy rules.
3981
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003982status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003983{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003984 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3985 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003986 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003987 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003988 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003989 // examine each mix's route type
3990 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003991 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003992 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3993 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3994 ALOGE("Unsupported Policy Mix %zu of %zu: "
3995 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3996 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003997 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003998 break;
3999 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004000 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4001 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004002 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004003 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4004 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004005 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004006 rSubmixModule = mHwModules.getModuleFromName(
4007 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4008 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004009 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004010 i);
4011 res = INVALID_OPERATION;
4012 break;
4013 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004014 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004015
Eric Laurent97ac8712018-07-27 18:59:02 -07004016 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004017 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004018 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004019 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004020 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4021 } else {
4022 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4023 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004024 }
François Gaffie036e1e92015-03-19 10:16:24 +01004025
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004026 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004027 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004028 res = INVALID_OPERATION;
4029 break;
4030 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004031 audio_config_t outputConfig = mix.mFormat;
4032 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004033 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4034 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4036 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004037 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004038 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4039 audio_is_linear_pcm(outputConfig.format)
4040 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004041 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004042 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4043 audio_is_linear_pcm(inputConfig.format)
4044 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004045
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004046 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004047 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004048 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004049 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004050 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004051 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004052 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004053 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4054 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004055 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004056 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004057 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004058
4059 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4060 mix.mDeviceType, mix.mDeviceAddress,
4061 String8(), AUDIO_FORMAT_DEFAULT);
4062 if (device == nullptr) {
4063 res = INVALID_OPERATION;
4064 break;
4065 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004066
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004067 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004068 // First try to find an already opened output supporting the device
4069 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004070 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004071
Eric Laurentc529cf62020-04-17 18:19:10 -07004072 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004073 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004074 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004075 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004076 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004077 } else {
4078 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004079 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004080 }
4081 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004082 // If no output found, try to find a direct output profile supporting the device
4083 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4084 sp<HwModule> module = mHwModules[i];
4085 for (size_t j = 0;
4086 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4087 j++) {
4088 sp<IOProfile> profile = module->getOutputProfiles()[j];
4089 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4090 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4091 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004092 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004093 res = INVALID_OPERATION;
4094 } else {
4095 foundOutput = true;
4096 }
4097 }
4098 }
4099 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004100 if (res != NO_ERROR) {
4101 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004102 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004103 res = INVALID_OPERATION;
4104 break;
4105 } else if (!foundOutput) {
4106 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004107 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004108 res = INVALID_OPERATION;
4109 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004110 } else {
4111 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004112 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004113 }
Eric Laurentc722f302014-12-10 11:21:49 -08004114 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004115 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004116 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004117 if (audio_flags::audio_mix_ownership()) {
4118 // Only unregister mixes that were actually registered to not accidentally unregister
4119 // mixes that already existed previously.
4120 unregisterPolicyMixes(registeredMixes);
4121 registeredMixes.clear();
4122 } else {
4123 unregisterPolicyMixes(mixes);
4124 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004125 } else if (checkOutputs) {
4126 checkForDeviceAndOutputChanges();
4127 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004128 }
4129 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004130}
4131
4132status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4133{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004134 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004135 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004136 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004137 sp<HwModule> rSubmixModule;
4138 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004139 for (const auto& mix : mixes) {
4140 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004141
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004142 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004143 rSubmixModule = mHwModules.getModuleFromName(
4144 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4145 if (rSubmixModule == 0) {
4146 res = INVALID_OPERATION;
4147 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004148 }
4149 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004150
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004151 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004152
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004153 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004154 res = INVALID_OPERATION;
4155 continue;
4156 }
4157
Marvin Ramin0783e202024-03-05 12:45:50 +01004158 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004159 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004160 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4161 status_t currentRes =
4162 setDeviceConnectionStateInt(device,
4163 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4164 address.c_str(),
4165 "remote-submix",
4166 AUDIO_FORMAT_DEFAULT);
4167 if (!audio_flags::audio_mix_ownership()) {
4168 res = currentRes;
4169 }
4170 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004171 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004172 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004173 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004174 }
4175 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004176 }
jiabin5740f082019-08-19 15:08:30 -07004177 rSubmixModule->removeOutputProfile(address.c_str());
4178 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004179
Kevin Rocard153f92d2018-12-18 18:33:28 -08004180 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004181 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004182 res = INVALID_OPERATION;
4183 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004184 } else {
4185 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004186 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004187 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004188 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004189
4190 if (res == NO_ERROR && checkOutputs) {
4191 checkForDeviceAndOutputChanges();
4192 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004193 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004194 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004195}
4196
Marvin Raminbdefaf02023-11-01 09:10:32 +01004197status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4198 if (!audio_flags::audio_mix_test_api()) {
4199 return INVALID_OPERATION;
4200 }
4201
4202 _aidl_return.clear();
4203 _aidl_return.reserve(mPolicyMixes.size());
4204 for (const auto &policyMix: mPolicyMixes) {
4205 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4206 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4207 policyMix->mCbFlags);
4208 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004209 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004210 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004211 }
4212
Vlad Popaa5d73f32024-03-08 16:05:38 -08004213 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004214 return OK;
4215}
4216
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004217status_t AudioPolicyManager::updatePolicyMix(
4218 const AudioMix& mix,
4219 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4220 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4221 if (res == NO_ERROR) {
4222 checkForDeviceAndOutputChanges();
4223 updateCallAndOutputRouting();
4224 }
4225 return res;
4226}
4227
Mikhail Naganov100f0122018-11-29 11:22:16 -08004228void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4229{
4230 size_t i = 0;
4231 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4232 for (const auto& fmt : mManualSurroundFormats) {
4233 if (i++ != 0) dst->append(", ");
4234 std::string sfmt;
4235 FormatConverter::toString(fmt, sfmt);
4236 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4237 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4238 }
4239}
4240
Eric Laurentc529cf62020-04-17 18:19:10 -07004241// Returns true if all devices types match the predicate and are supported by one HW module
4242bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004243 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004244 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004245 const char *context,
4246 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004247 for (size_t i = 0; i < devices.size(); i++) {
4248 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004249 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004250 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004251 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004252 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004253 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004254 return false;
4255 }
4256 }
4257 return true;
4258}
4259
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004260void AudioPolicyManager::changeOutputDevicesMuteState(
4261 const AudioDeviceTypeAddrVector& devices) {
4262 ALOGVV("%s() num devices %zu", __func__, devices.size());
4263
4264 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4265 getSoftwareOutputsForDevices(devices);
4266
4267 for (size_t i = 0; i < outputs.size(); i++) {
4268 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4269 DeviceVector prevDevices = outputDesc->devices();
4270 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4271 }
4272}
4273
4274std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4275 const AudioDeviceTypeAddrVector& devices) const
4276{
4277 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4278 DeviceVector deviceDescriptors;
4279 for (size_t j = 0; j < devices.size(); j++) {
4280 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4281 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4282 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4283 ALOGE("%s: device type %#x address %s not supported or not an output device",
4284 __func__, devices[j].mType, devices[j].getAddress());
4285 continue;
4286 }
4287 deviceDescriptors.add(desc);
4288 }
4289 for (size_t i = 0; i < mOutputs.size(); i++) {
4290 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4291 continue;
4292 }
4293 outputs.push_back(mOutputs.valueAt(i));
4294 }
4295 return outputs;
4296}
4297
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004298status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004299 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004300 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004301 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4302 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004303 }
4304 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004305 if (res != NO_ERROR) {
4306 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4307 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004308 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004309
4310 checkForDeviceAndOutputChanges();
4311 updateCallAndOutputRouting();
4312
4313 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004314}
4315
4316status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4317 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004318 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4319 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004320 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004321 __FUNCTION__, uid);
4322 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004323 }
4324
Eric Laurentc529cf62020-04-17 18:19:10 -07004325 checkForDeviceAndOutputChanges();
4326 updateCallAndOutputRouting();
4327
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004328 return res;
4329}
4330
Eric Laurent2517af32020-11-25 15:31:27 +01004331
jiabin0a488932020-08-07 17:32:40 -07004332status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4333 device_role_t role,
4334 const AudioDeviceTypeAddrVector &devices) {
4335 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4336 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004337
Eric Laurentc529cf62020-04-17 18:19:10 -07004338 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004339 return BAD_VALUE;
4340 }
jiabin0a488932020-08-07 17:32:40 -07004341 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004342 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004343 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4344 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004345 return status;
4346 }
4347
4348 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004349
4350 bool forceVolumeReeval = false;
4351 // FIXME: workaround for truncated touch sounds
4352 // to be removed when the problem is handled by system UI
4353 uint32_t delayMs = 0;
4354 if (strategy == mCommunnicationStrategy) {
4355 forceVolumeReeval = true;
4356 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4357 updateInputRouting();
4358 }
4359 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004360
4361 return NO_ERROR;
4362}
4363
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004364void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4365 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004366{
4367 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004368 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004369 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004370 // Only apply special touch sound delay once
4371 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004372 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004373 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004374 for (size_t i = 0; i < mOutputs.size(); i++) {
4375 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4376 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004377 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4378 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004379 // As done in setDeviceConnectionState, we could also fix default device issue by
4380 // preventing the force re-routing in case of default dev that distinguishes on address.
4381 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004382 bool newDevicesNotEmpty = !newDevices.isEmpty();
4383 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4384 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004385 // If the device is using preferred mixer attributes, the output need to reopen
4386 // with default configuration when the new selected devices are different from
4387 // current routing devices.
4388 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4389 continue;
4390 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304391
jiabin2361ed82024-09-20 17:36:31 +00004392 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4393 newDevicesNotEmpty /*force*/, delayMs,
4394 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4395 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004396 // Only apply special touch sound delay once
4397 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004398 }
4399 if (forceVolumeReeval && !newDevices.isEmpty()) {
4400 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4401 }
4402 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004403 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004404 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004405}
4406
Eric Laurent2517af32020-11-25 15:31:27 +01004407void AudioPolicyManager::updateInputRouting() {
4408 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304409 // Skip for hotword recording as the input device switch
4410 // is handled within sound trigger HAL
4411 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4412 continue;
4413 }
Eric Laurent2517af32020-11-25 15:31:27 +01004414 auto newDevice = getNewInputDevice(activeDesc);
4415 // Force new input selection if the new device can not be reached via current input
4416 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4417 setInputDevice(activeDesc->mIoHandle, newDevice);
4418 } else {
4419 closeInput(activeDesc->mIoHandle);
4420 }
4421 }
4422}
4423
Paul Wang5d7cdb52022-11-22 09:45:06 +00004424status_t
4425AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4426 device_role_t role,
4427 const AudioDeviceTypeAddrVector &devices) {
4428 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4429 dumpAudioDeviceTypeAddrVector(devices).c_str());
4430
Eric Laurent78fedbf2023-03-09 14:40:44 +01004431 if (!areAllDevicesSupported(
4432 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004433 return BAD_VALUE;
4434 }
4435 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4436 if (status != NO_ERROR) {
4437 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4438 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4439 return status;
4440 }
4441
4442 checkForDeviceAndOutputChanges();
4443
4444 bool forceVolumeReeval = false;
4445 // TODO(b/263479999): workaround for truncated touch sounds
4446 // to be removed when the problem is handled by system UI
4447 uint32_t delayMs = 0;
4448 if (strategy == mCommunnicationStrategy) {
4449 forceVolumeReeval = true;
4450 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4451 updateInputRouting();
4452 }
4453 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4454
4455 return NO_ERROR;
4456}
4457
4458status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4459 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004460{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004461 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004462
Paul Wang5d7cdb52022-11-22 09:45:06 +00004463 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004464 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004465 ALOGW_IF(status != NAME_NOT_FOUND,
4466 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004467 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004468 return status;
4469 }
4470
4471 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004472
4473 bool forceVolumeReeval = false;
4474 // FIXME: workaround for truncated touch sounds
4475 // to be removed when the problem is handled by system UI
4476 uint32_t delayMs = 0;
4477 if (strategy == mCommunnicationStrategy) {
4478 forceVolumeReeval = true;
4479 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4480 updateInputRouting();
4481 }
4482 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004483
4484 return NO_ERROR;
4485}
4486
jiabin0a488932020-08-07 17:32:40 -07004487status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4488 device_role_t role,
4489 AudioDeviceTypeAddrVector &devices) {
4490 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004491}
4492
Jiabin Huang3b98d322020-09-03 17:54:16 +00004493status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4494 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4495 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4496 dumpAudioDeviceTypeAddrVector(devices).c_str());
4497
Mikhail Naganov55773032020-10-01 15:08:13 -07004498 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004499 return BAD_VALUE;
4500 }
4501 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4502 ALOGW_IF(status != NO_ERROR,
4503 "Engine could not set preferred devices %s for audio source %d role %d",
4504 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4505
4506 return status;
4507}
4508
4509status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4510 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4511 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4512 dumpAudioDeviceTypeAddrVector(devices).c_str());
4513
Mikhail Naganov55773032020-10-01 15:08:13 -07004514 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004515 return BAD_VALUE;
4516 }
4517 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4518 ALOGW_IF(status != NO_ERROR,
4519 "Engine could not add preferred devices %s for audio source %d role %d",
4520 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4521
Eric Laurent2517af32020-11-25 15:31:27 +01004522 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004523 return status;
4524}
4525
4526status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4527 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4528{
4529 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4530 dumpAudioDeviceTypeAddrVector(devices).c_str());
4531
Eric Laurent78fedbf2023-03-09 14:40:44 +01004532 if (!areAllDevicesSupported(
4533 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004534 return BAD_VALUE;
4535 }
4536
4537 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4538 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004539 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004540 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004541 if (status == NO_ERROR) {
4542 updateInputRouting();
4543 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004544 return status;
4545}
4546
4547status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4548 device_role_t role) {
4549 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4550
4551 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004552 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004553 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004554 if (status == NO_ERROR) {
4555 updateInputRouting();
4556 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004557 return status;
4558}
4559
4560status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4561 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4562 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4563}
4564
Oscar Azucena90e77632019-11-27 17:12:28 -08004565status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004566 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004567 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004568 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4569 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004570 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004571 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4572 if (status != NO_ERROR) {
4573 ALOGE("%s() could not set device affinity for userId %d",
4574 __FUNCTION__, userId);
4575 return status;
4576 }
4577
4578 // reevaluate outputs for all devices
4579 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004580 changeOutputDevicesMuteState(devices);
4581 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4582 true /* skipDelays */);
4583 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004584
4585 return NO_ERROR;
4586}
4587
4588status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004589 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004590 AudioDeviceTypeAddrVector devices;
4591 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004592 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4593 if (status != NO_ERROR) {
4594 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4595 __FUNCTION__, userId);
4596 return status;
4597 }
4598
4599 // reevaluate outputs for all devices
4600 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004601 changeOutputDevicesMuteState(devices);
4602 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4603 true /* skipDelays */);
4604 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004605
4606 return NO_ERROR;
4607}
4608
Andy Hungc29d82b2018-10-05 12:23:17 -07004609void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004610{
Andy Hungc29d82b2018-10-05 12:23:17 -07004611 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004612 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004613 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004614 std::string stateLiteral;
4615 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004616 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004617 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4618 "communications", "media", "record", "dock", "system",
4619 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4620 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4621 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004622 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4623 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4624 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4625 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4626 dst->append(" (MANUAL: ");
4627 dumpManualSurroundFormats(dst);
4628 dst->append(")");
4629 }
4630 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004631 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004632 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4633 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004634 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004635 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004636
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004637 dst->append("\n");
4638 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4639 dst->append("\n");
4640 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004641 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004642 mOutputs.dump(dst);
4643 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004644 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004645 mAudioPatches.dump(dst);
4646 mPolicyMixes.dump(dst);
4647 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004648
Kevin Rocardb99cc752019-03-21 20:52:24 -07004649 dst->appendFormat(" AllowedCapturePolicies:\n");
4650 for (auto& policy : mAllowedCapturePolicies) {
4651 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4652 }
4653
jiabina84c3d32022-12-02 18:59:55 +00004654 dst->appendFormat(" Preferred mixer audio configuration:\n");
4655 for (const auto it : mPreferredMixerAttrInfos) {
4656 dst->appendFormat(" - device port id: %d\n", it.first);
4657 for (const auto preferredMixerInfoIt : it.second) {
4658 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4659 preferredMixerInfoIt.second->dump(dst);
4660 }
4661 }
4662
François Gaffiec005e562018-11-06 15:04:49 +01004663 dst->appendFormat("\nPolicy Engine dump:\n");
4664 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004665
4666 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4667 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4668 dst->appendFormat(" - device type: %s, driving stream %d\n",
4669 dumpDeviceTypes({it.first}).c_str(),
4670 mEngine->getVolumeGroupForAttributes(it.second));
4671 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004672}
4673
4674status_t AudioPolicyManager::dump(int fd)
4675{
4676 String8 result;
4677 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004678 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004679 return NO_ERROR;
4680}
4681
Kevin Rocardb99cc752019-03-21 20:52:24 -07004682status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4683{
4684 mAllowedCapturePolicies[uid] = capturePolicy;
4685 return NO_ERROR;
4686}
4687
Eric Laurente552edb2014-03-10 17:42:56 -07004688// This function checks for the parameters which can be offloaded.
4689// This can be enhanced depending on the capability of the DSP and policy
4690// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004691audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004692{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004693 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004694 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004695 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004696 offloadInfo.format,
4697 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4698 offloadInfo.has_video);
4699
jiabin2b9d5a12021-12-10 01:06:29 +00004700 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004701 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004702 }
4703
4704 // See if there is a profile to support this.
4705 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004706 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004707 offloadInfo.sample_rate,
4708 offloadInfo.format,
4709 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004710 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4711 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004712 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4713 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4714 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004715 if (profile == nullptr) {
4716 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4717 }
4718 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4719 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4720 }
4721 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004722}
4723
Michael Chana94fbb22018-04-24 14:31:19 +10004724bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4725 const audio_attributes_t& attributes) {
4726 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004727 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004728 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4729 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004730 config.sample_rate,
4731 config.format,
4732 config.channel_mask,
4733 output_flags,
4734 true /* directOnly */);
4735 ALOGV("%s() profile %sfound with name: %s, "
4736 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4737 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004738 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004739 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004740
4741 // also try the MSD module if compatible profile not found
4742 if (profile == nullptr) {
4743 profile = getMsdProfileForOutput(outputDevices,
4744 config.sample_rate,
4745 config.format,
4746 config.channel_mask,
4747 output_flags,
4748 true /* directOnly */);
4749 ALOGV("%s() MSD profile %sfound with name: %s, "
4750 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4751 __FUNCTION__, profile != 0 ? "" : "NOT ",
4752 (profile != 0 ? profile->getTagName().c_str() : "null"),
4753 config.sample_rate, config.format, config.channel_mask, output_flags);
4754 }
4755 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004756}
4757
jiabin2b9d5a12021-12-10 01:06:29 +00004758bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4759 bool durationIgnored) {
4760 if (mMasterMono) {
4761 return false; // no offloading if mono is set.
4762 }
4763
4764 // Check if offload has been disabled
4765 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4766 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4767 return false;
4768 }
4769
4770 // Check if stream type is music, then only allow offload as of now.
4771 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4772 {
4773 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4774 return false;
4775 }
4776
4777 //TODO: enable audio offloading with video when ready
4778 const bool allowOffloadWithVideo =
4779 property_get_bool("audio.offload.video", false /* default_value */);
4780 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4781 ALOGV("%s: has_video == true, returning false", __func__);
4782 return false;
4783 }
4784
4785 //If duration is less than minimum value defined in property, return false
4786 const int min_duration_secs = property_get_int32(
4787 "audio.offload.min.duration.secs", -1 /* default_value */);
4788 if (!durationIgnored) {
4789 if (min_duration_secs >= 0) {
4790 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4791 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4792 __func__, min_duration_secs);
4793 return false;
4794 }
4795 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4796 ALOGV("%s: Offload denied by duration < default min(=%u)",
4797 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4798 return false;
4799 }
4800 }
4801
4802 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4803 // creating an offloaded track and tearing it down immediately after start when audioflinger
4804 // detects there is an active non offloadable effect.
4805 // FIXME: We should check the audio session here but we do not have it in this context.
4806 // This may prevent offloading in rare situations where effects are left active by apps
4807 // in the background.
4808 if (mEffects.isNonOffloadableEffectEnabled()) {
4809 return false;
4810 }
4811
4812 return true;
4813}
4814
4815audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4816 const audio_config_t *config) {
4817 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4818 offloadInfo.format = config->format;
4819 offloadInfo.sample_rate = config->sample_rate;
4820 offloadInfo.channel_mask = config->channel_mask;
4821 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4822 offloadInfo.has_video = false;
4823 offloadInfo.is_streaming = false;
4824 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4825
4826 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4827 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4828 audio_flags_to_audio_output_flags(attr->flags, &flags);
4829 // only retain flags that will drive compressed offload or passthrough
4830 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4831 if (offloadPossible) {
4832 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4833 }
4834 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4835
Dorin Drimusfae3c642022-03-17 18:36:30 +01004836 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004837 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004838 DeviceVector outputDevices = engineOutputDevices;
4839 // the MSD module checks for different conditions and output devices
4840 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4841 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4842 continue;
4843 }
4844 outputDevices = getMsdAudioOutDevices();
4845 }
jiabin2b9d5a12021-12-10 01:06:29 +00004846 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004847 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004848 config->sample_rate, nullptr /*updatedSamplingRate*/,
4849 config->format, nullptr /*updatedFormat*/,
4850 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004851 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004852 continue;
4853 }
4854 // reject profiles not corresponding to a device currently available
4855 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4856 continue;
4857 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004858 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4859 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004860 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004861 != AUDIO_DIRECT_NOT_SUPPORTED) {
4862 // Already reports offload gapless supported. No need to report offload support.
4863 continue;
4864 }
4865 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4866 != AUDIO_OUTPUT_FLAG_NONE) {
4867 // If offload gapless is reported, no need to report offload support.
4868 directMode = (audio_direct_mode_t) ((directMode &
4869 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4870 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4871 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004872 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004873 }
4874 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004875 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004876 }
4877 }
4878 }
4879 return directMode;
4880}
4881
Dorin Drimusf2196d82022-01-03 12:11:18 +01004882status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4883 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004884 if (mEffects.isNonOffloadableEffectEnabled()) {
4885 return OK;
4886 }
jiabinf1c73972022-04-14 16:28:52 -07004887 DeviceVector devices;
4888 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004889 if (status != OK) {
4890 return status;
4891 }
4892 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4893 if (devices.empty()) {
4894 return OK; // no output devices for the attributes
4895 }
jiabinf1c73972022-04-14 16:28:52 -07004896 return getProfilesForDevices(devices, audioProfilesVector,
4897 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004898}
4899
jiabina84c3d32022-12-02 18:59:55 +00004900status_t AudioPolicyManager::getSupportedMixerAttributes(
4901 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4902 ALOGV("%s, portId=%d", __func__, portId);
4903 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4904 if (deviceDescriptor == nullptr) {
4905 ALOGE("%s the requested device is currently unavailable", __func__);
4906 return BAD_VALUE;
4907 }
jiabin96daffc2023-05-11 17:51:55 +00004908 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4909 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4910 deviceDescriptor->type());
4911 return BAD_VALUE;
4912 }
jiabina84c3d32022-12-02 18:59:55 +00004913 for (const auto& hwModule : mHwModules) {
4914 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4915 if (curProfile->supportsDevice(deviceDescriptor)) {
4916 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4917 }
4918 }
4919 }
4920 return NO_ERROR;
4921}
4922
4923status_t AudioPolicyManager::setPreferredMixerAttributes(
4924 const audio_attributes_t *attr,
4925 audio_port_handle_t portId,
4926 uid_t uid,
4927 const audio_mixer_attributes_t *mixerAttributes) {
4928 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4929 "mixerBehavior=%d}, uid=%d, portId=%u",
4930 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4931 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4932 mixerAttributes->mixer_behavior, uid, portId);
4933 if (attr->usage != AUDIO_USAGE_MEDIA) {
4934 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4935 return BAD_VALUE;
4936 }
4937 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4938 if (deviceDescriptor == nullptr) {
4939 ALOGE("%s the requested device is currently unavailable", __func__);
4940 return BAD_VALUE;
4941 }
4942 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4943 ALOGE("%s(%d), type=%d, is not a usb output device",
4944 __func__, portId, deviceDescriptor->type());
4945 return BAD_VALUE;
4946 }
4947
4948 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4949 audio_flags_to_audio_output_flags(attr->flags, &flags);
4950 flags = (audio_output_flags_t) (flags |
4951 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4952 sp<IOProfile> profile = nullptr;
4953 DeviceVector devices(deviceDescriptor);
4954 for (const auto& hwModule : mHwModules) {
4955 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4956 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004957 && curProfile->getCompatibilityScore(
4958 devices,
4959 mixerAttributes->config.sample_rate,
4960 nullptr /*updatedSamplingRate*/,
4961 mixerAttributes->config.format,
4962 nullptr /*updatedFormat*/,
4963 mixerAttributes->config.channel_mask,
4964 nullptr /*updatedChannelMask*/,
4965 flags,
4966 false /*exactMatchRequiredForInputFlags*/)
4967 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004968 profile = curProfile;
4969 break;
4970 }
4971 }
4972 }
4973 if (profile == nullptr) {
4974 ALOGE("%s, there is no compatible profile found", __func__);
4975 return BAD_VALUE;
4976 }
4977
4978 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4979 sp<PreferredMixerAttributesInfo>::make(
4980 uid, portId, profile, flags, *mixerAttributes);
4981 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4982 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4983
4984 // If 1) there is any client from the preferred mixer configuration owner that is currently
4985 // active and matches the strategy and 2) current output is on the preferred device and the
4986 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4987 // configuration.
4988 std::vector<audio_io_handle_t> outputsToReopen;
4989 for (size_t i = 0; i < mOutputs.size(); i++) {
4990 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004991 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4992 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004993 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004994 } else {
4995 for (const auto &client: output->getActiveClients()) {
4996 if (client->uid() == uid && client->strategy() == strategy) {
4997 client->setIsInvalid();
4998 outputsToReopen.push_back(output->mIoHandle);
4999 }
jiabina84c3d32022-12-02 18:59:55 +00005000 }
5001 }
5002 }
5003 }
5004 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5005 config.sample_rate = mixerAttributes->config.sample_rate;
5006 config.channel_mask = mixerAttributes->config.channel_mask;
5007 config.format = mixerAttributes->config.format;
5008 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005009 sp<SwAudioOutputDescriptor> desc =
5010 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5011 if (desc == nullptr) {
5012 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5013 continue;
5014 }
jiabin220eea12024-05-17 17:55:20 +00005015 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005016 }
5017
5018 return NO_ERROR;
5019}
5020
5021sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005022 audio_port_handle_t devicePortId,
5023 product_strategy_t strategy,
5024 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005025 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5026 if (it == mPreferredMixerAttrInfos.end()) {
5027 return nullptr;
5028 }
jiabind9a58d32023-06-01 17:57:30 +00005029 if (activeBitPerfectPreferred) {
5030 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005031 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005032 return info;
5033 }
5034 }
jiabina84c3d32022-12-02 18:59:55 +00005035 }
jiabind9a58d32023-06-01 17:57:30 +00005036 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5037 return strategyMatchedMixerAttrInfoIt == it->second.end()
5038 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005039}
5040
5041status_t AudioPolicyManager::getPreferredMixerAttributes(
5042 const audio_attributes_t *attr,
5043 audio_port_handle_t portId,
5044 audio_mixer_attributes_t* mixerAttributes) {
5045 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5046 portId, mEngine->getProductStrategyForAttributes(*attr));
5047 if (info == nullptr) {
5048 return NAME_NOT_FOUND;
5049 }
5050 *mixerAttributes = info->getMixerAttributes();
5051 return NO_ERROR;
5052}
5053
5054status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5055 audio_port_handle_t portId,
5056 uid_t uid) {
5057 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5058 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5059 if (preferredMixerAttrInfo == nullptr) {
5060 return NAME_NOT_FOUND;
5061 }
5062 if (preferredMixerAttrInfo->getUid() != uid) {
5063 ALOGE("%s, requested uid=%d, owned uid=%d",
5064 __func__, uid, preferredMixerAttrInfo->getUid());
5065 return PERMISSION_DENIED;
5066 }
5067 mPreferredMixerAttrInfos[portId].erase(strategy);
5068 if (mPreferredMixerAttrInfos[portId].empty()) {
5069 mPreferredMixerAttrInfos.erase(portId);
5070 }
5071
5072 // Reconfig existing output
5073 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5074 for (size_t i = 0; i < mOutputs.size(); i++) {
5075 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5076 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5077 }
5078 }
5079 for (const auto output : potentialOutputsToReopen) {
5080 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5081 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5082 preferredMixerAttrInfo->getFlags())) {
5083 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5084 }
5085 }
5086 return NO_ERROR;
5087}
5088
Eric Laurent6a94d692014-05-20 11:18:06 -07005089status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5090 audio_port_type_t type,
5091 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005092 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005093 unsigned int *generation)
5094{
jiabin19cdba52020-11-24 11:28:58 -08005095 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5096 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005097 return BAD_VALUE;
5098 }
5099 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005100 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005101 *num_ports = 0;
5102 }
5103
5104 size_t portsWritten = 0;
5105 size_t portsMax = *num_ports;
5106 *num_ports = 0;
5107 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005108 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5109 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005111 for (const auto& dev : mAvailableOutputDevices) {
5112 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005113 continue;
5114 }
5115 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005116 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005117 }
5118 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005120 }
5121 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005122 for (const auto& dev : mAvailableInputDevices) {
5123 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005124 continue;
5125 }
5126 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005127 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005128 }
5129 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005130 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005131 }
5132 }
5133 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5134 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5135 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5136 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5137 }
5138 *num_ports += mInputs.size();
5139 }
5140 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005141 size_t numOutputs = 0;
5142 for (size_t i = 0; i < mOutputs.size(); i++) {
5143 if (!mOutputs[i]->isDuplicated()) {
5144 numOutputs++;
5145 if (portsWritten < portsMax) {
5146 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5147 }
5148 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005149 }
Eric Laurent84c70242014-06-23 08:46:27 -07005150 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005151 }
5152 }
jiabina84c3d32022-12-02 18:59:55 +00005153
Eric Laurent6a94d692014-05-20 11:18:06 -07005154 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005155 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 return NO_ERROR;
5157}
5158
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005159status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5160 std::vector<media::AudioPortFw>* _aidl_return) {
5161 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5162 audio_port_v7 port;
5163 dev->toAudioPort(&port);
5164 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5165 _aidl_return->push_back(std::move(aidlPort));
5166 return OK;
5167 };
5168
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005169 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005170 for (const auto& dev : module->getDeclaredDevices()) {
5171 if (role == media::AudioPortRole::NONE ||
5172 ((role == media::AudioPortRole::SOURCE)
5173 == audio_is_input_device(dev->type()))) {
5174 RETURN_STATUS_IF_ERROR(pushPort(dev));
5175 }
5176 }
5177 }
5178 return OK;
5179}
5180
jiabin19cdba52020-11-24 11:28:58 -08005181status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005182{
Eric Laurent99fcae42018-05-17 16:59:18 -07005183 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5184 return BAD_VALUE;
5185 }
5186 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5187 if (dev != 0) {
5188 dev->toAudioPort(port);
5189 return NO_ERROR;
5190 }
5191 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5192 if (dev != 0) {
5193 dev->toAudioPort(port);
5194 return NO_ERROR;
5195 }
5196 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5197 if (out != 0) {
5198 out->toAudioPort(port);
5199 return NO_ERROR;
5200 }
5201 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5202 if (in != 0) {
5203 in->toAudioPort(port);
5204 return NO_ERROR;
5205 }
5206 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005207}
5208
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005209status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5210 audio_patch_handle_t *handle,
5211 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005212{
François Gaffieafd4cea2019-11-18 15:50:22 +01005213 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 if (handle == NULL || patch == NULL) {
5215 return BAD_VALUE;
5216 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005218 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005219 return BAD_VALUE;
5220 }
5221 // only one source per audio patch supported for now
5222 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 return INVALID_OPERATION;
5224 }
Eric Laurent874c42872014-08-08 15:13:39 -07005225 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 return INVALID_OPERATION;
5227 }
Eric Laurent874c42872014-08-08 15:13:39 -07005228 for (size_t i = 0; i < patch->num_sinks; i++) {
5229 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5230 return INVALID_OPERATION;
5231 }
5232 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005233
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005234 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5235 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5236 if (srcDevice == nullptr || sinkDevice == nullptr) {
5237 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5238 return BAD_VALUE;
5239 }
5240 ALOGV("%s between source %s and sink %s", __func__,
5241 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5242 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5243 // Default attributes, default volume priority, not to infer with non raw audio patches.
5244 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5245 const struct audio_port_config *source = &patch->sources[0];
5246 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005247 new SourceClientDescriptor(
5248 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5249 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005250 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005251 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005252
5253 status_t status =
5254 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5255
5256 if (status != NO_ERROR) {
5257 return INVALID_OPERATION;
5258 }
5259 mAudioSources.add(portId, sourceDesc);
5260 return NO_ERROR;
5261}
5262
5263status_t AudioPolicyManager::connectAudioSourceToSink(
5264 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5265 const struct audio_patch *patch,
5266 audio_patch_handle_t &handle,
5267 uid_t uid, uint32_t delayMs)
5268{
5269 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5270 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5271 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5272 return INVALID_OPERATION;
5273 }
5274 sourceDesc->connect(handle, sinkDevice);
5275 if (isMsdPatch(handle)) {
5276 return NO_ERROR;
5277 }
5278 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5279 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5280 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5281 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5282 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5283 goto FailurePatchAdded;
5284 }
5285 status = swOutput->start();
5286 if (status != NO_ERROR) {
5287 goto FailureSourceAdded;
5288 }
5289 swOutput->addClient(sourceDesc);
5290 status = startSource(swOutput, sourceDesc, &delayMs);
5291 if (status != NO_ERROR) {
5292 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5293 goto FailureSourceActive;
5294 }
5295 if (delayMs != 0) {
5296 usleep(delayMs * 1000);
5297 }
5298 return NO_ERROR;
5299
5300FailureSourceActive:
5301 swOutput->stop();
5302 releaseOutput(sourceDesc->portId());
5303FailureSourceAdded:
5304 sourceDesc->setSwOutput(nullptr);
5305FailurePatchAdded:
5306 releaseAudioPatchInternal(handle);
5307 return INVALID_OPERATION;
5308}
5309
5310status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5311 audio_patch_handle_t *handle,
5312 uid_t uid, uint32_t delayMs,
5313 const sp<SourceClientDescriptor>& sourceDesc)
5314{
5315 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 sp<AudioPatch> patchDesc;
5317 ssize_t index = mAudioPatches.indexOfKey(*handle);
5318
François Gaffieafd4cea2019-11-18 15:50:22 +01005319 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5320 patch->sources[0].role,
5321 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005322#if LOG_NDEBUG == 0
5323 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005324 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5325 patch->sinks[i].role,
5326 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005327 }
5328#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005329
5330 if (index >= 0) {
5331 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005332 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5333 __func__, mUidCached, patchDesc->getUid(), uid);
5334 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 return INVALID_OPERATION;
5336 }
5337 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005338 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 }
5340
5341 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005342 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 return BAD_VALUE;
5346 }
Eric Laurent84c70242014-06-23 08:46:27 -07005347 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5348 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005349 if (patchDesc != 0) {
5350 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005351 ALOGV("%s source id differs for patch current id %d new id %d",
5352 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005353 return BAD_VALUE;
5354 }
5355 }
Eric Laurent874c42872014-08-08 15:13:39 -07005356 DeviceVector devices;
5357 for (size_t i = 0; i < patch->num_sinks; i++) {
5358 // Only support mix to devices connection
5359 // TODO add support for mix to mix connection
5360 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005361 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005362 return INVALID_OPERATION;
5363 }
5364 sp<DeviceDescriptor> devDesc =
5365 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5366 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005367 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005368 return BAD_VALUE;
5369 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005370
jiabin66acc432024-02-06 00:57:36 +00005371 if (outputDesc->mProfile->getCompatibilityScore(
5372 DeviceVector(devDesc),
5373 patch->sources[0].sample_rate,
5374 nullptr, // updatedSamplingRate
5375 patch->sources[0].format,
5376 nullptr, // updatedFormat
5377 patch->sources[0].channel_mask,
5378 nullptr, // updatedChannelMask
5379 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005380 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005381 return INVALID_OPERATION;
5382 }
5383 devices.add(devDesc);
5384 }
5385 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005386 return INVALID_OPERATION;
5387 }
Eric Laurent874c42872014-08-08 15:13:39 -07005388
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005390 ALOGV("%s setting device %s on output %d",
5391 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305392 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005393 index = mAudioPatches.indexOfKey(*handle);
5394 if (index >= 0) {
5395 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005396 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 }
5398 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005399 patchDesc->setUid(uid);
5400 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005401 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005402 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005403 return INVALID_OPERATION;
5404 }
5405 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5406 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5407 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005408 // only one sink supported when connecting an input device to a mix
5409 if (patch->num_sinks > 1) {
5410 return INVALID_OPERATION;
5411 }
François Gaffie53615e22015-03-19 09:24:12 +01005412 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 if (inputDesc == NULL) {
5414 return BAD_VALUE;
5415 }
5416 if (patchDesc != 0) {
5417 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5418 return BAD_VALUE;
5419 }
5420 }
François Gaffie11d30102018-11-02 16:09:09 +01005421 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005422 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005423 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005424 return BAD_VALUE;
5425 }
5426
jiabin66acc432024-02-06 00:57:36 +00005427 if (inputDesc->mProfile->getCompatibilityScore(
5428 DeviceVector(device),
5429 patch->sinks[0].sample_rate,
5430 nullptr, /*updatedSampleRate*/
5431 patch->sinks[0].format,
5432 nullptr, /*updatedFormat*/
5433 patch->sinks[0].channel_mask,
5434 nullptr, /*updatedChannelMask*/
5435 // FIXME for the parameter type,
5436 // and the NONE
5437 (audio_output_flags_t)
5438 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005439 return INVALID_OPERATION;
5440 }
5441 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005442 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005443 device->toString().c_str(), inputDesc->mIoHandle);
5444 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005445 index = mAudioPatches.indexOfKey(*handle);
5446 if (index >= 0) {
5447 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005448 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005449 }
5450 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005451 patchDesc->setUid(uid);
5452 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005453 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005454 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 return INVALID_OPERATION;
5456 }
5457 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5458 // device to device connection
5459 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005460 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 return BAD_VALUE;
5462 }
5463 }
François Gaffie11d30102018-11-02 16:09:09 +01005464 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005466 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005467 return BAD_VALUE;
5468 }
Eric Laurent874c42872014-08-08 15:13:39 -07005469
Eric Laurent6a94d692014-05-20 11:18:06 -07005470 //update source and sink with our own data as the data passed in the patch may
5471 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005472 PatchBuilder patchBuilder;
5473 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005474
5475 // if first sink is to MSD, establish single MSD patch
5476 if (getMsdAudioOutDevices().contains(
5477 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5478 ALOGV("%s patching to MSD", __FUNCTION__);
5479 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5480 goto installPatch;
5481 }
5482
François Gaffieafd4cea2019-11-18 15:50:22 +01005483 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5484 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005485
Eric Laurent874c42872014-08-08 15:13:39 -07005486 for (size_t i = 0; i < patch->num_sinks; i++) {
5487 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005488 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005489 return INVALID_OPERATION;
5490 }
François Gaffie11d30102018-11-02 16:09:09 +01005491 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005492 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005493 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005494 return BAD_VALUE;
5495 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005496 audio_port_config sinkPortConfig = {};
5497 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5498 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005499
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005500 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5501 // volume management purpose (tracking activity)
5502 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5503 // in config XML to reach the sink so that is can be declared as available.
5504 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005505 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005506 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005507 // take care of dynamic routing for SwOutput selection,
5508 audio_attributes_t attributes = sourceDesc->attributes();
5509 audio_stream_type_t stream = sourceDesc->stream();
5510 audio_attributes_t resultAttr;
5511 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5512 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005513 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5514 config.channel_mask =
5515 (audio_channel_mask_get_representation(sourceMask)
5516 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5517 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005518 config.format = sourceDesc->config().format;
5519 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5520 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5521 bool isRequestedDeviceForExclusiveUse = false;
5522 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005523 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005524 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005525 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5526 &stream, sourceDesc->uid(), &config, &flags,
5527 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005528 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005529 if (output == AUDIO_IO_HANDLE_NONE) {
5530 ALOGV("%s no output for device %s",
5531 __FUNCTION__, sinkDevice->toString().c_str());
5532 return INVALID_OPERATION;
5533 }
5534 outputDesc = mOutputs.valueFor(output);
5535 if (outputDesc->isDuplicated()) {
5536 ALOGE("%s output is duplicated", __func__);
5537 return INVALID_OPERATION;
5538 }
François Gaffie7e39df22022-04-26 12:48:49 +02005539 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5540 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005541 } else {
5542 // Same for "raw patches" aka created from createAudioPatch API
5543 SortedVector<audio_io_handle_t> outputs =
5544 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5545 // if the sink device is reachable via an opened output stream, request to
5546 // go via this output stream by adding a second source to the patch
5547 // description
5548 output = selectOutput(outputs);
5549 if (output == AUDIO_IO_HANDLE_NONE) {
5550 ALOGE("%s no output available for internal patch sink", __func__);
5551 return INVALID_OPERATION;
5552 }
5553 outputDesc = mOutputs.valueFor(output);
5554 if (outputDesc->isDuplicated()) {
5555 ALOGV("%s output for device %s is duplicated",
5556 __func__, sinkDevice->toString().c_str());
5557 return INVALID_OPERATION;
5558 }
François Gaffie7e39df22022-04-26 12:48:49 +02005559 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005560 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005561 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005562 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005563 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005564 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005565 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5566 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005567 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5568 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005570 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005571 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005572 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005573 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005574 return INVALID_OPERATION;
5575 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005576 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005577 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005578 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005579 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005580 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005581 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005582 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005583 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5584 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005585 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005586 }
Eric Laurent83b88082014-06-20 18:31:16 -07005587 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005588 }
5589 // TODO: check from routing capabilities in config file and other conflicting patches
5590
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005591installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005592 status_t status = installPatch(
5593 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005594 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005595 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005596 return INVALID_OPERATION;
5597 }
5598 } else {
5599 return BAD_VALUE;
5600 }
5601 } else {
5602 return BAD_VALUE;
5603 }
5604 return NO_ERROR;
5605}
5606
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005607status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005608{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005609 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005610 ssize_t index = mAudioPatches.indexOfKey(handle);
5611
5612 if (index < 0) {
5613 return BAD_VALUE;
5614 }
5615 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005616 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5617 __func__, mUidCached, patchDesc->getUid(), uid);
5618 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005619 return INVALID_OPERATION;
5620 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005621 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5622 for (size_t i = 0; i < mAudioSources.size(); i++) {
5623 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5624 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5625 portId = sourceDesc->portId();
5626 break;
5627 }
5628 }
5629 return portId != AUDIO_PORT_HANDLE_NONE ?
5630 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005631}
Eric Laurent6a94d692014-05-20 11:18:06 -07005632
François Gaffieafd4cea2019-11-18 15:50:22 +01005633status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005634 uint32_t delayMs,
5635 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005636{
5637 ALOGV("%s patch %d", __func__, handle);
5638 if (mAudioPatches.indexOfKey(handle) < 0) {
5639 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5640 return BAD_VALUE;
5641 }
5642 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005643 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005644 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005645 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005646 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005647 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005648 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005649 return BAD_VALUE;
5650 }
5651
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305652 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005653 getNewOutputDevices(outputDesc, true /*fromCache*/),
5654 true,
5655 0,
5656 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005657 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5658 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005659 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005660 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005661 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005662 return BAD_VALUE;
5663 }
5664 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005665 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005666 true,
5667 NULL);
5668 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005669 status_t status =
5670 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5671 ALOGV("%s patch panel returned %d patchHandle %d",
5672 __func__, status, patchDesc->getAfHandle());
5673 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005674 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005675 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005676 // SW or HW Bridge
5677 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5678 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005679 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005680 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5681 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5682 outputDesc = sourceDesc->swOutput().promote();
5683 }
5684 if (outputDesc == nullptr) {
5685 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5686 // releaseOutput has already called closeOutput in case of direct output
5687 return NO_ERROR;
5688 }
François Gaffie7e39df22022-04-26 12:48:49 +02005689 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005690 // While using a HwBridge, force reconsidering device only if not reusing an existing
5691 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005692 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005693 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5694 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5695 // Reconsider device only for cases:
5696 // 1 / Active Output
5697 // 2 / Inactive Output previously hosting HwBridge
5698 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5699 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5700 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305701 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005702 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5703 outputDesc->devices(),
5704 force,
5705 0,
5706 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005707 } else {
5708 return BAD_VALUE;
5709 }
5710 } else {
5711 return BAD_VALUE;
5712 }
5713 return NO_ERROR;
5714}
5715
5716status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5717 struct audio_patch *patches,
5718 unsigned int *generation)
5719{
François Gaffie53615e22015-03-19 09:24:12 +01005720 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005721 return BAD_VALUE;
5722 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005723 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005724 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005725}
5726
Eric Laurente1715a42014-05-20 11:30:42 -07005727status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005728{
Eric Laurente1715a42014-05-20 11:30:42 -07005729 ALOGV("setAudioPortConfig()");
5730
5731 if (config == NULL) {
5732 return BAD_VALUE;
5733 }
5734 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5735 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005736 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5737 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005738 }
5739
Eric Laurenta121f902014-06-03 13:32:54 -07005740 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005741 if (config->type == AUDIO_PORT_TYPE_MIX) {
5742 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005743 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005744 if (outputDesc == NULL) {
5745 return BAD_VALUE;
5746 }
Eric Laurent84c70242014-06-23 08:46:27 -07005747 ALOG_ASSERT(!outputDesc->isDuplicated(),
5748 "setAudioPortConfig() called on duplicated output %d",
5749 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005750 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005751 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005752 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005753 if (inputDesc == NULL) {
5754 return BAD_VALUE;
5755 }
Eric Laurenta121f902014-06-03 13:32:54 -07005756 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005757 } else {
5758 return BAD_VALUE;
5759 }
5760 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5761 sp<DeviceDescriptor> deviceDesc;
5762 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5763 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5764 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5765 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5766 } else {
5767 return BAD_VALUE;
5768 }
5769 if (deviceDesc == NULL) {
5770 return BAD_VALUE;
5771 }
Eric Laurenta121f902014-06-03 13:32:54 -07005772 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005773 } else {
5774 return BAD_VALUE;
5775 }
5776
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005777 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005778 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5779 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005780 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005781 audioPortConfig->toAudioPortConfig(&newConfig, config);
5782 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005783 }
Eric Laurenta121f902014-06-03 13:32:54 -07005784 if (status != NO_ERROR) {
5785 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005786 }
Eric Laurente1715a42014-05-20 11:30:42 -07005787
5788 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005789}
5790
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005791void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5792{
Eric Laurentd60560a2015-04-10 11:31:20 -07005793 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005794 clearAudioPatches(uid);
5795 clearSessionRoutes(uid);
5796}
5797
Eric Laurent6a94d692014-05-20 11:18:06 -07005798void AudioPolicyManager::clearAudioPatches(uid_t uid)
5799{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005800 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005801 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005802 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005803 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005804 }
5805 }
5806}
5807
François Gaffiec005e562018-11-06 15:04:49 +01005808void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005809{
François Gaffiec005e562018-11-06 15:04:49 +01005810 // Take the first attributes following the product strategy as it is used to retrieve the routed
5811 // device. All attributes wihin a strategy follows the same "routing strategy"
5812 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5813 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005814 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005815 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005816 for (size_t j = 0; j < mOutputs.size(); j++) {
5817 if (mOutputs.keyAt(j) == ouptutToSkip) {
5818 continue;
5819 }
5820 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005821 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005822 continue;
5823 }
5824 // If the default device for this strategy is on another output mix,
5825 // invalidate all tracks in this strategy to force re connection.
5826 // Otherwise select new device on the output mix.
5827 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005828 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005829 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005830 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005831 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005832 // If the device is using preferred mixer attributes, the output need to reopen
5833 // with default configuration when the new selected devices are different from
5834 // current routing devices.
5835 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5836 continue;
5837 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305838 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005839 }
5840 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005841 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005842}
5843
5844void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5845{
5846 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005847 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005848 for (size_t i = 0; i < mOutputs.size(); i++) {
5849 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005850 for (const auto& client : outputDesc->getClientIterable()) {
5851 if (client->hasPreferredDevice() && client->uid() == uid) {
5852 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005853 auto clientStrategy = client->strategy();
5854 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5855 end(affectedStrategies)) {
5856 continue;
5857 }
5858 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005859 }
5860 }
5861 }
5862 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005863 for (const auto& strategy : affectedStrategies) {
5864 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005865 }
5866
5867 // remove input routes associated with this uid
5868 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005869 for (size_t i = 0; i < mInputs.size(); i++) {
5870 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005871 for (const auto& client : inputDesc->getClientIterable()) {
5872 if (client->hasPreferredDevice() && client->uid() == uid) {
5873 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5874 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005875 }
5876 }
5877 }
5878 // reroute inputs if necessary
5879 SortedVector<audio_io_handle_t> inputsToClose;
5880 for (size_t i = 0; i < mInputs.size(); i++) {
5881 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005882 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005883 inputsToClose.add(inputDesc->mIoHandle);
5884 }
5885 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005886 for (const auto& input : inputsToClose) {
5887 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005888 }
5889}
5890
Eric Laurentd60560a2015-04-10 11:31:20 -07005891void AudioPolicyManager::clearAudioSources(uid_t uid)
5892{
5893 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005894 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5895 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005896 stopAudioSource(mAudioSources.keyAt(i));
5897 }
5898 }
5899}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005900
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005901status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5902 audio_io_handle_t *ioHandle,
5903 audio_devices_t *device)
5904{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005905 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5906 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005907 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005908 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5909 if (deviceDesc == nullptr) {
5910 return INVALID_OPERATION;
5911 }
5912 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005913
François Gaffiedf372692015-03-19 10:43:27 +01005914 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005915}
5916
Eric Laurentd60560a2015-04-10 11:31:20 -07005917status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005918 const audio_attributes_t *attributes,
5919 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005920 uid_t uid) {
5921 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005922 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005923}
5924
5925status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5926 const audio_attributes_t *attributes,
5927 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005928 uid_t uid, bool internal, bool isCallRx,
5929 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005930{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005931 ALOGV("%s", __FUNCTION__);
5932 *portId = AUDIO_PORT_HANDLE_NONE;
5933
5934 if (source == NULL || attributes == NULL || portId == NULL) {
5935 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5936 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005937 return BAD_VALUE;
5938 }
5939
Eric Laurentd60560a2015-04-10 11:31:20 -07005940 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5941 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005942 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5943 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005944 return INVALID_OPERATION;
5945 }
5946
François Gaffie11d30102018-11-02 16:09:09 +01005947 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005948 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005949 String8(source->ext.device.address),
5950 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005951 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005952 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005953 return BAD_VALUE;
5954 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005955
jiabin4ef93452019-09-10 14:29:54 -07005956 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005957
François Gaffieaaac0fd2018-11-22 17:56:39 +01005958 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005959 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005960 mEngine->getStreamTypeForAttributes(*attributes),
5961 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005962 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005963
David Lif85c5e32024-07-01 13:14:10 +00005964 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005965 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005966 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005967 }
5968 return status;
5969}
5970
David Lif85c5e32024-07-01 13:14:10 +00005971status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5972 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005973{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005974 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005975
5976 // make sure we only have one patch per source.
5977 disconnectAudioSource(sourceDesc);
5978
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005979 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005980 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5981 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5982 sourceDesc->srcDevice()->type(),
5983 String8(sourceDesc->srcDevice()->address().c_str()),
5984 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005985 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005986 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005987 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005988 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005989 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5990 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5991 return INVALID_OPERATION;
5992 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005993 PatchBuilder patchBuilder;
5994 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5995 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005996
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005997 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00005998 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005999}
6000
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006001status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006002{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006003 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6004 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006005 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006006 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006007 return BAD_VALUE;
6008 }
6009 status_t status = disconnectAudioSource(sourceDesc);
6010
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006011 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006012 return status;
6013}
6014
Andy Hung2ddee192015-12-18 17:34:44 -08006015status_t AudioPolicyManager::setMasterMono(bool mono)
6016{
6017 if (mMasterMono == mono) {
6018 return NO_ERROR;
6019 }
6020 mMasterMono = mono;
6021 // if enabling mono we close all offloaded devices, which will invalidate the
6022 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6023 // for recreating the new AudioTrack as non-offloaded PCM.
6024 //
6025 // If disabling mono, we leave all tracks as is: we don't know which clients
6026 // and tracks are able to be recreated as offloaded. The next "song" should
6027 // play back offloaded.
6028 if (mMasterMono) {
6029 Vector<audio_io_handle_t> offloaded;
6030 for (size_t i = 0; i < mOutputs.size(); ++i) {
6031 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6032 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6033 offloaded.push(desc->mIoHandle);
6034 }
6035 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006036 for (const auto& handle : offloaded) {
6037 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006038 }
6039 }
6040 // update master mono for all remaining outputs
6041 for (size_t i = 0; i < mOutputs.size(); ++i) {
6042 updateMono(mOutputs.keyAt(i));
6043 }
6044 return NO_ERROR;
6045}
6046
6047status_t AudioPolicyManager::getMasterMono(bool *mono)
6048{
6049 *mono = mMasterMono;
6050 return NO_ERROR;
6051}
6052
Eric Laurentac9cef52017-06-09 15:46:26 -07006053float AudioPolicyManager::getStreamVolumeDB(
6054 audio_stream_type_t stream, int index, audio_devices_t device)
6055{
Vlad Popa9d482762024-06-21 16:40:23 -07006056 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6057 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006058}
6059
jiabin81772902018-04-02 17:52:27 -07006060status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6061 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006062 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006063{
Kriti Dang6537def2021-03-02 13:46:59 +01006064 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6065 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006066 return BAD_VALUE;
6067 }
Kriti Dang6537def2021-03-02 13:46:59 +01006068 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6069 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006070
6071 size_t formatsWritten = 0;
6072 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006073
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006074 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006075 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6076 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006077 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006078 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006079 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006080 bool formatEnabled = true;
6081 switch (forceUse) {
6082 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006083 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006084 break;
6085 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6086 formatEnabled = false;
6087 break;
6088 default: // AUTO or ALWAYS => true
6089 break;
jiabin81772902018-04-02 17:52:27 -07006090 }
6091 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6092 }
jiabin81772902018-04-02 17:52:27 -07006093 }
6094 return NO_ERROR;
6095}
6096
Kriti Dang6537def2021-03-02 13:46:59 +01006097status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6098 audio_format_t *surroundFormats) {
6099 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6100 return BAD_VALUE;
6101 }
6102 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6103 __func__, *numSurroundFormats, surroundFormats);
6104
6105 size_t formatsWritten = 0;
6106 size_t formatsMax = *numSurroundFormats;
6107 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6108
6109 // Return formats from all device profiles that have already been resolved by
6110 // checkOutputsForDevice().
6111 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6112 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6113 audio_devices_t deviceType = device->type();
6114 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6115 // returns formats reported by HDMI devices.
6116 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6117 continue;
6118 }
6119 // Formats reported by sink devices
6120 std::unordered_set<audio_format_t> formatset;
6121 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6122 formatset.insert(it->second.begin(), it->second.end());
6123 }
6124
6125 // Formats hard-coded in the in policy configuration file (if any).
6126 FormatVector encodedFormats = device->encodedFormats();
6127 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6128 // Filter the formats which are supported by the vendor hardware.
6129 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006130 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006131 formats.insert(*it);
6132 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006133 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006134 if (pair.second.count(*it) != 0) {
6135 formats.insert(pair.first);
6136 break;
6137 }
6138 }
6139 }
6140 }
6141 }
6142 *numSurroundFormats = formats.size();
6143 for (const auto& format: formats) {
6144 if (formatsWritten < formatsMax) {
6145 surroundFormats[formatsWritten++] = format;
6146 }
6147 }
6148 return NO_ERROR;
6149}
6150
jiabin81772902018-04-02 17:52:27 -07006151status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6152{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006153 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006154 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6155 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006156 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006157 return BAD_VALUE;
6158 }
6159
Mikhail Naganov100f0122018-11-29 11:22:16 -08006160 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6161 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006162 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006163 return INVALID_OPERATION;
6164 }
6165
Mikhail Naganov100f0122018-11-29 11:22:16 -08006166 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006167 return NO_ERROR;
6168 }
6169
Mikhail Naganov100f0122018-11-29 11:22:16 -08006170 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006171 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006172 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006173 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006174 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006175 }
6176 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006177 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006178 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006179 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006180 }
6181 }
6182
6183 sp<SwAudioOutputDescriptor> outputDesc;
6184 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006185 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6186 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006187 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6188 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006189 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006190 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006191 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6192 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6193 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006194 name.c_str(),
6195 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006196 if (status != NO_ERROR) {
6197 continue;
6198 }
6199 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6200 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6201 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006202 name.c_str(),
6203 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006204 profileUpdated |= (status == NO_ERROR);
6205 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006206 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006207 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006208 AUDIO_DEVICE_IN_HDMI);
6209 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6210 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006211 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006212 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006213 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6214 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6215 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006216 name.c_str(),
6217 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006218 if (status != NO_ERROR) {
6219 continue;
6220 }
6221 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6222 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6223 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006224 name.c_str(),
6225 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006226 profileUpdated |= (status == NO_ERROR);
6227 }
6228
jiabin81772902018-04-02 17:52:27 -07006229 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006230 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006231 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006232 }
6233
6234 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6235}
6236
Eric Laurent5ada82e2019-08-29 17:53:54 -07006237void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006238{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006239 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006240 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006241 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006242 }
6243}
6244
jiabin6012f912018-11-02 17:06:30 -07006245bool AudioPolicyManager::isHapticPlaybackSupported()
6246{
6247 for (const auto& hwModule : mHwModules) {
6248 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6249 for (const auto &outProfile : outputProfiles) {
6250 struct audio_port audioPort;
6251 outProfile->toAudioPort(&audioPort);
6252 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6253 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6254 return true;
6255 }
6256 }
6257 }
6258 }
6259 return false;
6260}
6261
Carter Hsu325a8eb2022-01-19 19:56:51 +08006262bool AudioPolicyManager::isUltrasoundSupported()
6263{
6264 bool hasUltrasoundOutput = false;
6265 bool hasUltrasoundInput = false;
6266 for (const auto& hwModule : mHwModules) {
6267 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6268 if (!hasUltrasoundOutput) {
6269 for (const auto &outProfile : outputProfiles) {
6270 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6271 hasUltrasoundOutput = true;
6272 break;
6273 }
6274 }
6275 }
6276
6277 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6278 if (!hasUltrasoundInput) {
6279 for (const auto &inputProfile : inputProfiles) {
6280 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6281 hasUltrasoundInput = true;
6282 break;
6283 }
6284 }
6285 }
6286
6287 if (hasUltrasoundOutput && hasUltrasoundInput)
6288 return true;
6289 }
6290 return false;
6291}
6292
Atneya Nair698f5ef2022-12-15 16:15:09 -08006293bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6294{
6295 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6296 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6297 for (const auto& hwModule : mHwModules) {
6298 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6299 for (const auto &inputProfile : inputProfiles) {
6300 if ((inputProfile->getFlags() & mask) == mask) {
6301 return true;
6302 }
6303 }
6304 }
6305 return false;
6306}
6307
Eric Laurent8340e672019-11-06 11:01:08 -08006308bool AudioPolicyManager::isCallScreenModeSupported()
6309{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006310 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006311}
6312
6313
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006314status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006315{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006316 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006317 if (!sourceDesc->isConnected()) {
6318 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6319 return NO_ERROR;
6320 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006321 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6322 if (swOutput != 0) {
6323 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006324 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006325 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006326 }
jiabinbce0c1d2020-10-05 11:20:18 -07006327 if (releaseOutput(sourceDesc->portId())) {
6328 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6329 // no need to release audio patch here but just return NO_ERROR.
6330 return NO_ERROR;
6331 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006332 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006333 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006334 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006335 // close Hwoutput and remove from mHwOutputs
6336 } else {
6337 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6338 }
6339 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006340 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006341 sourceDesc->disconnect();
6342 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006343}
6344
François Gaffiec005e562018-11-06 15:04:49 +01006345sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6346 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006347{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006348 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006349 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006350 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006351 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006352 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6353 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006354 source = sourceDesc;
6355 break;
6356 }
6357 }
6358 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006359}
6360
Eric Laurentb4f42a92022-01-17 17:37:31 +01006361bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006362 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006363 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006364{
6365 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6366 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006367 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006368 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006369 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6370 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6371 return false;
6372 }
6373 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6374 return false;
6375 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006376 }
6377
Eric Laurentd332bc82023-08-04 11:45:23 +02006378 // The caller can have the audio config criteria ignored by either passing a null ptr or
6379 // the AUDIO_CONFIG_INITIALIZER value.
6380 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006381 // some positional channel masks and PCM format and for stereo if low latency performance
6382 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006383
6384 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006385 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006386 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6387 ? audio_channel_mask_contains_stereo(config->channel_mask)
6388 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006389 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006390 return false;
6391 }
6392 if (!audio_is_linear_pcm(config->format)) {
6393 return false;
6394 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006395 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6396 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6397 return false;
6398 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006399 }
6400
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006401 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006402 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006403 if (profile == nullptr) {
6404 return false;
6405 }
6406
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006407 return true;
6408}
6409
Shunkai Yao4c3af932024-04-26 04:12:21 +00006410// The Spatializer output is compatible with Haptic use cases if:
6411// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6412// with client if client haptic channel bits were set, or
6413// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6414// including the haptic bits or creating the HapticGenerator effect for same session.
6415bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6416 const audio_config_t* config, audio_session_t sessionId) const {
6417 const auto clientHapticChannel =
6418 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6419 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6420 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6421
6422 if (threadOutputHapticChannel) {
6423 // check format and sampleRate match if client haptic channel mask exist
6424 if (clientHapticChannel) {
6425 return mSpatializerOutput->getFormat() == config->format &&
6426 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6427 }
6428 return true;
6429 } else {
6430 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6431 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6432 // HapticGenerator effect for this session) are not supported.
6433 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006434 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006435 }
6436}
6437
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006438void AudioPolicyManager::checkVirtualizerClientRoutes() {
6439 std::set<audio_stream_type_t> streamsToInvalidate;
6440 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006441 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6442 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006443 audio_attributes_t attr = client->attributes();
6444 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6445 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6446 audio_config_base_t clientConfig = client->config();
6447 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006448 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006449 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006450 streamsToInvalidate.insert(client->stream());
6451 }
6452 }
6453 }
6454
jiabinc44b3462022-12-08 12:52:31 -08006455 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006456}
6457
Eric Laurente191d1b2022-04-15 11:59:25 +02006458
6459bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6460 const sp<SwAudioOutputDescriptor>& outputDesc) {
6461 if (outputDesc->isDuplicated()) {
6462 return false;
6463 }
6464 DeviceVector devices = outputDesc->supportedDevices();
6465 for (size_t i = 0; i < mOutputs.size(); i++) {
6466 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6467 if (desc == outputDesc || desc->isDuplicated()) {
6468 continue;
6469 }
6470 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6471 if (!sharedDevices.isEmpty()
6472 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6473 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6474 return false;
6475 }
6476 }
6477 return true;
6478}
6479
6480
Eric Laurentfa0f6742021-08-17 18:39:44 +02006481status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006482 const audio_attributes_t *attr,
6483 audio_io_handle_t *output) {
6484 *output = AUDIO_IO_HANDLE_NONE;
6485
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006486 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6487 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6488 audio_config_t *configPtr = nullptr;
6489 audio_config_t config;
6490 if (mixerConfig != nullptr) {
6491 config = audio_config_initializer(mixerConfig);
6492 configPtr = &config;
6493 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006494 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006495 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006496 return BAD_VALUE;
6497 }
6498
6499 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006500 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006501 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006502 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006503 return BAD_VALUE;
6504 }
6505
Eric Laurente191d1b2022-04-15 11:59:25 +02006506 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006507 for (size_t i = 0; i < mOutputs.size(); i++) {
6508 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006509 if (!desc->isDuplicated()
6510 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6511 spatializerOutputs.push_back(desc);
6512 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006513 }
6514 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006515 mSpatializerOutput.clear();
6516 bool outputsChanged = false;
6517 for (const auto& desc : spatializerOutputs) {
6518 if (desc->mProfile == profile
6519 && (configPtr == nullptr
6520 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6521 mSpatializerOutput = desc;
6522 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6523 } else {
6524 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6525 " and devices %s", __func__, desc->mIoHandle,
6526 configPtr != nullptr ? configPtr->channel_mask : 0,
6527 devices.toString().c_str());
6528 closeOutput(desc->mIoHandle);
6529 outputsChanged = true;
6530 }
Eric Laurent39095982021-08-24 18:29:27 +02006531 }
6532
Eric Laurente191d1b2022-04-15 11:59:25 +02006533 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006534 sp<SwAudioOutputDescriptor> desc =
6535 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006536 if (desc != nullptr) {
6537 mSpatializerOutput = desc;
6538 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006539 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006540 }
6541
6542 checkVirtualizerClientRoutes();
6543
Eric Laurente191d1b2022-04-15 11:59:25 +02006544 if (outputsChanged) {
6545 mPreviousOutputs = mOutputs;
6546 mpClientInterface->onAudioPortListUpdate();
6547 }
6548
6549 if (mSpatializerOutput == nullptr) {
6550 ALOGV("%s could not open spatializer output with requested config", __func__);
6551 return BAD_VALUE;
6552 }
Eric Laurent39095982021-08-24 18:29:27 +02006553 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006554 ALOGV("%s returning new spatializer output %d", __func__, *output);
6555 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006556}
6557
Eric Laurentfa0f6742021-08-17 18:39:44 +02006558status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6559 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006560 return INVALID_OPERATION;
6561 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006562 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006563 return BAD_VALUE;
6564 }
Eric Laurent39095982021-08-24 18:29:27 +02006565
Eric Laurente191d1b2022-04-15 11:59:25 +02006566 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6567 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6568 closeOutput(mSpatializerOutput->mIoHandle);
6569 //from now on mSpatializerOutput is null
6570 checkVirtualizerClientRoutes();
6571 }
Eric Laurent39095982021-08-24 18:29:27 +02006572
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006573 return NO_ERROR;
6574}
6575
Eric Laurente552edb2014-03-10 17:42:56 -07006576// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006577// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006578// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006579uint32_t AudioPolicyManager::nextAudioPortGeneration()
6580{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006581 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006582}
6583
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006584AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006585 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006586 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006587 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006588 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006589 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006590 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006591 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006592 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006593 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006594 mAudioPortGeneration(1),
6595 mBeaconMuteRefCount(0),
6596 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006597 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006598 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006599 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006600 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006601{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006602}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006603
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006604status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006605 if (mEngine == nullptr) {
6606 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006607 }
6608 mEngine->setObserver(this);
6609 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006610 if (status != NO_ERROR) {
6611 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6612 return status;
6613 }
François Gaffie2110e042015-03-24 08:41:51 +01006614
jiabin29230182023-04-04 21:02:36 +00006615 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6616 // at the end of this function.
6617 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006618 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6619 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6620
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006621 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006622 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006623 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006624
Eric Laurent3a4311c2014-03-17 12:00:47 -07006625 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006626 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6627 defaultOutputDevice == nullptr ||
6628 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6629 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6630 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006631 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006632 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006633 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006634
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006635 // Silence ALOGV statements
6636 property_set("log.tag." LOG_TAG, "D");
6637
Eric Laurente552edb2014-03-10 17:42:56 -07006638 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006639 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006640}
6641
Eric Laurente0720872014-03-11 09:30:41 -07006642AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006643{
Eric Laurente552edb2014-03-10 17:42:56 -07006644 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006645 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006646 }
6647 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006648 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006649 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006650 mAvailableOutputDevices.clear();
6651 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006652 mOutputs.clear();
6653 mInputs.clear();
6654 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006655 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006656 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006657}
6658
Eric Laurente0720872014-03-11 09:30:41 -07006659status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006660{
Eric Laurent87ffa392015-05-22 10:32:38 -07006661 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006662}
6663
Eric Laurente552edb2014-03-10 17:42:56 -07006664// ---
6665
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006666void AudioPolicyManager::onNewAudioModulesAvailable()
6667{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006668 DeviceVector newDevices;
6669 onNewAudioModulesAvailableInt(&newDevices);
6670 if (!newDevices.empty()) {
6671 nextAudioPortGeneration();
6672 mpClientInterface->onAudioPortListUpdate();
6673 }
6674}
6675
6676void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6677{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006678 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006679 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6680 continue;
6681 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006682 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006683 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6684 handle != AUDIO_MODULE_HANDLE_NONE) {
6685 hwModule->setHandle(handle);
6686 } else {
6687 ALOGW("could not load HW module %s", hwModule->getName());
6688 continue;
6689 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006690 }
6691 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006692 // open all output streams needed to access attached devices.
6693 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006694 // This also validates mAvailableOutputDevices list
6695 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6696 if (!outProfile->canOpenNewIo()) {
6697 ALOGE("Invalid Output profile max open count %u for profile %s",
6698 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6699 continue;
6700 }
6701 if (!outProfile->hasSupportedDevices()) {
6702 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6703 continue;
6704 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006705 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6706 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006707 mTtsOutputAvailable = true;
6708 }
6709
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006710 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006711 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006712 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006713 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6714 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006715 } else {
6716 // choose first device present in profile's SupportedDevices also part of
6717 // mAvailableOutputDevices.
6718 if (availProfileDevices.isEmpty()) {
6719 continue;
6720 }
6721 supportedDevice = availProfileDevices.itemAt(0);
6722 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006723 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006724 continue;
6725 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306726
6727 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6728 && availProfileDevices.areAllDevicesAttached()) {
6729 ALOGV("%s skip opening output for mmap profile %s", __func__,
6730 outProfile->getTagName().c_str());
6731 continue;
6732 }
6733
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006734 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6735 mpClientInterface);
6736 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006737 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006738 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6739 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006740 AUDIO_STREAM_DEFAULT,
Haofan Wangf6e304f2024-07-09 23:06:58 -07006741 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006742 if (status != NO_ERROR) {
6743 ALOGW("Cannot open output stream for devices %s on hw module %s",
6744 supportedDevice->toString().c_str(), hwModule->getName());
6745 continue;
6746 }
6747 for (const auto &device : availProfileDevices) {
6748 // give a valid ID to an attached device once confirmed it is reachable
6749 if (!device->isAttached()) {
6750 device->attach(hwModule);
6751 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006752 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006753 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006754 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6755 }
6756 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006757 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006758 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6759 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006760 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006761 }
Eric Laurent39095982021-08-24 18:29:27 +02006762 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006763 outputDesc->close();
6764 } else {
6765 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306766 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006767 DeviceVector(supportedDevice),
6768 true,
6769 0,
6770 NULL);
6771 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006772 }
6773 // open input streams needed to access attached devices to validate
6774 // mAvailableInputDevices list
6775 for (const auto& inProfile : hwModule->getInputProfiles()) {
6776 if (!inProfile->canOpenNewIo()) {
6777 ALOGE("Invalid Input profile max open count %u for profile %s",
6778 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6779 continue;
6780 }
6781 if (!inProfile->hasSupportedDevices()) {
6782 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6783 continue;
6784 }
6785 // chose first device present in profile's SupportedDevices also part of
6786 // available input devices
6787 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006788 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006789 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006790 ALOGV("%s: Input device list is empty! for profile %s",
6791 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006792 continue;
6793 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306794
6795 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6796 && availProfileDevices.areAllDevicesAttached()) {
6797 ALOGV("%s skip opening input for mmap profile %s", __func__,
6798 inProfile->getTagName().c_str());
6799 continue;
6800 }
6801
Eric Laurentc71b11b2024-06-03 12:54:53 +00006802 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6803 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006804
6805 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6806 status_t status = inputDesc->open(nullptr,
6807 availProfileDevices.itemAt(0),
6808 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306809 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006810 &input);
6811 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306812 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6813 __func__, availProfileDevices.toString().c_str(),
6814 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006815 continue;
6816 }
6817 for (const auto &device : availProfileDevices) {
6818 // give a valid ID to an attached device once confirmed it is reachable
6819 if (!device->isAttached()) {
6820 device->attach(hwModule);
6821 device->importAudioPortAndPickAudioProfile(inProfile, true);
6822 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006823 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006824 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6825 }
6826 }
6827 inputDesc->close();
6828 }
6829 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006830
6831 // Check if spatializer outputs can be closed until used.
6832 // mOutputs vector never contains duplicated outputs at this point.
6833 std::vector<audio_io_handle_t> outputsClosed;
6834 for (size_t i = 0; i < mOutputs.size(); i++) {
6835 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6836 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6837 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6838 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006839 nextAudioPortGeneration();
6840 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6841 if (index >= 0) {
6842 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6843 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6844 patchDesc->getAfHandle(), 0);
6845 mAudioPatches.removeItemsAt(index);
6846 mpClientInterface->onAudioPatchListUpdate();
6847 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006848 desc->close();
6849 }
6850 }
6851 for (auto output : outputsClosed) {
6852 removeOutput(output);
6853 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006854}
6855
Eric Laurent98e38192018-02-15 18:31:53 -08006856void AudioPolicyManager::addOutput(audio_io_handle_t output,
6857 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006858{
Eric Laurent1c333e22014-05-20 10:48:17 -07006859 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006860 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006861 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006862 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006863 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006864}
6865
François Gaffie53615e22015-03-19 09:24:12 +01006866void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6867{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006868 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6869 ALOGV("%s: removing primary output", __func__);
6870 mPrimaryOutput = nullptr;
6871 }
François Gaffie53615e22015-03-19 09:24:12 +01006872 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006873 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006874}
6875
Eric Laurent98e38192018-02-15 18:31:53 -08006876void AudioPolicyManager::addInput(audio_io_handle_t input,
6877 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006878{
Eric Laurent1c333e22014-05-20 10:48:17 -07006879 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006880 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006881}
Eric Laurente552edb2014-03-10 17:42:56 -07006882
François Gaffie11d30102018-11-02 16:09:09 +01006883status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006884 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006885 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006886{
François Gaffie11d30102018-11-02 16:09:09 +01006887 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006888 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006889 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006890
François Gaffie11d30102018-11-02 16:09:09 +01006891 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006892 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006893 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006894 }
Eric Laurente552edb2014-03-10 17:42:56 -07006895
Eric Laurent3b73df72014-03-11 09:06:29 -07006896 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006897 // first call getAudioPort to get the supported attributes from the HAL
6898 struct audio_port_v7 port = {};
6899 device->toAudioPort(&port);
6900 status_t status = mpClientInterface->getAudioPort(&port);
6901 if (status == NO_ERROR) {
6902 device->importAudioPort(port);
6903 }
6904
6905 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006906 for (size_t i = 0; i < mOutputs.size(); i++) {
6907 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006908 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006909 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006910 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6911 mOutputs.keyAt(i), device->toString().c_str());
6912 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006913 }
6914 }
6915 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006916 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006917 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006918 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6919 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006920 if (profile->supportsDevice(device)) {
6921 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306922 ALOGV("%s(): adding profile %s from module %s",
6923 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006924 }
6925 }
6926 }
6927
Eric Laurent7b279bb2015-12-14 10:18:23 -08006928 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006929
Eric Laurente552edb2014-03-10 17:42:56 -07006930 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006931 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006932 return BAD_VALUE;
6933 }
6934
6935 // open outputs for matching profiles if needed. Direct outputs are also opened to
6936 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6937 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006938 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006939
6940 // nothing to do if one output is already opened for this profile
6941 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006942 for (j = 0; j < outputs.size(); j++) {
6943 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006944 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006945 // matching profile: save the sample rates, format and channel masks supported
6946 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006947 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006948 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006949 }
Eric Laurente552edb2014-03-10 17:42:56 -07006950 break;
6951 }
6952 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006953 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006954 continue;
6955 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306956 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6957 ALOGV("%s skip opening output for mmap profile %s",
6958 __func__, profile->getTagName().c_str());
6959 continue;
6960 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006961 if (!profile->canOpenNewIo()) {
6962 ALOGW("Max Output number %u already opened for this profile %s",
6963 profile->maxOpenCount, profile->getTagName().c_str());
6964 continue;
6965 }
6966
Eric Laurent83efe1c2017-07-09 16:51:08 -07006967 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006968 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006969 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6970 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006971 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006972 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006973 profiles.removeAt(profile_index);
6974 profile_index--;
6975 } else {
6976 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006977 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006978 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006979 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6980 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006981 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006982 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006983
François Gaffie11d30102018-11-02 16:09:09 +01006984 if (device_distinguishes_on_address(deviceType)) {
6985 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6986 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306987 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6988 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006989 }
Eric Laurente552edb2014-03-10 17:42:56 -07006990 ALOGV("checkOutputsForDevice(): adding output %d", output);
6991 }
6992 }
6993
6994 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006995 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006996 return BAD_VALUE;
6997 }
Eric Laurentd4692962014-05-05 18:13:44 -07006998 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006999 // check if one opened output is not needed any more after disconnecting one device
7000 for (size_t i = 0; i < mOutputs.size(); i++) {
7001 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007002 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007003 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007004 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007005 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007006 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007007 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007008 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7009 mOutputs.keyAt(i));
7010 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007011 }
Eric Laurente552edb2014-03-10 17:42:56 -07007012 }
7013 }
Eric Laurentd4692962014-05-05 18:13:44 -07007014 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007015 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007016 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7017 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007018 if (!profile->supportsDevice(device)) {
7019 continue;
7020 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307021 ALOGV("%s(): clearing direct output profile %s on module %s",
7022 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007023 profile->clearAudioProfiles();
7024 if (!profile->hasDynamicAudioProfile()) {
7025 continue;
7026 }
7027 // When a device is disconnected, if there is an IOProfile that contains dynamic
7028 // profiles and supports the disconnected device, call getAudioPort to repopulate
7029 // the capabilities of the devices that is supported by the IOProfile.
7030 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7031 if (supportedDevice == device ||
7032 !mAvailableOutputDevices.contains(supportedDevice)) {
7033 continue;
7034 }
7035 struct audio_port_v7 port;
7036 supportedDevice->toAudioPort(&port);
7037 status_t status = mpClientInterface->getAudioPort(&port);
7038 if (status == NO_ERROR) {
7039 supportedDevice->importAudioPort(port);
7040 }
Eric Laurente552edb2014-03-10 17:42:56 -07007041 }
7042 }
7043 }
7044 }
7045 return NO_ERROR;
7046}
7047
François Gaffie11d30102018-11-02 16:09:09 +01007048status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007049 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007050{
François Gaffie11d30102018-11-02 16:09:09 +01007051 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007052 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007053 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007054 }
7055
Eric Laurentd4692962014-05-05 18:13:44 -07007056 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007057 sp<AudioInputDescriptor> desc;
7058
jiabinbf5f4262023-04-12 21:48:34 +00007059 // first call getAudioPort to get the supported attributes from the HAL
7060 struct audio_port_v7 port = {};
7061 device->toAudioPort(&port);
7062 status_t status = mpClientInterface->getAudioPort(&port);
7063 if (status == NO_ERROR) {
7064 device->importAudioPort(port);
7065 }
7066
Eric Laurent0dd51852019-04-19 18:18:58 -07007067 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007068 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007069 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007070 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007071 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007072 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007073 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007074
François Gaffie11d30102018-11-02 16:09:09 +01007075 if (profile->supportsDevice(device)) {
7076 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307077 ALOGV("%s : adding profile %s from module %s", __func__,
7078 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007079 }
7080 }
7081 }
7082
Eric Laurent0dd51852019-04-19 18:18:58 -07007083 if (profiles.isEmpty()) {
7084 ALOGW("%s: No input profile available for device %s",
7085 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007086 return BAD_VALUE;
7087 }
7088
7089 // open inputs for matching profiles if needed. Direct inputs are also opened to
7090 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7091 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7092
Eric Laurent1c333e22014-05-20 10:48:17 -07007093 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007094
Eric Laurentd4692962014-05-05 18:13:44 -07007095 // nothing to do if one input is already opened for this profile
7096 size_t input_index;
7097 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7098 desc = mInputs.valueAt(input_index);
7099 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007100 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007101 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007102 }
Eric Laurentd4692962014-05-05 18:13:44 -07007103 break;
7104 }
7105 }
7106 if (input_index != mInputs.size()) {
7107 continue;
7108 }
7109
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307110 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7111 ALOGV("%s skip opening input for mmap profile %s",
7112 __func__, profile->getTagName().c_str());
7113 continue;
7114 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007115 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307116 ALOGW("%s Max Input number %u already opened for this profile %s",
7117 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007118 continue;
7119 }
7120
Eric Laurentc71b11b2024-06-03 12:54:53 +00007121 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007122 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307123 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307124 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7125 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007126
Eric Laurentcf2c0212014-07-25 16:20:43 -07007127 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007128 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007129 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007130 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007131 mpClientInterface->setParameters(input, String8(param));
7132 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007133 }
jiabin12537fc2023-10-12 17:56:08 +00007134 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007135 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307136 ALOGW("%s direct input missing param for profile %s", __func__,
7137 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007138 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007139 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007140 }
7141
Eric Laurent0dd51852019-04-19 18:18:58 -07007142 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007143 addInput(input, desc);
7144 }
7145 } // endif input != 0
7146
Eric Laurentcf2c0212014-07-25 16:20:43 -07007147 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307148 ALOGW("%s could not open input for device %s on profile %s", __func__,
7149 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007150 profiles.removeAt(profile_index);
7151 profile_index--;
7152 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007153 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007154 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007155 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307156 ALOGV("%s: adding input %d for profile %s", __func__,
7157 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007158
7159 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307160 ALOGV("%s: closing input %d for profile %s", __func__,
7161 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007162 closeInput(input);
7163 }
Eric Laurentd4692962014-05-05 18:13:44 -07007164 }
7165 } // end scan profiles
7166
7167 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007168 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007169 return BAD_VALUE;
7170 }
7171 } else {
7172 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007173 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007174 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007175 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007176 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007177 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007178 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007179 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307180 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7181 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007182 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007183 }
7184 }
7185 }
7186 } // end disconnect
7187
7188 return NO_ERROR;
7189}
7190
7191
Eric Laurente0720872014-03-11 09:30:41 -07007192void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007193{
7194 ALOGV("closeOutput(%d)", output);
7195
François Gaffie1c878552018-11-22 16:53:21 +01007196 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7197 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007198 ALOGW("closeOutput() unknown output %d", output);
7199 return;
7200 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007201 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007202 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007203
Eric Laurente552edb2014-03-10 17:42:56 -07007204 // look for duplicated outputs connected to the output being removed.
7205 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007206 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7207 if (dupOutput->isDuplicated() &&
7208 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7209 sp<SwAudioOutputDescriptor> remainingOutput =
7210 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007211 // As all active tracks on duplicated output will be deleted,
7212 // and as they were also referenced on the other output, the reference
7213 // count for their stream type must be adjusted accordingly on
7214 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007215 const bool wasActive = remainingOutput->isActive();
7216 // Note: no-op on the closing output where all clients has already been set inactive
7217 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007218 // stop() will be a no op if the output is still active but is needed in case all
7219 // active streams refcounts where cleared above
7220 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007221 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007222 }
Eric Laurente552edb2014-03-10 17:42:56 -07007223 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7224 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7225
7226 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007227 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007228 }
7229 }
7230
Eric Laurent05b90f82014-08-27 15:32:29 -07007231 nextAudioPortGeneration();
7232
François Gaffie1c878552018-11-22 16:53:21 +01007233 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007234 if (index >= 0) {
7235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007236 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7237 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007238 mAudioPatches.removeItemsAt(index);
7239 mpClientInterface->onAudioPatchListUpdate();
7240 }
7241
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007242 if (closingOutputWasActive) {
7243 closingOutput->stop();
7244 }
François Gaffie1c878552018-11-22 16:53:21 +01007245 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007246 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007247 for (const auto device : closingOutput->devices()) {
7248 device->setPreferredConfig(nullptr);
7249 }
7250 }
Eric Laurente552edb2014-03-10 17:42:56 -07007251
François Gaffie53615e22015-03-19 09:24:12 +01007252 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007253 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007254 if (closingOutput == mSpatializerOutput) {
7255 mSpatializerOutput.clear();
7256 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007257
7258 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7259 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007260 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007261 bool directOutputOpen = false;
7262 for (size_t i = 0; i < mOutputs.size(); i++) {
7263 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7264 directOutputOpen = true;
7265 break;
7266 }
7267 }
7268 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007269 ALOGV("no direct outputs open, reset MSD patches");
7270 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7271 // how output devices for patching are resolved. Avoid by caching and reusing the
7272 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7273 // devices to patch to. This may be complicated by the fact that devices may become
7274 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007275 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007276 }
7277 }
jiabin220eea12024-05-17 17:55:20 +00007278
7279 if (closingOutput->mPreferredAttrInfo != nullptr) {
7280 closingOutput->mPreferredAttrInfo->resetActiveClient();
7281 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007282}
7283
7284void AudioPolicyManager::closeInput(audio_io_handle_t input)
7285{
7286 ALOGV("closeInput(%d)", input);
7287
7288 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7289 if (inputDesc == NULL) {
7290 ALOGW("closeInput() unknown input %d", input);
7291 return;
7292 }
7293
Eric Laurent6a94d692014-05-20 11:18:06 -07007294 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007295
François Gaffie11d30102018-11-02 16:09:09 +01007296 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007297 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007298 if (index >= 0) {
7299 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007300 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7301 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007302 mAudioPatches.removeItemsAt(index);
7303 mpClientInterface->onAudioPatchListUpdate();
7304 }
7305
François Gaffie6ebbce02023-07-19 13:27:53 +02007306 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007307 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007308 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007309
François Gaffie11d30102018-11-02 16:09:09 +01007310 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7311 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007312 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007313 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007314 }
Eric Laurente552edb2014-03-10 17:42:56 -07007315}
7316
François Gaffie11d30102018-11-02 16:09:09 +01007317SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7318 const DeviceVector &devices,
7319 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007320{
7321 SortedVector<audio_io_handle_t> outputs;
7322
François Gaffie11d30102018-11-02 16:09:09 +01007323 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007324 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007325 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007326 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007327 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007328 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007329 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007330 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007331 outputs.add(openOutputs.keyAt(i));
7332 }
7333 }
7334 return outputs;
7335}
7336
Mikhail Naganov37977152018-07-11 15:54:44 -07007337void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7338{
7339 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7340 // output is suspended before any tracks are moved to it
7341 checkA2dpSuspend();
7342 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007343 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007344 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007345 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007346 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007347 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7348 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7349 // configuration changes will ultimately be rerouted correctly. We can still avoid
7350 // unnecessary rerouting by caching and reusing the arguments to
7351 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7352 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007353 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007354 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007355 // an event that changed routing likely occurred, inform upper layers
7356 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007357}
7358
François Gaffiec005e562018-11-06 15:04:49 +01007359bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7360 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007361{
François Gaffiec005e562018-11-06 15:04:49 +01007362 return mEngine->getProductStrategyForAttributes(lAttr) ==
7363 mEngine->getProductStrategyForAttributes(rAttr);
7364}
7365
Francois Gaffieff1eb522020-05-06 18:37:04 +02007366void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7367{
7368 for (size_t i = 0; i < mAudioSources.size(); i++) {
7369 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7370 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007371 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007372 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007373 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007374 }
7375 }
7376}
7377
7378void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7379{
7380 for (size_t i = 0; i < mAudioSources.size(); i++) {
7381 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7382 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7383 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7384 disconnectAudioSource(sourceDesc);
7385 }
7386 }
7387}
7388
François Gaffiec005e562018-11-06 15:04:49 +01007389void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7390{
7391 auto psId = mEngine->getProductStrategyForAttributes(attr);
7392
7393 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7394 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007395
François Gaffie11d30102018-11-02 16:09:09 +01007396 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7397 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007398
Eric Laurentc209fe42020-06-05 18:11:23 -07007399 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007400 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007401 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007402 // take into account dynamic audio policies related changes: if a client is now associated
7403 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007404 // invalidate clients on outputs that do not support all the newly selected devices for the
7405 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007406 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007407 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007408 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007409 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007410 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007411
Eric Laurentc209fe42020-06-05 18:11:23 -07007412 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7413 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7414 continue;
7415 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007416 if (!desc->supportsAllDevices(newDevices)) {
7417 invalidatedOutputs.push_back(desc);
7418 break;
7419 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007420 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007421 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007422 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7423 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7424 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007425 if (status == OK) {
7426 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7427 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7428 maxLatency = desc->latency();
7429 }
7430 invalidatedOutputs.push_back(desc);
7431 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007432 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007433 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007434 }
7435 }
7436
Eric Laurent56ed8842022-11-15 16:04:41 +01007437 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007438 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7439 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007440 for (audio_io_handle_t srcOut : srcOutputs) {
7441 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007442 if (desc == nullptr) continue;
7443
7444 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007445 maxLatency = desc->latency();
7446 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007447
Eric Laurent56ed8842022-11-15 16:04:41 +01007448 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007449 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007450 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007451 // a client on a non direct outputs has necessarily a linear PCM format
7452 // so we can call selectOutput() safely
7453 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7454 client->flags(),
7455 client->config().format,
7456 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007457 client->config().sample_rate,
7458 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007459 if (newOutput != srcOut) {
7460 invalidate = true;
7461 break;
7462 }
7463 } else {
7464 sp<IOProfile> profile = getProfileForOutput(newDevices,
7465 client->config().sample_rate,
7466 client->config().format,
7467 client->config().channel_mask,
7468 client->flags(),
7469 true /* directOnly */);
7470 if (profile != desc->mProfile) {
7471 invalidate = true;
7472 break;
7473 }
7474 }
7475 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007476 // mute strategy while moving tracks from one output to another
7477 if (invalidate) {
7478 invalidatedOutputs.push_back(desc);
7479 if (desc->isStrategyActive(psId)) {
7480 setStrategyMute(psId, true, desc);
7481 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7482 newDevices.types());
7483 }
Eric Laurente552edb2014-03-10 17:42:56 -07007484 }
François Gaffiec005e562018-11-06 15:04:49 +01007485 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007486 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007487 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007488 }
Eric Laurente552edb2014-03-10 17:42:56 -07007489 }
7490
Eric Laurent56ed8842022-11-15 16:04:41 +01007491 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7492 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7493 std::to_string(srcOutputs[0]).c_str(),
7494 std::to_string(dstOutputs[0]).c_str());
7495
François Gaffiec005e562018-11-06 15:04:49 +01007496 // Move effects associated to this stream from previous output to new output
7497 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007498 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007499 }
François Gaffiec005e562018-11-06 15:04:49 +01007500 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007501 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007502 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007503 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007504 desc->setTracksInvalidatedStatusByStrategy(psId);
7505 }
Eric Laurente552edb2014-03-10 17:42:56 -07007506 }
7507 }
7508}
7509
Eric Laurente0720872014-03-11 09:30:41 -07007510void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007511{
François Gaffiec005e562018-11-06 15:04:49 +01007512 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7513 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7514 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007515 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007516 }
Eric Laurente552edb2014-03-10 17:42:56 -07007517}
7518
Kevin Rocard153f92d2018-12-18 18:33:28 -08007519void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007520 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007521 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007522 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007523 for (size_t i = 0; i < mOutputs.size(); i++) {
7524 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7525 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007526 sp<AudioPolicyMix> primaryMix;
7527 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007528 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007529 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7530 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7531 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007532 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7533 for (auto &secondaryMix : secondaryMixes) {
7534 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7535 if (outputDesc != nullptr &&
7536 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7537 secondaryDescs.push_back(outputDesc);
7538 }
7539 }
7540
jiabinc44b3462022-12-08 12:52:31 -08007541 if (status != OK &&
7542 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7543 // When it failed to query secondary output, only invalidate the client that is not
7544 // MMAP. The reason is that MMAP stream will not support secondary output.
7545 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007546 } else if (!std::equal(
7547 client->getSecondaryOutputs().begin(),
7548 client->getSecondaryOutputs().end(),
7549 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007550 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7551 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007552 // If the format is not PCM, the tracks should be invalidated to get correct
7553 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007554 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007555 } else {
7556 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7557 std::vector<audio_io_handle_t> secondaryOutputIds;
7558 for (const auto &secondaryDesc: secondaryDescs) {
7559 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7560 weakSecondaryDescs.push_back(secondaryDesc);
7561 }
7562 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7563 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007564 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007565 }
7566 }
7567 }
jiabin10a03f12021-05-07 23:46:28 +00007568 if (!trackSecondaryOutputs.empty()) {
7569 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7570 }
jiabinc44b3462022-12-08 12:52:31 -08007571 if (!clientsToInvalidate.empty()) {
7572 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7573 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007574 }
7575}
7576
Eric Laurent2517af32020-11-25 15:31:27 +01007577bool AudioPolicyManager::isScoRequestedForComm() const {
7578 AudioDeviceTypeAddrVector devices;
7579 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7580 for (const auto &device : devices) {
7581 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7582 return true;
7583 }
7584 }
7585 return false;
7586}
7587
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007588bool AudioPolicyManager::isHearingAidUsedForComm() const {
7589 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7590 true /*fromCache*/);
7591 for (const auto &device : devices) {
7592 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7593 return true;
7594 }
7595 }
7596 return false;
7597}
7598
7599
Eric Laurente0720872014-03-11 09:30:41 -07007600void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007601{
François Gaffie53615e22015-03-19 09:24:12 +01007602 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007603 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007604 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007605 return;
7606 }
7607
Eric Laurent3a4311c2014-03-17 12:00:47 -07007608 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007609 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7610 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007611 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007612
7613 // if suspended, restore A2DP output if:
7614 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007615 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007616 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007617 //
Eric Laurentf732e072016-08-03 19:30:28 -07007618 // if not suspended, suspend A2DP output if:
7619 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007620 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007621 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007622 //
7623 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007624 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007625 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007626 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007627 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007628
7629 mpClientInterface->restoreOutput(a2dpOutput);
7630 mA2dpSuspended = false;
7631 }
7632 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007633 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007634 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007635 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007636 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007637
7638 mpClientInterface->suspendOutput(a2dpOutput);
7639 mA2dpSuspended = true;
7640 }
7641 }
7642}
7643
François Gaffie11d30102018-11-02 16:09:09 +01007644DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7645 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007646{
François Gaffiedb1755b2023-09-01 11:50:35 +02007647 if (outputDesc == nullptr) {
7648 return DeviceVector{};
7649 }
François Gaffie11d30102018-11-02 16:09:09 +01007650
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007651 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007652 if (index >= 0) {
7653 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007654 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007655 ALOGV("%s device %s forced by patch %d", __func__,
7656 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7657 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007658 }
7659 }
7660
Dean Wheatley514b4312020-06-17 21:45:00 +10007661 // Do not retrieve engine device for outputs through MSD
7662 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7663 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7664 return outputDesc->devices();
7665 }
7666
Eric Laurent97ac8712018-07-27 18:59:02 -07007667 // Honor explicit routing requests only if no client using default routing is active on this
7668 // input: a specific app can not force routing for other apps by setting a preferred device.
7669 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007670 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007671 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007672 if (device != nullptr) {
7673 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007674 }
7675
François Gaffiea807ef92018-11-05 10:44:33 +01007676 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7677 // of setForceUse / Default Bus device here
7678 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7679 if (device != nullptr) {
7680 return DeviceVector(device);
7681 }
7682
François Gaffiedb1755b2023-09-01 11:50:35 +02007683 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007684 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7685 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307686 auto hasStreamActive = [&](auto stream) {
7687 return hasStream(streams, stream) && isStreamActive(stream, 0);
7688 };
Eric Laurent484e9272018-06-07 17:29:23 -07007689
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307690 auto doGetOutputDevicesForVoice = [&]() {
7691 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007692 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307693 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007694 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7695 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307696 };
7697
7698 // With low-latency playing on speaker, music on WFD, when the first low-latency
7699 // output is stopped, getNewOutputDevices checks for a product strategy
7700 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007701 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307702 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7703 // stream is associated to the output descriptor.
7704 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7705 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7706 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7707 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007708 // Retrieval of devices for voice DL is done on primary output profile, cannot
7709 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007710 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007711 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7712 break;
7713 }
Eric Laurente552edb2014-03-10 17:42:56 -07007714 }
François Gaffiec005e562018-11-06 15:04:49 +01007715 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007716 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007717}
7718
François Gaffie11d30102018-11-02 16:09:09 +01007719sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7720 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007721{
François Gaffie11d30102018-11-02 16:09:09 +01007722 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007723
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007724 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007725 if (index >= 0) {
7726 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007727 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007728 ALOGV("getNewInputDevice() device %s forced by patch %d",
7729 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7730 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007731 }
7732 }
7733
Eric Laurent97ac8712018-07-27 18:59:02 -07007734 // Honor explicit routing requests only if no client using default routing is active on this
7735 // input: a specific app can not force routing for other apps by setting a preferred device.
7736 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007737 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7738 if (device != nullptr) {
7739 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007740 }
7741
Eric Laurentdc95a252018-04-12 12:46:56 -07007742 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007743 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007744 audio_attributes_t attributes;
7745 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007746 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007747 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7748 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007749 attributes = topClient->attributes();
7750 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007751 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007752 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007753 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7754 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007755 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007756 }
7757
Francois Gaffie716e1432019-01-14 16:58:59 +01007758 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7759 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007760 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007761 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007762 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007763 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007764
Eric Laurente552edb2014-03-10 17:42:56 -07007765 return device;
7766}
7767
Eric Laurent794fde22016-03-11 09:50:45 -08007768bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7769 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007770 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007771}
7772
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007773status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007774 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007775 if (devices == nullptr) {
7776 return BAD_VALUE;
7777 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007778
Andy Hung6d23c0f2022-02-16 09:37:15 -08007779 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007780 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7781 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007782 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007783 for (const auto& device : curDevices) {
7784 devices->push_back(device->getDeviceTypeAddr());
7785 }
7786 return NO_ERROR;
7787}
7788
Eric Laurente0720872014-03-11 09:30:41 -07007789void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007790 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007791 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007792 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007793 updateDevicesAndOutputs();
7794 break;
7795 default:
7796 break;
7797 }
7798}
7799
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007800uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007801
7802 // skip beacon mute management if a dedicated TTS output is available
7803 if (mTtsOutputAvailable) {
7804 return 0;
7805 }
7806
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007807 switch(event) {
7808 case STARTING_OUTPUT:
7809 mBeaconMuteRefCount++;
7810 break;
7811 case STOPPING_OUTPUT:
7812 if (mBeaconMuteRefCount > 0) {
7813 mBeaconMuteRefCount--;
7814 }
7815 break;
7816 case STARTING_BEACON:
7817 mBeaconPlayingRefCount++;
7818 break;
7819 case STOPPING_BEACON:
7820 if (mBeaconPlayingRefCount > 0) {
7821 mBeaconPlayingRefCount--;
7822 }
7823 break;
7824 }
7825
7826 if (mBeaconMuteRefCount > 0) {
7827 // any playback causes beacon to be muted
7828 return setBeaconMute(true);
7829 } else {
7830 // no other playback: unmute when beacon starts playing, mute when it stops
7831 return setBeaconMute(mBeaconPlayingRefCount == 0);
7832 }
7833}
7834
7835uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7836 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7837 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7838 // keep track of muted state to avoid repeating mute/unmute operations
7839 if (mBeaconMuted != mute) {
7840 // mute/unmute AUDIO_STREAM_TTS on all outputs
7841 ALOGV("\t muting %d", mute);
7842 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007843 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7844 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7845 ALOGV("\t no tts volume source available");
7846 return 0;
7847 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007848 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007849 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007850 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007851 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007852 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007853 maxLatency = latency;
7854 }
7855 }
7856 mBeaconMuted = mute;
7857 return maxLatency;
7858 }
7859 return 0;
7860}
7861
Eric Laurente0720872014-03-11 09:30:41 -07007862void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007863{
François Gaffiec005e562018-11-06 15:04:49 +01007864 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007865 mPreviousOutputs = mOutputs;
7866}
7867
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007868uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007869 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007870 uint32_t delayMs)
7871{
7872 // mute/unmute strategies using an incompatible device combination
7873 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7874 // if unmuting, unmute only after the specified delay
7875 if (outputDesc->isDuplicated()) {
7876 return 0;
7877 }
7878
7879 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007880 DeviceVector devices = outputDesc->devices();
7881 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007882
François Gaffiec005e562018-11-06 15:04:49 +01007883 auto productStrategies = mEngine->getOrderedProductStrategies();
7884 for (const auto &productStrategy : productStrategies) {
7885 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7886 DeviceVector curDevices =
7887 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7888 curDevices = curDevices.filter(outputDesc->supportedDevices());
7889 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007890 bool doMute = false;
7891
François Gaffiec005e562018-11-06 15:04:49 +01007892 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007893 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007894 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7895 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007896 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007897 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007898 }
Eric Laurent99401132014-05-07 19:48:15 -07007899 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007900 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007901 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007902 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007903 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007904 continue;
7905 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307906 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007907 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7908 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7909 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007910 if (mute) {
7911 // FIXME: should not need to double latency if volume could be applied
7912 // immediately by the audioflinger mixer. We must account for the delay
7913 // between now and the next time the audioflinger thread for this output
7914 // will process a buffer (which corresponds to one buffer size,
7915 // usually 1/2 or 1/4 of the latency).
7916 if (muteWaitMs < desc->latency() * 2) {
7917 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007918 }
7919 }
7920 }
7921 }
7922 }
7923 }
7924
Eric Laurent99401132014-05-07 19:48:15 -07007925 // temporary mute output if device selection changes to avoid volume bursts due to
7926 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007927 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007928 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007929
Eric Laurentdc462862016-07-19 12:29:53 -07007930 if (muteWaitMs < tempMuteWaitMs) {
7931 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007932 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007933
7934 // If recommended duration is defined, replace temporary mute duration to avoid
7935 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7936 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7937 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7938 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7939 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7940
François Gaffieaaac0fd2018-11-22 17:56:39 +01007941 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7942 // make sure that we do not start the temporary mute period too early in case of
7943 // delayed device change
7944 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7945 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007946 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007947 }
7948 }
7949
Eric Laurente552edb2014-03-10 17:42:56 -07007950 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7951 if (muteWaitMs > delayMs) {
7952 muteWaitMs -= delayMs;
7953 usleep(muteWaitMs * 1000);
7954 return muteWaitMs;
7955 }
7956 return 0;
7957}
7958
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307959uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7960 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007961 const DeviceVector &devices,
7962 bool force,
7963 int delayMs,
7964 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007965 bool requiresMuteCheck, bool requiresVolumeCheck,
7966 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007967{
jiabin3ff8d7d2022-12-13 06:27:44 +00007968 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307969 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7970 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7971 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007972 uint32_t muteWaitMs;
7973
7974 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307975 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007976 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307977 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007978 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007979 return muteWaitMs;
7980 }
Eric Laurente552edb2014-03-10 17:42:56 -07007981
7982 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007983 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007984 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007985 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007986
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307987 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7988 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007989
7990 if (!filteredDevices.isEmpty()) {
7991 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007992 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007993
7994 // if the outputs are not materially active, there is no need to mute.
7995 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007996 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007997 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307998 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7999 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008000 muteWaitMs = 0;
8001 }
Eric Laurente552edb2014-03-10 17:42:56 -07008002
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008003 bool outputRouted = outputDesc->isRouted();
8004
Eric Laurent79ea9582020-06-11 18:49:24 -07008005 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8006 // output profile or if new device is not supported AND previous device(s) is(are) still
8007 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008008 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308009 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8010 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008011 // restore previous device after evaluating strategy mute state
8012 outputDesc->setDevices(prevDevices);
8013 return muteWaitMs;
8014 }
8015
Eric Laurente552edb2014-03-10 17:42:56 -07008016 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008017 // the requested device is AUDIO_DEVICE_NONE
8018 // OR the requested device is the same as current device
8019 // AND force is not specified
8020 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008021 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008022 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308023 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8024 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8025 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008026 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308027 ALOGV("%s %s setting same device on routed output, force apply volumes",
8028 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008029 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8030 }
Eric Laurente552edb2014-03-10 17:42:56 -07008031 return muteWaitMs;
8032 }
8033
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308034 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8035 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008036
Eric Laurente552edb2014-03-10 17:42:56 -07008037 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008038 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008039 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008040 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008041 PatchBuilder patchBuilder;
8042 patchBuilder.addSource(outputDesc);
8043 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8044 for (const auto &filteredDevice : filteredDevices) {
8045 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008046 }
8047
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008048 // Add half reported latency to delayMs when muteWaitMs is null in order
8049 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008050 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8051 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8052 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008053 }
Eric Laurente552edb2014-03-10 17:42:56 -07008054
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008055 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8056 if (!skipMuteDelay) {
8057 // update stream volumes according to new device
8058 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8059 }
Eric Laurente552edb2014-03-10 17:42:56 -07008060
8061 return muteWaitMs;
8062}
8063
Eric Laurentc75307b2015-03-17 15:29:32 -07008064status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008065 int delayMs,
8066 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008067{
Eric Laurent6a94d692014-05-20 11:18:06 -07008068 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008069 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8070 return INVALID_OPERATION;
8071 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008072 if (patchHandle) {
8073 index = mAudioPatches.indexOfKey(*patchHandle);
8074 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008075 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008076 }
8077 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008078 return INVALID_OPERATION;
8079 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008080 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008081 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008082 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008083 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008084 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008085 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008086 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008087 return status;
8088}
8089
8090status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008091 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008092 bool force,
8093 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008094{
8095 status_t status = NO_ERROR;
8096
Eric Laurent1f2f2232014-06-02 12:01:23 -07008097 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008098 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8099 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008100
François Gaffie11d30102018-11-02 16:09:09 +01008101 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008102 PatchBuilder patchBuilder;
8103 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008104 // AUDIO_SOURCE_HOTWORD is for internal use only:
8105 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008106 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8107 auto result = usecase;
8108 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8109 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8110 }
8111 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008112 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008113 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008114 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008115 }
8116 }
8117 return status;
8118}
8119
Eric Laurent6a94d692014-05-20 11:18:06 -07008120status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8121 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008122{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008123 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008124 ssize_t index;
8125 if (patchHandle) {
8126 index = mAudioPatches.indexOfKey(*patchHandle);
8127 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008128 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008129 }
8130 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008131 return INVALID_OPERATION;
8132 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008133 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008134 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008135 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008136 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008137 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008138 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008139 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008140 return status;
8141}
8142
François Gaffie11d30102018-11-02 16:09:09 +01008143sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008144 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008145 audio_format_t& format,
8146 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008147 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008148{
8149 // Choose an input profile based on the requested capture parameters: select the first available
8150 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008151 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008152
Atneya Nair0f0a8032022-12-12 16:20:12 -08008153 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8154 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8155 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8156
8157 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008158
jiabin2fd710d2022-05-02 23:20:22 +00008159 for (;;) {
8160 sp<IOProfile> firstInexact = nullptr;
8161 uint32_t updatedSamplingRate = 0;
8162 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8163 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8164 for (const auto& hwModule : mHwModules) {
8165 for (const auto& profile : hwModule->getInputProfiles()) {
8166 // profile->log();
8167 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008168 if (profile->getCompatibilityScore(
8169 DeviceVector(device),
8170 samplingRate,
8171 &updatedSamplingRate,
8172 format,
8173 &updatedFormat,
8174 channelMask,
8175 &updatedChannelMask,
8176 // FIXME ugly cast
8177 (audio_output_flags_t) flags,
8178 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8179 samplingRate = updatedSamplingRate;
8180 format = updatedFormat;
8181 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008182 return profile;
8183 }
jiabin66acc432024-02-06 00:57:36 +00008184 if (firstInexact == nullptr
8185 && profile->getCompatibilityScore(
8186 DeviceVector(device),
8187 samplingRate,
8188 &updatedSamplingRate,
8189 format,
8190 &updatedFormat,
8191 channelMask,
8192 &updatedChannelMask,
8193 // FIXME ugly cast
8194 (audio_output_flags_t) flags,
8195 false /*exactMatchRequiredForInputFlags*/)
8196 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008197 firstInexact = profile;
8198 }
8199 }
8200 }
8201
8202 if (firstInexact != nullptr) {
8203 samplingRate = updatedSamplingRate;
8204 format = updatedFormat;
8205 channelMask = updatedChannelMask;
8206 return firstInexact;
8207 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8208 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8209 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8210 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8211 flags = AUDIO_INPUT_FLAG_NONE;
8212 } else { // fail
8213 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8214 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8215 samplingRate, format, channelMask, oriFlags);
8216 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008217 }
8218 }
jiabin2fd710d2022-05-02 23:20:22 +00008219
8220 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008221}
8222
Vlad Popa87e0e582024-05-20 18:49:20 -07008223float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8224 VolumeSource volumeSource,
8225 int index,
8226 const DeviceTypeSet &deviceTypes)
8227{
8228 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8229 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8230 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8231
8232 if (com_android_media_audio_abs_volume_index_fix()) {
8233 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8234 mAbsoluteVolumeDrivingStreams.end()) {
8235 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8236 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8237 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8238 ALOGD("%s: no group matching with %s", __FUNCTION__,
8239 toString(attributesToDriveAbs).c_str());
8240 return volumeDb;
8241 }
8242
8243 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8244 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8245 if (vsToDriveAbs == volumeSource) {
8246 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008247 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008248 } else {
8249 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8250 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8251 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8252 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8253 curvesAbs.getVolumeIndexMax());
8254 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8255 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8256 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8257 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8258 return newVolumeDb;
8259 }
8260 }
8261 return volumeDb;
8262 } else {
8263 return volumeDb;
8264 }
8265}
8266
François Gaffieaaac0fd2018-11-22 17:56:39 +01008267float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8268 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008269 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008270 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008271 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008272 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008273{
Vlad Popa9d482762024-06-21 16:40:23 -07008274 float volumeDb;
8275 if (adjustAttenuation) {
8276 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8277 } else {
8278 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8279 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008280 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8281 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8282
8283 if (!computeInternalInteraction) {
8284 return volumeDb;
8285 }
8286
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008287 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8288 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8289 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8290 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008291 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8292 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8293 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8294 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8295 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008296 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008297 mOutputs.isActive(ringVolumeSrc, 0)) {
8298 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008299 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008300 adjustAttenuation,
8301 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008302 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008303 }
8304
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008305 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008306 if ((volumeSource != callVolumeSrc && (isInCall() ||
8307 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008308 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008309 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8310 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008311 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8312 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8313 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008314 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008315 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008316 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008317 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008318 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008319 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008320 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008321 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8322 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8323 // programmatically muted.
8324 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8325 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8326 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008327 bool exemptFromCapping =
8328 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8329 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008330 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8331 volumeSource, volumeDb);
8332 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008333 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8334 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8335 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008336 }
8337 }
Eric Laurente552edb2014-03-10 17:42:56 -07008338 // if a headset is connected, apply the following rules to ring tones and notifications
8339 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008340 // - always attenuate notifications volume by 6dB
8341 // - attenuate ring tones volume by 6dB unless music is not playing and
8342 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008343 // - if music is playing, always limit the volume to current music volume,
8344 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008345 if (!Intersection(deviceTypes,
8346 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8347 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008348 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8349 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008350 ((volumeSource == alarmVolumeSrc ||
8351 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008352 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8353 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8354 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008355 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8356 curves.canBeMuted()) {
8357
Eric Laurente552edb2014-03-10 17:42:56 -07008358 // when the phone is ringing we must consider that music could have been paused just before
8359 // by the music application and behave as if music was active if the last music track was
8360 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008361 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8362 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008363 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008364 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008365 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8366 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008367 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008368 float musicVolDb = computeVolume(musicCurves,
8369 musicVolumeSrc,
8370 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008371 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008372 adjustAttenuation,
8373 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008374 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8375 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8376 if (volumeDb > minVolDb) {
8377 volumeDb = minVolDb;
8378 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008379 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008380 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8381 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008382 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8383 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8384 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8385 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008386 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008387 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008388 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8389 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008390 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8391 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008392 }
8393 }
jiabin9a3361e2019-10-01 09:38:30 -07008394 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008395 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008396 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008397 }
8398 }
8399
François Gaffie43c73442018-11-08 08:21:55 +01008400 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008401}
8402
Eric Laurent3839bc02018-07-10 18:33:34 -07008403int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008404 VolumeSource fromVolumeSource,
8405 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008406{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008407 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008408 return srcIndex;
8409 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008410 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8411 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008412 float minSrc = (float)srcCurves.getVolumeIndexMin();
8413 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8414 float minDst = (float)dstCurves.getVolumeIndexMin();
8415 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008416
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008417 // preserve mute request or correct range
8418 if (srcIndex < minSrc) {
8419 if (srcIndex == 0) {
8420 return 0;
8421 }
8422 srcIndex = minSrc;
8423 } else if (srcIndex > maxSrc) {
8424 srcIndex = maxSrc;
8425 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008426 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8427}
8428
François Gaffieaaac0fd2018-11-22 17:56:39 +01008429status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8430 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008431 int index,
8432 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008433 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008434 int delayMs,
8435 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008436{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008437 // APM is single threaded, and single instance.
8438 static std::set<IVolumeCurves*> invalidCurvesReported;
8439
François Gaffieaaac0fd2018-11-22 17:56:39 +01008440 // do not change actual attributes volume if the attributes is muted
8441 if (outputDesc->isMuted(volumeSource)) {
8442 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8443 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008444 return NO_ERROR;
8445 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008446
Eric Laurentae6e88c2024-01-10 14:42:57 +01008447 bool isVoiceVolSrc;
8448 bool isBtScoVolSrc;
8449 if (!isVolumeConsistentForCalls(
8450 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008451 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008452 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008453 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008454 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008455
jiabin9a3361e2019-10-01 09:38:30 -07008456 if (deviceTypes.empty()) {
8457 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008458 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008459 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008460 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008461 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008462
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008463 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008464 if (!invalidCurvesReported.count(&curves)) {
8465 invalidCurvesReported.insert(&curves);
8466 String8 dump;
8467 curves.dump(&dump);
8468 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8469 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008470 return BAD_VALUE;
8471 }
8472
jiabin9a3361e2019-10-01 09:38:30 -07008473 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8474 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008475 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008476 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008477 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8478 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008479 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008480 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008481 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008482 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8483 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008484
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008485 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008486 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8487 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8488 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008489 }
Eric Laurente552edb2014-03-10 17:42:56 -07008490 return NO_ERROR;
8491}
8492
Eric Laurentae6e88c2024-01-10 14:42:57 +01008493void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008494 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008495 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008496 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008497 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008498 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008499 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8500 } else {
8501 voiceVolume = index == 0 ? 0.0 : 1.0;
8502 }
8503 if (voiceVolume != mLastVoiceVolume) {
8504 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8505 mLastVoiceVolume = voiceVolume;
8506 }
8507}
8508
8509bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8510 const DeviceTypeSet& deviceTypes,
8511 bool& isVoiceVolSrc,
8512 bool& isBtScoVolSrc,
8513 const char* caller) {
8514 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008515 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8516
Eric Laurentae6e88c2024-01-10 14:42:57 +01008517 const bool isScoRequested = isScoRequestedForComm();
8518 const bool isHAUsed = isHearingAidUsedForComm();
8519
Vlad Popa695b76b2024-06-14 16:49:25 -07008520 if (com_android_media_audio_replace_stream_bt_sco()) {
8521 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8522 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8523 (isScoRequested || isHAUsed);
8524 return true;
8525 }
8526
8527 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008528 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8529
8530 if ((callVolSrc != btScoVolSrc) &&
8531 ((isVoiceVolSrc && isScoRequested) ||
8532 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8533 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8534 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8535 volumeSource, isScoRequested ? " " : " not ");
8536 return false;
8537 }
8538 return true;
8539}
8540
Eric Laurentc75307b2015-03-17 15:29:32 -07008541void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008542 const DeviceTypeSet& deviceTypes,
8543 int delayMs,
8544 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008545{
jiabincd510522020-01-22 09:40:55 -08008546 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008547 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8548 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8549 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008550 curves.getVolumeIndex(deviceTypes),
8551 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008552 }
8553}
8554
François Gaffiec005e562018-11-06 15:04:49 +01008555void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8556 bool on,
8557 const sp<AudioOutputDescriptor>& outputDesc,
8558 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008559 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008560{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008561 std::vector<VolumeSource> sourcesToMute;
8562 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8563 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8564 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008565 VolumeSource source = toVolumeSource(attributes, false);
8566 if ((source != VOLUME_SOURCE_NONE) &&
8567 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8568 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008569 sourcesToMute.push_back(source);
8570 }
Eric Laurente552edb2014-03-10 17:42:56 -07008571 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008572 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008573 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008574 }
8575
Eric Laurente552edb2014-03-10 17:42:56 -07008576}
8577
François Gaffieaaac0fd2018-11-22 17:56:39 +01008578void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8579 bool on,
8580 const sp<AudioOutputDescriptor>& outputDesc,
8581 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008582 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008583{
jiabin9a3361e2019-10-01 09:38:30 -07008584 if (deviceTypes.empty()) {
8585 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008586 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008587 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008588 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008589 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008590 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008591 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008592 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8593 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008594 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008595 }
8596 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008597 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8598 // ignored
8599 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008600 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008601 if (!outputDesc->isMuted(volumeSource)) {
8602 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008603 return;
8604 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008605 if (outputDesc->decMuteCount(volumeSource) == 0) {
8606 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008607 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008608 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008609 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008610 delayMs);
8611 }
8612 }
8613}
8614
François Gaffie53615e22015-03-19 09:24:12 +01008615bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8616{
François Gaffiec005e562018-11-06 15:04:49 +01008617 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008618 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8619 return true;
8620 }
8621
8622 // has known usage?
8623 switch (paa->usage) {
8624 case AUDIO_USAGE_UNKNOWN:
8625 case AUDIO_USAGE_MEDIA:
8626 case AUDIO_USAGE_VOICE_COMMUNICATION:
8627 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8628 case AUDIO_USAGE_ALARM:
8629 case AUDIO_USAGE_NOTIFICATION:
8630 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8631 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8632 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8633 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8634 case AUDIO_USAGE_NOTIFICATION_EVENT:
8635 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8636 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8637 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8638 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008639 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008640 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008641 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008642 case AUDIO_USAGE_EMERGENCY:
8643 case AUDIO_USAGE_SAFETY:
8644 case AUDIO_USAGE_VEHICLE_STATUS:
8645 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008646 break;
8647 default:
8648 return false;
8649 }
8650 return true;
8651}
8652
François Gaffie2110e042015-03-24 08:41:51 +01008653audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8654{
8655 return mEngine->getForceUse(usage);
8656}
8657
Eric Laurent96d1dda2022-03-14 17:14:19 +01008658bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008659 return isStateInCall(mEngine->getPhoneState());
8660}
8661
Eric Laurent96d1dda2022-03-14 17:14:19 +01008662bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008663 return is_state_in_call(state);
8664}
8665
Eric Laurentf9cccec2022-11-16 19:12:00 +01008666bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008667 audio_mode_t mode = mEngine->getPhoneState();
8668 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008669 || (mode == AUDIO_MODE_CALL_SCREEN)
8670 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008671}
8672
Eric Laurentf9cccec2022-11-16 19:12:00 +01008673bool AudioPolicyManager::isInCallOrScreening() const {
8674 audio_mode_t mode = mEngine->getPhoneState();
8675 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8676}
8677
Eric Laurentd60560a2015-04-10 11:31:20 -07008678void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8679{
8680 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008681 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008682 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008683 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008684 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008685 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008686 }
8687 }
8688
8689 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8690 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8691 bool release = false;
8692 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8693 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8694 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8695 source->ext.device.type == deviceDesc->type()) {
8696 release = true;
8697 }
8698 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008699 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008700 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8701 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8702 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008703 sink->ext.device.type == deviceDesc->type() &&
8704 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8705 || strncmp(sink->ext.device.address, address,
8706 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008707 release = true;
8708 }
8709 }
8710 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008711 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8712 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008713 }
8714 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008715
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008716 mInputs.clearSessionRoutesForDevice(deviceDesc);
8717
Francois Gaffie716e1432019-01-14 16:58:59 +01008718 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008719}
8720
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008721void AudioPolicyManager::modifySurroundFormats(
8722 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008723 std::unordered_set<audio_format_t> enforcedSurround(
8724 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008725 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008726 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008727 allSurround.insert(pair.first);
8728 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8729 }
Phil Burk09bc4612016-02-24 15:58:15 -08008730
8731 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8732 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008733 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008734 // This is the resulting set of formats depending on the surround mode:
8735 // 'all surround' = allSurround
8736 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8737 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8738 // 'manual surround' = mManualSurroundFormats
8739 // AUTO: formats v 'enforced surround'
8740 // ALWAYS: formats v 'all surround' v 'enforced surround'
8741 // NEVER: formats ^ 'non-surround'
8742 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008743
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008744 std::unordered_set<audio_format_t> formatSet;
8745 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8746 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008747 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008748 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008749 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008750 formatSet.insert(*formatIter);
8751 }
8752 }
8753 } else {
8754 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8755 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008756 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008757
jiabin81772902018-04-02 17:52:27 -07008758 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008759 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008760 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8761 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8762 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008763 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008764 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8765 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8766 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008767 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008768 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008769 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008770 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008771 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008772 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008773}
8774
jiabin06e4bab2019-07-29 10:13:34 -07008775void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8776 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008777 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8778 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8779
8780 // If NEVER, then remove support for channelMasks > stereo.
8781 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008782 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8783 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008784 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008785 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008786 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008787 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008788 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008789 }
8790 }
jiabin81772902018-04-02 17:52:27 -07008791 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8792 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8793 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008794 bool supports5dot1 = false;
8795 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008796 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008797 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8798 supports5dot1 = true;
8799 break;
8800 }
8801 }
8802 // If not then add 5.1 support.
8803 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008804 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008805 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008806 }
Phil Burk09bc4612016-02-24 15:58:15 -08008807 }
8808}
8809
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008810void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008811 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008812 const sp<IOProfile>& profile) {
8813 if (!profile->hasDynamicAudioProfile()) {
8814 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008815 }
François Gaffie112b0af2015-11-19 16:13:25 +01008816
jiabin12537fc2023-10-12 17:56:08 +00008817 audio_port_v7 devicePort;
8818 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008819
jiabin12537fc2023-10-12 17:56:08 +00008820 audio_port_v7 mixPort;
8821 profile->toAudioPort(&mixPort);
8822 mixPort.ext.mix.handle = ioHandle;
8823
8824 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8825 if (status != NO_ERROR) {
8826 ALOGE("%s failed to query the attributes of the mix port", __func__);
8827 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008828 }
jiabin12537fc2023-10-12 17:56:08 +00008829
8830 std::set<audio_format_t> supportedFormats;
8831 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8832 supportedFormats.insert(mixPort.audio_profiles[i].format);
8833 }
8834 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8835 mReportedFormatsMap[devDesc] = formats;
8836
8837 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8838 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8839 modifySurroundFormats(devDesc, &formats);
8840 size_t modifiedNumProfiles = 0;
8841 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8842 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8843 formats.end()) {
8844 // Skip the format that is not present after modifying surround formats.
8845 continue;
8846 }
8847 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8848 sizeof(struct audio_profile));
8849 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8850 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8851 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8852 modifySurroundChannelMasks(&channels);
8853 std::copy(channels.begin(), channels.end(),
8854 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8855 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8856 }
8857 mixPort.num_audio_profiles = modifiedNumProfiles;
8858 }
8859 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008860}
Eric Laurentd60560a2015-04-10 11:31:20 -07008861
Mikhail Naganovdc769682018-05-04 15:34:08 -07008862status_t AudioPolicyManager::installPatch(const char *caller,
8863 audio_patch_handle_t *patchHandle,
8864 AudioIODescriptorInterface *ioDescriptor,
8865 const struct audio_patch *patch,
8866 int delayMs)
8867{
8868 ssize_t index = mAudioPatches.indexOfKey(
8869 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8870 *patchHandle : ioDescriptor->getPatchHandle());
8871 sp<AudioPatch> patchDesc;
8872 status_t status = installPatch(
8873 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8874 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008875 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008876 }
8877 return status;
8878}
8879
8880status_t AudioPolicyManager::installPatch(const char *caller,
8881 ssize_t index,
8882 audio_patch_handle_t *patchHandle,
8883 const struct audio_patch *patch,
8884 int delayMs,
8885 uid_t uid,
8886 sp<AudioPatch> *patchDescPtr)
8887{
8888 sp<AudioPatch> patchDesc;
8889 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8890 if (index >= 0) {
8891 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008892 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008893 }
8894
8895 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8896 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8897 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8898 if (status == NO_ERROR) {
8899 if (index < 0) {
8900 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008901 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008902 } else {
8903 patchDesc->mPatch = *patch;
8904 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008905 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008906 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008907 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008908 }
8909 nextAudioPortGeneration();
8910 mpClientInterface->onAudioPatchListUpdate();
8911 }
8912 if (patchDescPtr) *patchDescPtr = patchDesc;
8913 return status;
8914}
8915
jiabinbce0c1d2020-10-05 11:20:18 -07008916bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8917{
8918 const TrackClientVector activeClients = output->getActiveClients();
8919 if (activeClients.empty()) {
8920 return true;
8921 }
8922 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8923 if (index < 0) {
8924 ALOGE("%s, no audio patch found while there are active clients on output %d",
8925 __func__, output->getId());
8926 return false;
8927 }
8928 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8929 DeviceVector routedDevices;
8930 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8931 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8932 patchDesc->mPatch.sinks[i].id);
8933 if (device == nullptr) {
8934 ALOGE("%s, no audio device found with id(%d)",
8935 __func__, patchDesc->mPatch.sinks[i].id);
8936 return false;
8937 }
8938 routedDevices.add(device);
8939 }
8940 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008941 if (client->isInvalid()) {
8942 // No need to take care about invalidated clients.
8943 continue;
8944 }
jiabinbce0c1d2020-10-05 11:20:18 -07008945 sp<DeviceDescriptor> preferredDevice =
8946 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8947 if (mEngine->getOutputDevicesForAttributes(
8948 client->attributes(), preferredDevice, false) == routedDevices) {
8949 return false;
8950 }
8951 }
8952 return true;
8953}
8954
8955sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008956 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008957 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8958 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008959{
8960 for (const auto& device : devices) {
8961 // TODO: This should be checking if the profile supports the device combo.
8962 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008963 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8964 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008965 return nullptr;
8966 }
8967 }
8968 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8969 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07008970 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008971 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07008972 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008973 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008974 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008975 return nullptr;
8976 }
jiabin14b50cc2023-12-13 19:01:52 +00008977 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8978 auto portConfig = desc->getConfig();
8979 for (const auto& device : devices) {
8980 device->setPreferredConfig(&portConfig);
8981 }
8982 }
jiabinbce0c1d2020-10-05 11:20:18 -07008983
8984 // Here is where the out_set_parameters() for card & device gets called
8985 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8986 const audio_devices_t deviceType = device->type();
8987 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008988 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008989 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8990 mpClientInterface->setParameters(output, String8(param));
8991 free(param);
8992 }
jiabin12537fc2023-10-12 17:56:08 +00008993 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008994 if (!profile->hasValidAudioProfile()) {
8995 ALOGW("%s() missing param", __func__);
8996 desc->close();
8997 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008998 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8999 // Reopen the output with the best audio profile picked by APM when the profile supports
9000 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009001 desc->close();
9002 output = AUDIO_IO_HANDLE_NONE;
9003 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9004 profile->pickAudioProfile(
9005 config.sample_rate, config.channel_mask, config.format);
9006 config.offload_info.sample_rate = config.sample_rate;
9007 config.offload_info.channel_mask = config.channel_mask;
9008 config.offload_info.format = config.format;
9009
Haofan Wangf6e304f2024-07-09 23:06:58 -07009010 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
9011 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009012 if (status != NO_ERROR) {
9013 return nullptr;
9014 }
9015 }
9016
9017 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00009018 setOutputDevices(__func__, desc,
9019 devices,
9020 true,
9021 0,
9022 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00009023 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9024 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9025
jiabinbce0c1d2020-10-05 11:20:18 -07009026 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9027 sp<AudioPolicyMix> policyMix;
9028 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9029 policyMix->setOutput(desc);
9030 desc->mPolicyMix = policyMix;
9031 } else {
9032 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009033 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009034 }
9035
baek.kim -61c20122022-07-27 10:05:32 +00009036 } else if (hasPrimaryOutput() && speaker != nullptr
9037 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009038 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9039 // no duplicated output for:
9040 // - direct outputs
9041 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009042 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009043 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9044
9045 //TODO: configure audio effect output stage here
9046
9047 // open a duplicating output thread for the new output and the primary output
9048 sp<SwAudioOutputDescriptor> dupOutputDesc =
9049 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9050 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9051 if (status == NO_ERROR) {
9052 // add duplicated output descriptor
9053 addOutput(duplicatedOutput, dupOutputDesc);
9054 } else {
9055 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9056 mPrimaryOutput->mIoHandle, output);
9057 desc->close();
9058 removeOutput(output);
9059 nextAudioPortGeneration();
9060 return nullptr;
9061 }
9062 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009063 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9064 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9065 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009066 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009067 }
jiabinbce0c1d2020-10-05 11:20:18 -07009068 return desc;
9069}
9070
jiabinf1c73972022-04-14 16:28:52 -07009071status_t AudioPolicyManager::getDevicesForAttributes(
9072 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009073 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9074 // over any usage or content type also present in attr.
9075 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9076 attr.source != AUDIO_SOURCE_INVALID) {
9077 return getInputDevicesForAttributes(attr, devices);
9078 }
9079
jiabinf1c73972022-04-14 16:28:52 -07009080 // Devices are determined in the following precedence:
9081 //
9082 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9083 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9084 //
9085 // If no such dynamic policy then
9086 // 2) Devices containing an active client using setPreferredDevice
9087 // with same strategy as the attributes.
9088 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9089 //
9090 // If no corresponding active client with setPreferredDevice then
9091 // 3) Devices associated with the strategy determined by the attributes
9092 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9093 //
9094 // See related getOutputForAttrInt().
9095
9096 // check dynamic policies but only for primary descriptors (secondary not used for audible
9097 // audio routing, only used for duplication for playback capture)
9098 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009099 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009100 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009101 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9102 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9103 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009104 if (status != OK) {
9105 return status;
9106 }
9107
9108 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9109 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9110 // as they are unaffected by device/stream volume
9111 // (per SwAudioOutputDescriptor::isFixedVolume()).
9112 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9113 ) {
9114 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9115 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9116 devices.add(deviceDesc);
9117 } else {
9118 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9119 // which selects setPreferredDevice if active. This means forVolume call
9120 // will take an active setPreferredDevice, if such exists.
9121
9122 devices = mEngine->getOutputDevicesForAttributes(
9123 attr, nullptr /* preferredDevice */, false /* fromCache */);
9124 }
9125
9126 if (forVolume) {
9127 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9128 // for single volume control in AudioService (such relationship should exist if
9129 // SPEAKER_SAFE is present).
9130 //
9131 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9132 DeviceVector speakerSafeDevices =
9133 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9134 if (!speakerSafeDevices.isEmpty()) {
9135 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9136 devices.remove(speakerSafeDevices);
9137 }
9138 }
9139
9140 return NO_ERROR;
9141}
9142
wenyu zhang8558a332024-09-09 15:12:48 +00009143status_t AudioPolicyManager::getInputDevicesForAttributes(
9144 const audio_attributes_t &attr, DeviceVector &devices) {
9145 devices = DeviceVector(
9146 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9147 AUDIO_SESSION_NONE,
9148 nullptr /* mix */));
9149 return NO_ERROR;
9150}
9151
jiabinf1c73972022-04-14 16:28:52 -07009152status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9153 AudioProfileVector& audioProfiles,
9154 uint32_t flags,
9155 bool isInput) {
9156 for (const auto& hwModule : mHwModules) {
9157 // the MSD module checks for different conditions
9158 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9159 continue;
9160 }
9161 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9162 : hwModule->getOutputProfiles();
9163 for (const auto& profile : ioProfiles) {
9164 if (!profile->areAllDevicesSupported(devices) ||
9165 !profile->isCompatibleProfileForFlags(
9166 flags, false /*exactMatchRequiredForInputFlags*/)) {
9167 continue;
9168 }
9169 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9170 }
9171 }
9172
9173 if (!isInput) {
9174 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9175 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9176 if (msdModule != nullptr) {
9177 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9178 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9179 for (const auto &profile: msdModule->getOutputProfiles()) {
9180 if (!profile->asAudioPort()->isDirectOutput()) {
9181 continue;
9182 }
9183 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9184 }
9185 } else {
9186 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9187 }
9188 }
9189 }
9190
9191 return NO_ERROR;
9192}
9193
jiabin3ff8d7d2022-12-13 06:27:44 +00009194sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9195 const audio_config_t *config,
9196 audio_output_flags_t flags,
9197 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009198 closeOutput(outputDesc->mIoHandle);
9199 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9200 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9201 if (preferredOutput == nullptr) {
9202 ALOGE("%s failed to reopen output device=%d, caller=%s",
9203 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009204 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009205 return preferredOutput;
9206}
9207
9208void AudioPolicyManager::reopenOutputsWithDevices(
9209 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9210 for (const auto& [output, devices] : outputsToReopen) {
9211 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9212 closeOutput(output);
9213 openOutputWithProfileAndDevice(desc->mProfile, devices);
9214 }
jiabina84c3d32022-12-02 18:59:55 +00009215}
9216
jiabinc44b3462022-12-08 12:52:31 -08009217PortHandleVector AudioPolicyManager::getClientsForStream(
9218 audio_stream_type_t streamType) const {
9219 PortHandleVector clients;
9220 for (size_t i = 0; i < mOutputs.size(); ++i) {
9221 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9222 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9223 }
9224 return clients;
9225}
9226
9227void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9228 PortHandleVector clients;
9229 for (auto stream : streams) {
9230 PortHandleVector clientsForStream = getClientsForStream(stream);
9231 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9232 }
9233 mpClientInterface->invalidateTracks(clients);
9234}
9235
jiabin220eea12024-05-17 17:55:20 +00009236void AudioPolicyManager::updateClientsInternalMute(
9237 const sp<android::SwAudioOutputDescriptor> &desc) {
9238 if (!desc->isBitPerfect() ||
9239 !com::android::media::audioserver::
9240 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9241 // This is only used for bit perfect output now.
9242 return;
9243 }
9244 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9245 bool bitPerfectClientInternalMute = false;
9246 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9247 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9248 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9249 bitPerfectClient = client;
9250 continue;
9251 }
9252 bool muted = false;
9253 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9254 // System sound is muted.
9255 muted = true;
9256 } else {
9257 bitPerfectClientInternalMute = true;
9258 }
9259 if (client->setInternalMute(muted)) {
9260 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9261 if (!result.ok()) {
9262 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9263 continue;
9264 }
9265 media::TrackInternalMuteInfo info;
9266 info.portId = result.value();
9267 info.muted = client->getInternalMute();
9268 clientsInternalMute.push_back(std::move(info));
9269 }
9270 }
9271 if (bitPerfectClient != nullptr &&
9272 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9273 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9274 if (result.ok()) {
9275 media::TrackInternalMuteInfo info;
9276 info.portId = result.value();
9277 info.muted = bitPerfectClient->getInternalMute();
9278 clientsInternalMute.push_back(std::move(info));
9279 } else {
9280 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9281 __func__, bitPerfectClient->portId());
9282 }
9283 }
9284 if (!clientsInternalMute.empty()) {
9285 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9286 status != NO_ERROR) {
9287 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9288 }
9289 }
9290}
9291
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009292} // namespace android