blob: e27eba8b83332b508d070053d47b02e4e5bb4958 [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 Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
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
François Gaffie11d30102018-11-02 16:09:09 +0100126void 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);
jiabinc0048632023-04-27 22:04:31 +0000131 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000132 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700133 ALOGE("Error %d while setting connected state %d for device %s",
134 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000135 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...)
jiabinc0048632023-04-27 22:04:31 +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();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
393 if (mAvailableInputDevices.add(device) < 0) {
394 return NO_MEMORY;
395 }
396
François Gaffie44481e72016-04-20 07:49:57 +0200397 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
398 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000399 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700400 // Propagate device availability to Engine
401 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200402
Eric Laurent0dd51852019-04-19 18:18:58 -0700403 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700404 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 mAvailableInputDevices.remove(device);
407
jiabinc0048632023-04-27 22:04:31 +0000408 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100409
410 mHwModules.cleanUpForDevice(device);
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 return INVALID_OPERATION;
413 }
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700418 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700419 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100420 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700421 return INVALID_OPERATION;
422 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700423
François Gaffie11d30102018-11-02 16:09:09 +0100424 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
jiabinc0048632023-04-27 22:04:31 +0000426 // Notify the HAL to prepare to disconnect device
427 broadcastDeviceConnectionState(
428 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700429
François Gaffie11d30102018-11-02 16:09:09 +0100430 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700431
432 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100433
jiabinc0048632023-04-27 22:04:31 +0000434 // Set Disconnect to HALs
435 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
436
Kriti Dangef6be8f2020-11-05 11:58:19 +0100437 // remove device from mReportedFormatsMap cache
438 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700439
440 // Propagate device availability to Engine
441 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700442 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700443
444 default:
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700446 return BAD_VALUE;
447 }
448
Eric Laurent0dd51852019-04-19 18:18:58 -0700449 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700450 // As the input device list can impact the output device selection, update
451 // getDeviceForStrategy() cache
452 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700453
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100454 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200455 // Reconnect Audio Source
456 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
457 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
458 checkAudioSourceForAttributes(attributes);
459 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700460 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100461 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 }
463
Eric Laurentb52c1522014-05-20 11:27:36 -0700464 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700465 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700466 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700467
François Gaffie11d30102018-11-02 16:09:09 +0100468 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return BAD_VALUE;
470}
471
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100472status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
473 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800474 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700475 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
476 devDescr->setName(device_name);
477 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100478}
479
Eric Laurent736a1022019-03-27 18:28:46 -0700480void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
481 audio_policy_dev_state_t state) {
482
483 // the Engine does not have to know about remote submix devices used by dynamic audio policies
484 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
485 return;
486 }
487 mEngine->setDeviceConnectionState(device, state);
488}
489
490
Eric Laurente0720872014-03-11 09:30:41 -0700491audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100492 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700493{
Eric Laurent634b7142016-04-20 13:48:02 -0700494 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
496 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700497 (strlen(device_address) != 0)/*matchAddress*/);
498
499 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100500 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700501 device, device_address);
502 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
503 }
François Gaffie53615e22015-03-19 09:24:12 +0100504
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 DeviceVector *deviceVector;
506
Eric Laurente552edb2014-03-10 17:42:56 -0700507 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700510 deviceVector = &mAvailableInputDevices;
511 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100512 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700514 }
Eric Laurent634b7142016-04-20 13:48:02 -0700515
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 return (deviceVector->getDevice(
517 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800519}
520
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
522 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 const char *device_name,
524 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
527 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800529 // connect/disconnect only 1 device at a time
530 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
531
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700533 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Nothing to do: device is not connected
536 return NO_ERROR;
537 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700540 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 // configure codecs.
542 // Handle two specific cases by sending a set parameter to
543 // configure A2DP codecs. No need to toggle device state.
544 // Case 1: A2DP active device switches from primary to primary
545 // module
546 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700548 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800549 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
550 if (availablePrimaryOutputDevices().contains(devDesc) &&
551 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 bool isA2dp = audio_is_a2dp_out_device(device);
553 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
554 : String8(AudioParameter::keyReconfigLeSupported);
555 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100557 int isReconfigSupported;
558 repliedParameters.getInt(supportKey, isReconfigSupported);
559 if (isReconfigSupported) {
560 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
561 : String8(AudioParameter::keyReconfigLe);
562 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 param.add(key, String8("true"));
564 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
565 devDesc->setEncodedFormat(encodedFormat);
566 return NO_ERROR;
567 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700568 }
569 }
cnx421bd2dcc42020-07-11 14:58:44 +0800570 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000571 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800572 for (size_t i = 0; i < mOutputs.size(); i++) {
573 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000574 // mute media strategies to avoid sending the music tail into
575 // the earpiece or headset.
576 if (desc->isStrategyActive(musicStrategy)) {
577 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
578 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
579 tempRecommendedMuteDuration : desc->latency() * 4;
580 if (muteWaitMs < tempMuteDurationMs) {
581 muteWaitMs = tempMuteDurationMs;
582 }
583 }
cnx421bd2dcc42020-07-11 14:58:44 +0800584 setStrategyMute(musicStrategy, true, desc);
585 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
586 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
587 nullptr, true /*fromCache*/).types());
588 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000589 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
590 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
591 // happens after the actual device switch.
592 if (muteWaitMs > 0) {
593 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
594 usleep(muteWaitMs * 1000);
595 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800596 // Toggle the device state: UNAVAILABLE -> AVAILABLE
597 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100598 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800600 device_address, device_name,
601 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 if (status != NO_ERROR) {
603 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
604 status);
605 return status;
606 }
607
608 status = setDeviceConnectionState(device,
609 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800610 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800611 if (status != NO_ERROR) {
612 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
613 status);
614 return status;
615 }
616
617 return NO_ERROR;
618}
619
Pattydd807582021-11-04 21:01:03 +0800620status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
621 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622{
Pattydd807582021-11-04 21:01:03 +0800623 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800624 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 std::unordered_set<audio_format_t> formatSet;
626 sp<HwModule> primaryModule =
627 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700628 if (primaryModule == nullptr) {
629 ALOGE("%s() unable to get primary module", __func__);
630 return NO_INIT;
631 }
Pattydd807582021-11-04 21:01:03 +0800632
633 DeviceTypeSet audioDeviceSet;
634
635 switch(device) {
636 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
637 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
638 break;
639 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800640 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
643 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800644 break;
645 default:
646 ALOGE("%s() device type 0x%08x not supported", __func__, device);
647 return BAD_VALUE;
648 }
649
jiabin9a3361e2019-10-01 09:38:30 -0700650 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800651 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800652 for (const auto& device : declaredDevices) {
653 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800654 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800656 return status;
657}
658
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100659DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
660{
661 DeviceVector rxSinkdevices{};
662 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
663 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
664 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
665 auto rxSinkDevice = rxSinkdevices.itemAt(0);
666 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
667 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
668 // retrieve Rx Source device descriptor
669 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
671
672 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
673 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
674 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
675 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
676 return DeviceVector(rxSinkDevice);
677 }
678 }
679 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
680 // the device returned is not necessarily reachable via this output
681 // (filter later by setOutputDevices())
682 return getNewOutputDevices(mPrimaryOutput, fromCache);
683}
684
685status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
686{
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100688 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
689 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
690 }
691 return INVALID_OPERATION;
692}
693
694status_t AudioPolicyManager::updateCallRoutingInternal(
695 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696{
697 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100698 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700699 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200700 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700701 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100702 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700703 }
François Gaffie11d30102018-11-02 16:09:09 +0100704
Francois Gaffie716e1432019-01-14 16:58:59 +0100705 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100706 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200707
Eric Laurentb2fb4102024-06-21 12:25:26 +0000708 if (!fix_call_audio_patch()) {
709 disconnectTelephonyAudioSource(mCallRxSourceClient);
710 disconnectTelephonyAudioSource(mCallTxSourceClient);
711 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200712
713 if (rxDevices.isEmpty()) {
714 ALOGW("%s() no selected output device", __func__);
715 return INVALID_OPERATION;
716 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000717 if (txSourceDevice == nullptr) {
718 ALOGE("%s() selected input device not available", __func__);
719 return INVALID_OPERATION;
720 }
François Gaffiec005e562018-11-06 15:04:49 +0100721
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100722 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100723 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724
François Gaffie9eb18552018-11-05 10:33:26 +0100725 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700726 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100727 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700728 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100729 // retrieve Rx Source and Tx Sink device descriptors
730 sp<DeviceDescriptor> rxSourceDevice =
731 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
732 String8(),
733 AUDIO_FORMAT_DEFAULT);
734 sp<DeviceDescriptor> txSinkDevice =
735 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738
739 // RX and TX Telephony device are declared by Primary Audio HAL
740 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
741 (telephonyRxModule->getHalVersionMajor() >= 3)) {
742 if (rxSourceDevice == 0 || txSinkDevice == 0) {
743 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGE("%s() no telephony Tx and/or RX device", __func__);
745 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100746 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100747 // createAudioPatchInternal now supports both HW / SW bridging
748 createRxPatch = true;
749 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 } else {
751 // If the RX device is on the primary HW module, then use legacy routing method for
752 // voice calls via setOutputDevice() on primary output.
753 // Otherwise, create two audio patches for TX and RX path.
754 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
755 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700756 // If the TX device is also on the primary HW module, setOutputDevice() will take care
757 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100758 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
759 (txSinkDevice != 0);
760 }
761 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
762 // Otherwise, create two audio patches for TX and RX path.
763 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000764 if (fix_call_audio_patch()) {
765 disconnectTelephonyAudioSource(mCallRxSourceClient);
766 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200767 if (!hasPrimaryOutput()) {
768 ALOGW("%s() no primary output available", __func__);
769 return INVALID_OPERATION;
770 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530771 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700772 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200773 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800774 // If the TX device is on the primary HW module but RX device is
775 // on other HW module, SinkMetaData of telephony input should handle it
776 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700778 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100779 // terminate active capture if on the same HW module as the call TX source device
780 // FIXME: would be better to refine to only inputs whose profile connects to the
781 // call TX device but this information is not in the audio patch and logic here must be
782 // symmetric to the one in startInput()
783 for (const auto& activeDesc : mInputs.getActiveInputs()) {
784 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
785 closeActiveClients(activeDesc);
786 }
787 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000789 } else if (fix_call_audio_patch()) {
790 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800791 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100792 if (waitMs != nullptr) {
793 *waitMs = muteWaitMs;
794 }
795 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800796}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700797
Mikhail Naganov100f0122018-11-29 11:22:16 -0800798bool AudioPolicyManager::isDeviceOfModule(
799 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
800 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
801 if (module != 0) {
802 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
803 .indexOf(devDesc) != NAME_NOT_FOUND
804 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
805 .indexOf(devDesc) != NAME_NOT_FOUND;
806 }
807 return false;
808}
809
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200810void AudioPolicyManager::connectTelephonyRxAudioSource()
811{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000812 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
813
814 if (fix_call_audio_patch()) {
815 if (mCallRxSourceClient != nullptr) {
816 DeviceVector rxDevices =
817 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
818 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
819 "connectTelephonyRxAudioSource(): no device found for call RX source");
820 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
821 if (mCallRxSourceClient->isConnected()
822 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
823 return;
824 }
825 disconnectTelephonyAudioSource(mCallRxSourceClient);
826 }
827 } else {
828 disconnectTelephonyAudioSource(mCallRxSourceClient);
829 }
830
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200831 const struct audio_port_config source = {
832 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
833 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
834 };
Eric Laurent541a2002024-01-15 18:11:42 +0100835 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000836
Eric Laurentccbd7872024-06-20 12:34:15 +0000837 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
838 true /*internal*/, true /*isCallRx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100839 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
840 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000841 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
842 mCallRxSourceClient->srcDevice()->toString().c_str(),
843 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200844 ALOGE_IF(mCallRxSourceClient == nullptr,
845 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200846}
847
Francois Gaffie601801d2021-06-22 13:27:39 +0200848void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200849{
Francois Gaffie601801d2021-06-22 13:27:39 +0200850 if (clientDesc == nullptr) {
851 return;
852 }
853 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
854 "%s error stopping audio source", __func__);
855 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200856}
857
858void AudioPolicyManager::connectTelephonyTxAudioSource(
859 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
860 uint32_t delayMs)
861{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200862 if (srcDevice == nullptr || sinkDevice == nullptr) {
863 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
864 return;
865 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000866
867 if (fix_call_audio_patch()) {
868 if (mCallTxSourceClient != nullptr) {
869 if (mCallTxSourceClient->isConnected()
870 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
871 return;
872 }
873 disconnectTelephonyAudioSource(mCallTxSourceClient);
874 }
875 } else {
876 disconnectTelephonyAudioSource(mCallTxSourceClient);
877 }
878
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200879 PatchBuilder patchBuilder;
880 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000881
Francois Gaffie601801d2021-06-22 13:27:39 +0200882 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200883 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
884
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200885 struct audio_port_config source = {};
886 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100887 mCallTxSourceClient = new SourceClientDescriptor(
888 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000889 mCommunnicationStrategy, toVolumeSource(aa), true,
890 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
892
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200893 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
894 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200895 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
896 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000898 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
899 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200900 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200901 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200902 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200903}
904
Eric Laurente0720872014-03-11 09:30:41 -0700905void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700906{
907 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100908 // store previous phone state for management of sonification strategy below
909 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100910 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100911
912 if (mEngine->setPhoneState(state) != NO_ERROR) {
913 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700914 return;
915 }
François Gaffie2110e042015-03-24 08:41:51 +0100916 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700917 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700918 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700919 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800920 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
François Gaffie2110e042015-03-24 08:41:51 +0100923 /**
924 * Switching to or from incall state or switching between telephony and VoIP lead to force
925 * routing command.
926 */
Eric Laurent74b71512019-11-06 17:21:57 -0800927 bool force = ((isStateInCall(oldState) != isStateInCall(state))
928 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700929
930 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700931 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700932
Eric Laurente552edb2014-03-10 17:42:56 -0700933 int delayMs = 0;
934 if (isStateInCall(state)) {
935 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100936 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
937 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 // mute media and sonification strategies and delay device switch by the largest
941 // latency of any output where either strategy is active.
942 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100943 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
944 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
945 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700946 (delayMs < (int)desc->latency()*2)) {
947 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700948 }
François Gaffiec005e562018-11-06 15:04:49 +0100949 setStrategyMute(musicStrategy, true, desc);
950 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
951 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
952 nullptr, true /*fromCache*/).types());
953 setStrategyMute(sonificationStrategy, true, desc);
954 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
956 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700957 }
958 }
959
François Gaffiedb1755b2023-09-01 11:50:35 +0200960 if (state == AUDIO_MODE_IN_CALL) {
961 (void)updateCallRouting(false /*fromCache*/, delayMs);
962 } else {
963 if (oldState == AUDIO_MODE_IN_CALL) {
964 disconnectTelephonyAudioSource(mCallRxSourceClient);
965 disconnectTelephonyAudioSource(mCallTxSourceClient);
966 }
967 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100968 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
969 // force routing command to audio hardware when ending call
970 // even if no device change is needed
971 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
972 rxDevices = mPrimaryOutput->devices();
973 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530974 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700975 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700976 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700977
jiabin3ff8d7d2022-12-13 06:27:44 +0000978 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700979 // reevaluate routing on all outputs in case tracks have been started during the call
980 for (size_t i = 0; i < mOutputs.size(); i++) {
981 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100982 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000983 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
984 && desc->mPreferredAttrInfo != nullptr) {
985 // If the output is using preferred mixer attributes and the audio mode is not normal,
986 // the output need to reopen with default configuration.
987 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
988 continue;
989 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200990 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
991 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530992 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200993 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700994 }
995 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000996 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700997
Eric Laurent96d1dda2022-03-14 17:14:19 +0100998 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
999
Eric Laurente552edb2014-03-10 17:42:56 -07001000 if (isStateInCall(state)) {
1001 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001002 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001003 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001004 }
1005
1006 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001007 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1008 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001009}
1010
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001011audio_mode_t AudioPolicyManager::getPhoneState() {
1012 return mEngine->getPhoneState();
1013}
1014
Eric Laurente0720872014-03-11 09:30:41 -07001015void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001016 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001017{
François Gaffie2110e042015-03-24 08:41:51 +01001018 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001019 if (config == mEngine->getForceUse(usage)) {
1020 return;
1021 }
Eric Laurente552edb2014-03-10 17:42:56 -07001022
François Gaffie2110e042015-03-24 08:41:51 +01001023 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1024 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1025 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
François Gaffie2110e042015-03-24 08:41:51 +01001027 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1028 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1029 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001030
1031 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001032 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001033
Eric Laurent22fcda22019-05-17 16:28:47 -07001034 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1035 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001036 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001037 }
1038
Eric Laurentdc462862016-07-19 12:29:53 -07001039 //FIXME: workaround for truncated touch sounds
1040 // to be removed when the problem is handled by system UI
1041 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001042 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1043 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1044 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001045
1046 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001047 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001048}
1049
Eric Laurente0720872014-03-11 09:30:41 -07001050void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001051{
1052 ALOGV("setSystemProperty() property %s, value %s", property, value);
1053}
1054
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055// Find an MSD output profile compatible with the parameters passed.
1056// When "directOnly" is set, restrict search to profiles for direct outputs.
1057sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1058 const DeviceVector& devices,
1059 uint32_t samplingRate,
1060 audio_format_t format,
1061 audio_channel_mask_t channelMask,
1062 audio_output_flags_t flags,
1063 bool directOnly)
1064{
1065 flags = getRelevantFlags(flags, directOnly);
1066
1067 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1068 if (msdModule != nullptr) {
1069 // for the msd module check if there are patches to the output devices
1070 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1071 HwModuleCollection modules;
1072 modules.add(msdModule);
1073 return searchCompatibleProfileHwModules(
1074 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1075 flags, directOnly);
1076 }
1077 }
1078 return nullptr;
1079}
1080
Michael Chana94fbb22018-04-24 14:31:19 +10001081// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1082// search to profiles for direct outputs.
1083sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001084 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001085 uint32_t samplingRate,
1086 audio_format_t format,
1087 audio_channel_mask_t channelMask,
1088 audio_output_flags_t flags,
1089 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001090{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001091 flags = getRelevantFlags(flags, directOnly);
1092
1093 return searchCompatibleProfileHwModules(
1094 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1095}
1096
1097audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1098 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001099 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001100 // only retain flags that will drive the direct output profile selection
1101 // if explicitly requested
1102 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001103 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1105 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001106 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001107 return flags;
1108}
Eric Laurent861a6282015-05-18 15:40:16 -07001109
Dorin Drimusecc9f422022-03-09 17:57:40 +01001110sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1111 const HwModuleCollection& hwModules,
1112 const DeviceVector& devices,
1113 uint32_t samplingRate,
1114 audio_format_t format,
1115 audio_channel_mask_t channelMask,
1116 audio_output_flags_t flags,
1117 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001118 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001119 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001120 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001121 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 samplingRate, NULL /*updatedSamplingRate*/,
1123 format, NULL /*updatedFormat*/,
1124 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001125 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 continue;
1127 }
1128 // reject profiles not corresponding to a device currently available
1129 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1130 continue;
1131 }
1132 // reject profiles if connected device does not support codec
1133 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1134 continue;
1135 }
1136 if (!directOnly) {
1137 return curProfile;
1138 }
1139
1140 // when searching for direct outputs, if several profiles are compatible, give priority
1141 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001142 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001143 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001144 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001145 }
1146 profile = curProfile;
1147 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1148 break;
1149 }
Eric Laurente552edb2014-03-10 17:42:56 -07001150 }
1151 }
Eric Laurent861a6282015-05-18 15:40:16 -07001152 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001153}
1154
Eric Laurentfa0f6742021-08-17 18:39:44 +02001155sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001156 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001157{
1158 for (const auto& hwModule : mHwModules) {
1159 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001160 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161 continue;
1162 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001163 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001164 // reject profiles not corresponding to a device currently available
1165 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1166 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1167 continue;
1168 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001169 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1170 != devices.size()) {
1171 continue;
1172 }
1173 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001174 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1175 return curProfile;
1176 }
1177 }
1178 return nullptr;
1179}
1180
Eric Laurentf4e63452017-11-06 19:31:46 +00001181audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001182{
François Gaffiec005e562018-11-06 15:04:49 +01001183 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001184
1185 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1186 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1187 // format, flags, etc. This may result in some discrepancy for functions that utilize
1188 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1189 // and AudioSystem::getOutputSamplingRate().
1190
François Gaffie11d30102018-11-02 16:09:09 +01001191 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001192 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1193 if (stream == AUDIO_STREAM_MUSIC &&
1194 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1195 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1196 }
1197 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001198
François Gaffie11d30102018-11-02 16:09:09 +01001199 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1200 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001201 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001202}
1203
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001204status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1205 const audio_attributes_t *srcAttr,
1206 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001207{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208 if (srcAttr != NULL) {
1209 if (!isValidAttributes(srcAttr)) {
1210 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1211 __func__,
1212 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1213 srcAttr->tags);
1214 return BAD_VALUE;
1215 }
1216 *dstAttr = *srcAttr;
1217 } else {
1218 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1219 ALOGE("%s: invalid stream type", __func__);
1220 return BAD_VALUE;
1221 }
François Gaffiec005e562018-11-06 15:04:49 +01001222 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001223 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001224
1225 // Only honor audibility enforced when required. The client will be
1226 // forced to reconnect if the forced usage changes.
1227 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001228 dstAttr->flags = static_cast<audio_flags_mask_t>(
1229 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001230 }
1231
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001232 return NO_ERROR;
1233}
1234
Kevin Rocard153f92d2018-12-18 18:33:28 -08001235status_t AudioPolicyManager::getOutputForAttrInt(
1236 audio_attributes_t *resultAttr,
1237 audio_io_handle_t *output,
1238 audio_session_t session,
1239 const audio_attributes_t *attr,
1240 audio_stream_type_t *stream,
1241 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001242 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001243 audio_output_flags_t *flags,
1244 audio_port_handle_t *selectedDeviceId,
1245 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001246 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001247 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001248 bool *isSpatialized,
1249 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001250{
François Gaffiec005e562018-11-06 15:04:49 +01001251 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001252 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001253 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001254 const sp<DeviceDescriptor> requestedDevice =
1255 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1256
Eric Laurent8a1095a2019-11-08 14:44:16 -08001257 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001258 *isSpatialized = false;
1259
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001260 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1261 if (status != NO_ERROR) {
1262 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001263 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001264 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001265 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001266 }
François Gaffiec005e562018-11-06 15:04:49 +01001267 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001268
François Gaffiec005e562018-11-06 15:04:49 +01001269 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1270 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001271
Oscar Azucena873d10f2023-01-12 18:34:42 -08001272 bool usePrimaryOutputFromPolicyMixes = false;
1273
Kevin Rocard153f92d2018-12-18 18:33:28 -08001274 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1275 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1276 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001278 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1279 .channel_mask = config->channel_mask,
1280 .format = config->format,
1281 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001282 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001283 mAvailableOutputDevices, requestedDevice, primaryMix,
1284 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001285 if (status != OK) {
1286 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001287 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001288
Kevin Rocard153f92d2018-12-18 18:33:28 -08001289 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001290 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1291 && !audio_is_linear_pcm(config->format)) {
1292 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001293 return BAD_VALUE;
1294 }
1295 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001296 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001297 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1298 primaryMix->mDeviceAddress,
1299 AUDIO_FORMAT_DEFAULT);
1300 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001301 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001302 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1303 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001304 // if a direct output can be opened to deliver the track's multi-channel content to the
1305 // output rather than being downmixed by the primary output, then use this direct
1306 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1307 // mix.
1308 bool tryDirectForChannelMask = policyDesc != nullptr
1309 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1310 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001311 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001312 audio_io_handle_t newOutput;
1313 status = openDirectOutput(
1314 *stream, session, config,
1315 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001316 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001317 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001318 policyDesc = mOutputs.valueFor(newOutput);
1319 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001320 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001321 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001322 policyDesc = nullptr;
1323 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001324 }
1325 if (policyDesc != nullptr) {
1326 policyDesc->mPolicyMix = primaryMix;
1327 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001328 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1329 : AUDIO_PORT_HANDLE_NONE;
1330 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1331 // Remove direct flag as it is not on a direct output.
1332 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1333 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001334
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001335 ALOGV("getOutputForAttr() returns output %d", *output);
1336 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1337 *outputType = API_OUT_MIX_PLAYBACK;
1338 } else {
1339 *outputType = API_OUTPUT_LEGACY;
1340 }
1341 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001342 } else {
1343 if (policyMixDevice != nullptr) {
1344 ALOGE("%s, try to use primary mix but no output found", __func__);
1345 return INVALID_OPERATION;
1346 }
1347 // Fallback to default engine selection as the selected primary mix device is not
1348 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001349 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001350 }
François Gaffiec005e562018-11-06 15:04:49 +01001351 // Virtual sources must always be dynamicaly or explicitly routed
1352 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1353 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1354 return BAD_VALUE;
1355 }
1356 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1357 // in order to let the choice of the order to future vendor engine
1358 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001359
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001360 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001361 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001362 }
1363
Nadav Barb2f18162018-07-18 13:01:53 +03001364 // Set incall music only if device was explicitly set, and fallback to the device which is
1365 // chosen by the engine if not.
1366 // FIXME: provide a more generic approach which is not device specific and move this back
1367 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001368 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001369 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001370 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001371 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001372 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001373 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001374 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001375 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001376 }
1377 }
1378
François Gaffiec005e562018-11-06 15:04:49 +01001379 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1380 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1381 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001382
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001383 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001384 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001385 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001386 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001387 ALOGV("%s() Using MSD devices %s instead of devices %s",
1388 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001389 } else {
1390 *output = AUDIO_IO_HANDLE_NONE;
1391 }
1392 }
1393 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001394 sp<PreferredMixerAttributesInfo> info = nullptr;
1395 if (outputDevices.size() == 1) {
1396 info = getPreferredMixerAttributesInfo(
1397 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001398 mEngine->getProductStrategyForAttributes(*resultAttr),
1399 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001400 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1401 // and it is currently active.
1402 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001403 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001404 info = nullptr;
1405 }
jiabin220eea12024-05-17 17:55:20 +00001406 if (com::android::media::audioserver::
1407 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1408 if (info != nullptr && info->getUid() == uid &&
1409 info->configMatches(*config) &&
1410 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1411 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1412 [this, &outputDevices](audio_usage_t usage) {
1413 return mOutputs.isUsageActiveOnDevice(
1414 usage, outputDevices[0]); }))) {
1415 // Bit-perfect request is not allowed when the phone mode is not normal or
1416 // there is any higher priority user case active.
1417 return INVALID_OPERATION;
1418 }
1419 }
jiabina84c3d32022-12-02 18:59:55 +00001420 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001421 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001422 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001423 // The client will be active if the client is currently preferred mixer owner and the
1424 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001425 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001426 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001427 && info->getUid() == uid
1428 && *output != AUDIO_IO_HANDLE_NONE
1429 // When bit-perfect output is selected for the preferred mixer attributes owner,
1430 // only need to consider the config matches.
1431 && mOutputs.valueFor(*output)->isConfigurationMatched(
1432 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001433
1434 if (*isBitPerfect) {
1435 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1436 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001438 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001439 AudioProfileVector profiles;
1440 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1441 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001442 const auto channels = profiles[0]->getChannels();
1443 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1444 config->channel_mask = *channels.begin();
1445 }
1446 const auto sampleRates = profiles[0]->getSampleRates();
1447 if (!sampleRates.empty() &&
1448 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1449 config->sample_rate = *sampleRates.begin();
1450 }
jiabinf1c73972022-04-14 16:28:52 -07001451 config->format = profiles[0]->getFormat();
1452 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001453 return INVALID_OPERATION;
1454 }
Paul McLeanaa981192015-03-21 09:55:15 -07001455
François Gaffiec005e562018-11-06 15:04:49 +01001456 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001457 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001458 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001459 *selectedDeviceId = outputDevice->getId();
1460 break;
1461 }
1462 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001463
Eric Laurent8a1095a2019-11-08 14:44:16 -08001464 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1465 *outputType = API_OUTPUT_TELEPHONY_TX;
1466 } else {
1467 *outputType = API_OUTPUT_LEGACY;
1468 }
1469
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1471
1472 return NO_ERROR;
1473}
1474
1475status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1476 audio_io_handle_t *output,
1477 audio_session_t session,
1478 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001479 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001480 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001481 audio_output_flags_t *flags,
1482 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001483 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001484 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001485 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001486 bool *isSpatialized,
1487 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001488{
1489 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1490 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1491 return INVALID_OPERATION;
1492 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001493 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001494 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001495 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001496 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001497 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001498 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001499 const sp<DeviceDescriptor> requestedDevice =
1500 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1501
1502 // Prevent from storing invalid requested device id in clients
1503 const audio_port_handle_t sanitizedRequestedPortId =
1504 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1505 *selectedDeviceId = sanitizedRequestedPortId;
1506
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001507 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001508 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001509 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1510 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 if (status != NO_ERROR) {
1512 return status;
1513 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001514 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001515 if (secondaryOutputs != nullptr) {
1516 for (auto &secondaryMix : secondaryMixes) {
1517 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1518 if (outputDesc != nullptr &&
1519 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1520 secondaryOutputs->push_back(outputDesc->mIoHandle);
1521 weakSecondaryOutputDescs.push_back(outputDesc);
1522 }
1523 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001524 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001525
Eric Laurent8fc147b2018-07-22 19:13:55 -07001526 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001527 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001528 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001529 };
jiabin4ef93452019-09-10 14:29:54 -07001530 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001531
Eric Laurentc209fe42020-06-05 18:11:23 -07001532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001533 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001534 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001535 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001536 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001537 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001538 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001539 std::move(weakSecondaryOutputDescs),
1540 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001541 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001542
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001543 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1544 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001545
Eric Laurente83b55d2014-11-14 10:06:21 -08001546 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001547}
1548
Eric Laurentc529cf62020-04-17 18:19:10 -07001549status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1550 audio_session_t session,
1551 const audio_config_t *config,
1552 audio_output_flags_t flags,
1553 const DeviceVector &devices,
1554 audio_io_handle_t *output) {
1555
1556 *output = AUDIO_IO_HANDLE_NONE;
1557
1558 // skip direct output selection if the request can obviously be attached to a mixed output
1559 // and not explicitly requested
1560 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1561 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1562 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1563 return NAME_NOT_FOUND;
1564 }
1565
1566 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1567 // This prevents creating an offloaded track and tearing it down immediately after start
1568 // when audioflinger detects there is an active non offloadable effect.
1569 // FIXME: We should check the audio session here but we do not have it in this context.
1570 // This may prevent offloading in rare situations where effects are left active by apps
1571 // in the background.
1572 sp<IOProfile> profile;
1573 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1574 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1575 profile = getProfileForOutput(
1576 devices, config->sample_rate, config->format, config->channel_mask,
1577 flags, true /* directOnly */);
1578 }
1579
1580 if (profile == nullptr) {
1581 return NAME_NOT_FOUND;
1582 }
1583
1584 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1585 for (size_t i = 0; i < mOutputs.size(); i++) {
1586 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1587 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1588 // reuse direct output if currently open by the same client
1589 // and configured with same parameters
1590 if ((config->sample_rate == desc->getSamplingRate()) &&
1591 (config->format == desc->getFormat()) &&
1592 (config->channel_mask == desc->getChannelMask()) &&
1593 (session == desc->mDirectClientSession)) {
1594 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001595 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001596 mOutputs.keyAt(i), session);
1597 *output = mOutputs.keyAt(i);
1598 return NO_ERROR;
1599 }
1600 }
1601 }
1602
1603 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001604 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1605 return NAME_NOT_FOUND;
1606 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1607 // MMAP gracefully handles lack of an exclusive track resource by mixing
1608 // above the audio framework. For AAudio to know that the limit is reached,
1609 // return an error.
1610 return NAME_NOT_FOUND;
1611 } else {
1612 // Close outputs on this profile, if available, to free resources for this request
1613 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1614 const auto desc = mOutputs.valueAt(i);
1615 if (desc->mProfile == profile) {
1616 closeOutput(desc->mIoHandle);
1617 }
1618 }
1619 }
1620 }
1621
1622 // Unable to close streams to find free resources for this request
1623 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001624 return NAME_NOT_FOUND;
1625 }
1626
Atneya Nairb16666a2023-12-11 20:18:33 -08001627 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001628
Michael Chan6fb34492020-12-08 15:44:49 +11001629 // An MSD patch may be using the only output stream that can service this request. Release
1630 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001631 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001632
Eric Laurentf1f22e72021-07-13 14:04:14 +02001633 status_t status =
1634 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001635
1636 // only accept an output with the requested parameters
1637 if (status != NO_ERROR ||
1638 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1639 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1640 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1641 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1642 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1643 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1644 config->channel_mask, outputDesc->getChannelMask());
1645 if (*output != AUDIO_IO_HANDLE_NONE) {
1646 outputDesc->close();
1647 }
1648 // fall back to mixer output if possible when the direct output could not be open
1649 if (audio_is_linear_pcm(config->format) &&
1650 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1651 return NAME_NOT_FOUND;
1652 }
1653 *output = AUDIO_IO_HANDLE_NONE;
1654 return BAD_VALUE;
1655 }
1656 outputDesc->mDirectOpenCount = 1;
1657 outputDesc->mDirectClientSession = session;
1658
1659 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001660 setOutputDevices(__func__, outputDesc,
1661 devices,
1662 true,
1663 0,
1664 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001665 mPreviousOutputs = mOutputs;
1666 ALOGV("%s returns new direct output %d", __func__, *output);
1667 mpClientInterface->onAudioPortListUpdate();
1668 return NO_ERROR;
1669}
1670
François Gaffie11d30102018-11-02 16:09:09 +01001671audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1672 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001673 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001674 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001675 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001676 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001677 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001678 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001679 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001680{
Andy Hungc88b0642018-04-27 15:42:35 -07001681 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001682
jiabine375d412019-02-26 12:54:53 -08001683 // Discard haptic channel mask when forcing muting haptic channels.
1684 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001685 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1686 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001687
Eric Laurente552edb2014-03-10 17:42:56 -07001688 // open a direct output if required by specified parameters
1689 //force direct flag if offload flag is set: offloading implies a direct output stream
1690 // and all common behaviors are driven by checking only the direct flag
1691 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001692 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1693 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001694 }
Nadav Bar766fb022018-01-07 12:18:03 +02001695 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1696 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001697 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001698
1699 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1700
Eric Laurente83b55d2014-11-14 10:06:21 -08001701 // only allow deep buffering for music stream type
1702 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001703 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001704 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001705 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001706 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1707 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001708 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001709 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001710 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001711 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001712 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001713 audio_is_linear_pcm(config->format) &&
1714 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001715 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001716 AUDIO_OUTPUT_FLAG_DIRECT);
1717 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001718 }
Eric Laurente552edb2014-03-10 17:42:56 -07001719
Carter Hsua3abb402021-10-26 11:11:20 +08001720 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1721 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1722 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1723 }
1724
Eric Laurentf9230d52024-01-26 18:49:09 +01001725 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001726 // was specified and offload or direct playback is not explicitly requested, and there is no
1727 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001728 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001729 if (mSpatializerOutput != nullptr &&
1730 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1731 prefMixerConfigInfo == nullptr &&
1732 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1733 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001734 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001735 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001736 }
1737
Eric Laurentc529cf62020-04-17 18:19:10 -07001738 audio_config_t directConfig = *config;
1739 directConfig.channel_mask = channelMask;
1740 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1741 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001742 return output;
1743 }
1744
Eric Laurent14cbfca2016-03-17 09:42:16 -07001745 // A request for HW A/V sync cannot fallback to a mixed output because time
1746 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001747 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001748 return AUDIO_IO_HANDLE_NONE;
1749 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001750 // A request for Tuner cannot fallback to a mixed output
1751 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1752 return AUDIO_IO_HANDLE_NONE;
1753 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001754
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // ignoring channel mask due to downmix capability in mixer
1756
1757 // open a non direct output
1758
1759 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001760 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001761 // get which output is suitable for the specified stream. The actual
1762 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001763 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001764 if (prefMixerConfigInfo != nullptr) {
1765 for (audio_io_handle_t outputHandle : outputs) {
1766 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1767 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1768 output = outputHandle;
1769 break;
1770 }
1771 }
1772 if (output == AUDIO_IO_HANDLE_NONE) {
1773 // No output open with the preferred profile. Open a new one.
1774 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1775 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1776 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1777 config.format = prefMixerConfigInfo->getConfigBase().format;
1778 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1779 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1780 &config, prefMixerConfigInfo->getFlags());
1781 if (preferredOutput == nullptr) {
1782 ALOGE("%s failed to open output with preferred mixer config", __func__);
1783 } else {
1784 output = preferredOutput->mIoHandle;
1785 }
1786 }
1787 } else {
1788 // at this stage we should ignore the DIRECT flag as no direct output could be
1789 // found earlier
1790 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001791 if (com::android::media::audioserver::
1792 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1793 // If the preferred mixer attributes is null, do not select the bit-perfect output
1794 // unless the bit-perfect output is the only output.
1795 // The bit-perfect output can exist while the passed in preferred mixer attributes
1796 // info is null when it is a high priority client. The high priority clients are
1797 // ringtone or alarm, which is not a bit-perfect use case.
1798 size_t i = 0;
1799 while (i < outputs.size() && outputs.size() > 1) {
1800 auto desc = mOutputs.valueFor(outputs[i]);
1801 // The output descriptor must not be null here.
1802 if (desc->isBitPerfect()) {
1803 outputs.removeItemsAt(i);
1804 } else {
1805 i += 1;
1806 }
1807 }
1808 }
jiabina84c3d32022-12-02 18:59:55 +00001809 output = selectOutput(
1810 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1811 }
Eric Laurente552edb2014-03-10 17:42:56 -07001812 }
François Gaffie11d30102018-11-02 16:09:09 +01001813 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001814 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001815 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001816
Eric Laurente552edb2014-03-10 17:42:56 -07001817 return output;
1818}
1819
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001820sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001821 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1822 mAvailableInputDevices);
1823 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1824}
1825
1826DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1827 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1828 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829}
1830
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001831const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001833 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1834 if (msdModule != 0) {
1835 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1836 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1837 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1838 const struct audio_port_config *source = &patch->mPatch.sources[j];
1839 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1840 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001841 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001842 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001843 }
1844 }
1845 }
1846 return msdPatches;
1847}
1848
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001849bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1850 ssize_t index = mAudioPatches.indexOfKey(handle);
1851 if (index < 0) {
1852 return false;
1853 }
1854 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1855 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1856 if (msdModule == nullptr) {
1857 return false;
1858 }
1859 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1860 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1861 return true;
1862 }
1863 index = getMsdOutputPatches().indexOfKey(handle);
1864 if (index < 0) {
1865 return false;
1866 }
1867 return true;
1868}
1869
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001870status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1871 const InputProfileCollection &inputProfiles,
1872 const OutputProfileCollection &outputProfiles,
1873 const sp<DeviceDescriptor> &sourceDevice,
1874 const sp<DeviceDescriptor> &sinkDevice,
1875 AudioProfileVector& sourceProfiles,
1876 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001878 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001879 return NO_INIT;
1880 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 return NO_INIT;
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1887 inProfile->supportsDevice(sourceDevice)) {
1888 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 }
1890 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001891 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001892 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001893 outProfile->supportsDevice(sinkDevice)) {
1894 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 }
1896 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 return NO_ERROR;
1898}
1899
1900status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1901 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1902 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1903{
Dean Wheatley16809da2022-12-09 14:55:46 +11001904 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1905 static const std::vector<audio_format_t> formatsOrder = {{
1906 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001907 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1908 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001909 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1910 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1911 // preferred).
1912 std::vector<audio_channel_mask_t> masks = {{
1913 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1914 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1915 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1916 // insert index masks (higher counts most preferred) as preferred over position masks
1917 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1918 masks.insert(
1919 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1920 }
1921 return masks;
1922 }();
1923
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001924 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001925 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1926 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001928 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1929 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001930 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001931 }
1932 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1933 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1934 sinkConfig->format = bestSinkConfig.format;
1935 // For encoded streams force direct flag to prevent downstream mixing.
1936 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1937 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001938 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1939 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001941 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1942 // raw and IEC61937 framed streams.
1943 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1944 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1945 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1947 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001948 sourceConfig->channel_mask =
1949 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1950 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1951 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 sourceConfig->format = bestSinkConfig.format;
1953 // Copy input stream directly without any processing (e.g. resampling).
1954 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1955 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1956 if (hwAvSync) {
1957 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1958 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1959 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1960 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1961 }
1962 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1963 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1964 sinkConfig->config_mask |= config_mask;
1965 sourceConfig->config_mask |= config_mask;
1966 return NO_ERROR;
1967}
1968
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1970 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001971{
1972 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001973 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1974 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1975 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1976 if (deviceModule == nullptr) {
1977 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1978 return patchBuilder;
1979 }
1980 const InputProfileCollection inputProfiles = msdIsSource ?
1981 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1982 const OutputProfileCollection outputProfiles = msdIsSource ?
1983 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1984
1985 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1986 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1987 device : getMsdAudioOutDevices().itemAt(0);
1988 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1989
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001990 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1991 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001992 AudioProfileVector sourceProfiles;
1993 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001994 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1995 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001996 for (auto hwAvSync : { true, false }) {
1997 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1998 sourceProfiles, sinkProfiles) != NO_ERROR) {
1999 continue;
2000 }
2001 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2002 &sinkConfig) == NO_ERROR) {
2003 // Found a matching config. Re-create PatchBuilder with this config.
2004 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2005 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002007 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002008 " supporting PCM format conversion.", __func__);
2009 return patchBuilder;
2010}
2011
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002012status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002013 DeviceVector devices;
2014 if (outputDevices != nullptr && outputDevices->size() > 0) {
2015 devices.add(*outputDevices);
2016 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002017 // Use media strategy for unspecified output device. This should only
2018 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2019 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002020 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002021 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002022 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002023 }
Michael Chan6fb34492020-12-08 15:44:49 +11002024 std::vector<PatchBuilder> patchesToCreate;
2025 for (auto i = 0u; i < devices.size(); ++i) {
2026 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002027 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002028 }
2029 // Retain only the MSD patches associated with outputDevices request.
2030 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002031 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002032 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2033 auto retainedPatch = false;
2034 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2035 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2036 patchesToRemove.removeItemsAt(i);
2037 retainedPatch = true;
2038 break;
2039 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040 }
Michael Chan6fb34492020-12-08 15:44:49 +11002041 if (retainedPatch) {
2042 it = patchesToCreate.erase(it);
2043 continue;
2044 }
2045 ++it;
2046 }
2047 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2048 return NO_ERROR;
2049 }
2050 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2051 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002052 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002053 }
Michael Chan6fb34492020-12-08 15:44:49 +11002054 status_t status = NO_ERROR;
2055 for (const auto &p : patchesToCreate) {
2056 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2057 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2058 char message[256];
2059 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2060 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2061 currStatus == NO_ERROR ? "Success" : "Error",
2062 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2063 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2064 if (currStatus == NO_ERROR) {
2065 ALOGD("%s", message);
2066 } else {
2067 ALOGE("%s", message);
2068 if (status == NO_ERROR) {
2069 status = currStatus;
2070 }
2071 }
2072 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002073 return status;
2074}
2075
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002076void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2077 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002078 for (size_t i = 0; i < msdPatches.size(); i++) {
2079 const auto& patch = msdPatches[i];
2080 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2081 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2082 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2083 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2084 releaseAudioPatch(patch->getHandle(), mUidCached);
2085 break;
2086 }
2087 }
2088 }
2089}
2090
Dorin Drimus94d94412022-02-02 09:05:02 +01002091bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002092 DeviceVector devicesToCheck =
2093 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002094 AudioPatchCollection msdPatches = getMsdOutputPatches();
2095 for (size_t i = 0; i < msdPatches.size(); i++) {
2096 const auto& patch = msdPatches[i];
2097 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2098 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2099 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2100 const auto& foundDevice = devicesToCheck.getDevice(
2101 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2102 if (foundDevice != nullptr) {
2103 devicesToCheck.remove(foundDevice);
2104 if (devicesToCheck.isEmpty()) {
2105 return true;
2106 }
2107 }
2108 }
2109 }
2110 }
2111 return false;
2112}
2113
Eric Laurente0720872014-03-11 09:30:41 -07002114audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002115 audio_output_flags_t flags,
2116 audio_format_t format,
2117 audio_channel_mask_t channelMask,
2118 uint32_t samplingRate,
2119 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002120{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2122 "%s called with format %#x", __func__, format);
2123
jiabinebb6af42020-06-09 17:31:17 -07002124 // Return the output that haptic-generating attached to when 1) session id is specified,
2125 // 2) haptic-generating effect exists for given session id and 3) the output that
2126 // haptic-generating effect attached to is in given outputs.
2127 if (sessionId != AUDIO_SESSION_NONE) {
2128 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2129 sessionId, FX_IID_HAPTICGENERATOR);
2130 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2131 return hapticGeneratingOutput;
2132 }
2133 }
2134
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135 // Flags disqualifying an output: the match must happen before calling selectOutput()
2136 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2137 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2138
2139 // Flags expressing a functional request: must be honored in priority over
2140 // other criteria
2141 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2142 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002143 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2144 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 // Flags expressing a performance request: have lower priority than serving
2146 // requested sampling rate or channel mask
2147 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2148 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2149 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2150
2151 const audio_output_flags_t functionalFlags =
2152 (audio_output_flags_t)(flags & kFunctionalFlags);
2153 const audio_output_flags_t performanceFlags =
2154 (audio_output_flags_t)(flags & kPerformanceFlags);
2155
2156 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2157
Eric Laurente552edb2014-03-10 17:42:56 -07002158 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002159 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002160 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002161 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002163 // with tiebreak preferring the minimum number of extra functional flags
2164 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002165 // 3: the output supporting the exact channel mask
2166 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002167 // 5: the output with the highest sampling rate if the requested sample rate is
2168 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002169 // 6: the output with the highest number of requested performance flags
2170 // 7: the output with the bit depth the closest to the requested one
2171 // 8: the primary output
2172 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002173
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 // matching criteria values in priority order for best matching output so far
2175 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002176
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002177 const bool hasOrphanHaptic =
2178 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2180 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2181 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002182
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002183 for (audio_io_handle_t output : outputs) {
2184 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002185 // matching criteria values in priority order for current output
2186 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002187
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 if (outputDesc->isDuplicated()) {
2189 continue;
2190 }
2191 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2192 continue;
2193 }
Eric Laurent8838a382014-09-08 16:44:28 -07002194
Eric Laurent16c66dd2019-05-01 17:54:10 -07002195 // If haptic channel is specified, use the haptic output if present.
2196 // When using haptic output, same audio format and sample rate are required.
2197 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002198 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002199 // skip if haptic channel specified but output does not support it, or output support haptic
2200 // but there is no haptic channel requested AND no orphan haptic effect exist
2201 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2202 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 continue;
2204 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002205 // In the case of audio-coupled-haptic playback, there is no format conversion and
2206 // resampling in the framework, same format/channel/sampleRate for client and the output
2207 // thread is required. In the case of HapticGenerator effect, do not require format
2208 // matching.
2209 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2210 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002211 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002212 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 }
2214
2215 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002216 const int matchingFunctionalFlags =
2217 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2218 const int totalFunctionalFlags =
2219 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2220 // Prefer matching functional flags, but subtract unnecessary functional flags.
2221 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002222
2223 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002224 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2225 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002226 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2227 channelCount <= outputChannelCount) {
2228 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002229 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2230 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002232 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002233 currentMatchCriteria[3] = outputChannelCount;
2234 }
2235
2236 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002237 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002238 int diff; // avoid unsigned integer overflow.
2239 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2240
2241 // prefer the closest output sampling rate greater than or equal to target
2242 // if none exists, prefer the closest output sampling rate less than target.
2243 //
2244 // criteria is offset to make non-negative.
2245 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002246 }
2247
2248 // performance flags match
2249 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2250
2251 // format match
2252 if (format != AUDIO_FORMAT_INVALID) {
2253 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002254 PolicyAudioPort::kFormatDistanceMax -
2255 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256 }
2257
2258 // primary output match
2259 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2260
2261 // compare match criteria by priority then value
2262 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2263 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2264 bestMatchCriteria = currentMatchCriteria;
2265 bestOutput = output;
2266
2267 std::stringstream result;
2268 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2269 std::ostream_iterator<int>(result, " "));
2270 ALOGV("%s new bestOutput %d criteria %s",
2271 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002272 }
2273 }
2274
Eric Laurent16c66dd2019-05-01 17:54:10 -07002275 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002276}
2277
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002280 ALOGV("%s portId %d", __FUNCTION__, portId);
2281
2282 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2283 if (outputDesc == 0) {
2284 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002285 return BAD_VALUE;
2286 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002287 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002288
Eric Laurent8fc147b2018-07-22 19:13:55 -07002289 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002290 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002291
jiabin220eea12024-05-17 17:55:20 +00002292 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2293 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2294 && outputDesc->isBitPerfect()) {
2295 // Usually, APM selects bit-perfect output for high priority use cases only when
2296 // bit-perfect output is the only output that can be routed to the selected device.
2297 // However, here is no need to play high priority use cases such as ringtone and alarm
2298 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2299 // can attach to new output.
2300 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2301 __func__, client->stream());
2302 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2303 return DEAD_OBJECT;
2304 }
2305
Eric Laurent733ce942017-12-07 12:18:25 -08002306 status_t status = outputDesc->start();
2307 if (status != NO_ERROR) {
2308 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002309 }
2310
Eric Laurent97ac8712018-07-27 18:59:02 -07002311 uint32_t delayMs;
2312 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002313
2314 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002315 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002316 if (status == DEAD_OBJECT) {
2317 sp<SwAudioOutputDescriptor> desc =
2318 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2319 if (desc == nullptr) {
2320 // This is not common, it may indicate something wrong with the HAL.
2321 ALOGE("%s unable to open output with default config", __func__);
2322 return status;
2323 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002324 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002325 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002326 }
jiabina84c3d32022-12-02 18:59:55 +00002327
2328 // If the client is the first one active on preferred mixer parameters, reopen the output
2329 // if the current mixer parameters doesn't match the preferred one.
2330 if (outputDesc->devices().size() == 1) {
2331 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2332 outputDesc->devices()[0]->getId(), client->strategy());
2333 if (info != nullptr && info->getUid() == client->uid()) {
2334 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2335 info->getConfigBase(), info->getFlags())) {
2336 stopSource(outputDesc, client);
2337 outputDesc->stop();
2338 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2339 config.channel_mask = info->getConfigBase().channel_mask;
2340 config.sample_rate = info->getConfigBase().sample_rate;
2341 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002342 sp<SwAudioOutputDescriptor> desc =
2343 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2344 if (desc == nullptr) {
2345 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002346 }
jiabin220eea12024-05-17 17:55:20 +00002347 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002348 // Intentionally return error to let the client side resending request for
2349 // creating and starting.
2350 return DEAD_OBJECT;
2351 }
2352 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002353 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002354 // If it is first bit-perfect client, reroute all clients that will be routed to
2355 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2356 PortHandleVector clientsToInvalidate;
2357 for (size_t i = 0; i < mOutputs.size(); i++) {
2358 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002359 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002360 continue;
2361 }
2362 for (const auto& c : mOutputs[i]->getClientIterable()) {
2363 clientsToInvalidate.push_back(c->portId());
2364 }
2365 }
2366 if (!clientsToInvalidate.empty()) {
2367 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2368 __func__);
2369 mpClientInterface->invalidateTracks(clientsToInvalidate);
2370 }
2371 }
jiabina84c3d32022-12-02 18:59:55 +00002372 }
2373 }
2374
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002375 if (client->hasPreferredDevice()) {
2376 // playback activity with preferred device impacts routing occurred, inform upper layers
2377 mpClientInterface->onRoutingUpdated();
2378 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002379 if (delayMs != 0) {
2380 usleep(delayMs * 1000);
2381 }
2382
jiabin220eea12024-05-17 17:55:20 +00002383 if (status == NO_ERROR &&
2384 outputDesc->mPreferredAttrInfo != nullptr &&
2385 outputDesc->isBitPerfect() &&
2386 com::android::media::audioserver::
2387 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2388 // A new client is started on bit-perfect output, update all clients internal mute.
2389 updateClientsInternalMute(outputDesc);
2390 }
2391
Eric Laurentc75307b2015-03-17 15:29:32 -07002392 return status;
2393}
2394
Eric Laurent96d1dda2022-03-14 17:14:19 +01002395bool AudioPolicyManager::isLeUnicastActive() const {
2396 if (isInCall()) {
2397 return true;
2398 }
2399 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2400}
2401
2402bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2403 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2404 return false;
2405 }
2406 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2407 ALOGV("%s active %d", __func__, active);
2408 return active;
2409}
2410
Eric Laurent97ac8712018-07-27 18:59:02 -07002411status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2412 const sp<TrackClientDescriptor>& client,
2413 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002414{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002415 // cannot start playback of STREAM_TTS if any other output is being used
2416 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002417
2418 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002419 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002420 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002421 auto clientStrategy = client->strategy();
2422 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002423 if (stream == AUDIO_STREAM_TTS) {
2424 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002425 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002426 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002427 return INVALID_OPERATION;
2428 } else {
2429 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2430 }
2431 } else {
2432 // some playback other than beacon starts
2433 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2434 }
2435
Eric Laurent77305a62016-07-25 16:39:22 -07002436 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002437 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002438 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002439
François Gaffie11d30102018-11-02 16:09:09 +01002440 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002441 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002443 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002444 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002445 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002446 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002447 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002448 } else {
2449 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002450 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002451 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2452 AUDIO_FORMAT_DEFAULT);
2453 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2454 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002455 }
2456
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002457 // requiresMuteCheck is false when we can bypass mute strategy.
2458 // It covers a common case when there is no materially active audio
2459 // and muting would result in unnecessary delay and dropped audio.
2460 const uint32_t outputLatencyMs = outputDesc->latency();
2461 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002462 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002463
Eric Laurente552edb2014-03-10 17:42:56 -07002464 // increment usage count for this stream on the requested output:
2465 // NOTE that the usage count is the same for duplicated output and hardware output which is
2466 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002467 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002468
2469 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002470 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002471 // Preferred device may be exclusive, use only if no other active clients on this output
2472 devices = DeviceVector(
2473 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2474 } else {
2475 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2476 }
François Gaffie11d30102018-11-02 16:09:09 +01002477 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002478 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002479 }
2480 }
Eric Laurente552edb2014-03-10 17:42:56 -07002481
François Gaffiec005e562018-11-06 15:04:49 +01002482 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002483 selectOutputForMusicEffects();
2484 }
2485
François Gaffie1c878552018-11-22 16:53:21 +01002486 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002487 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002488 if (devices.isEmpty()) {
2489 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002490 }
François Gaffiec005e562018-11-06 15:04:49 +01002491 bool shouldWait =
2492 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2493 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2494 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002495 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002496 const bool needToCloseBitPerfectOutput =
2497 (com::android::media::audioserver::
2498 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2499 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2500 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002501 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002502 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002503 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002504 // An output has a shared device if
2505 // - managed by the same hw module
2506 // - supports the currently selected device
2507 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002508 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002509
Eric Laurent77305a62016-07-25 16:39:22 -07002510 // force a device change if any other output is:
2511 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002512 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002513 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002514 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002515 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002516 // change the device currently selected by the other output.
2517 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002518 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002519 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002520 force = true;
2521 }
2522 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002523 // a notification so that audio focus effect can propagate, or that a mute/unmute
2524 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002525 const uint32_t latencyMs = desc->latency();
2526 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2527
2528 if (shouldWait && isActive && (waitMs < latencyMs)) {
2529 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002530 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002531
2532 // Require mute check if another output is on a shared device
2533 // and currently active to have proper drain and avoid pops.
2534 // Note restoring AudioTracks onto this output needs to invoke
2535 // a volume ramp if there is no mute.
2536 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002537
2538 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2539 outputsToReopen.push_back(desc);
2540 }
Eric Laurente552edb2014-03-10 17:42:56 -07002541 }
2542 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002543
jiabin220eea12024-05-17 17:55:20 +00002544 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002545 // If the output is open with preferred mixer attributes, but the routed device is
2546 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2547 // changed.
2548 return DEAD_OBJECT;
2549 }
jiabin220eea12024-05-17 17:55:20 +00002550 for (auto& outputToReopen : outputsToReopen) {
2551 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2552 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002553 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302554 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2555 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002556
Eric Laurente552edb2014-03-10 17:42:56 -07002557 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002558 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002559 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002560 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002561 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002562 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002563 outputDesc->useHwGain() /*force*/)) {
2564 // request AudioService to reinitialize the volume curves asynchronously
2565 ALOGE("checkAndSetVolume failed, requesting volume range init");
2566 mpClientInterface->onVolumeRangeInitRequest();
2567 };
Eric Laurente552edb2014-03-10 17:42:56 -07002568
2569 // update the outputs if starting an output with a stream that can affect notification
2570 // routing
2571 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002572
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002573 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002574 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002575 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002576 }
Eric Laurentdc462862016-07-19 12:29:53 -07002577
2578 if (waitMs > muteWaitMs) {
2579 *delayMs = waitMs - muteWaitMs;
2580 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002581
2582 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2583 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2584 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2585 // change occurs after the MixerThread starts and causes a stream volume
2586 // glitch.
2587 //
2588 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002589 }
Eric Laurentdc462862016-07-19 12:29:53 -07002590
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002591 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002592 mEngine->getForceUse(
2593 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002594 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002595 }
2596
Eric Laurent97ac8712018-07-27 18:59:02 -07002597 // Automatically enable the remote submix input when output is started on a re routing mix
2598 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002599 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2600 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002601 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2602 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2603 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002604 "remote-submix",
2605 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002606 }
2607
Eric Laurent96d1dda2022-03-14 17:14:19 +01002608 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2609
Eric Laurente552edb2014-03-10 17:42:56 -07002610 return NO_ERROR;
2611}
2612
Eric Laurent96d1dda2022-03-14 17:14:19 +01002613void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2614 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2615 bool isUnicastActive = isLeUnicastActive();
2616
2617 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002618 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002619 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2620 for (size_t i = 0; i < mOutputs.size(); i++) {
2621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2622 if (desc != ignoredOutput && desc->isActive()
2623 && ((isUnicastActive &&
2624 !desc->devices().
2625 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2626 || (wasUnicastActive &&
2627 !desc->devices().getDevicesFromTypes(
2628 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2629 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2630 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002631 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002632 // If the device is using preferred mixer attributes, the output need to reopen
2633 // with default configuration when the new selected devices are different from
2634 // current routing devices.
2635 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2636 continue;
2637 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302638 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002639 // re-apply device specific volume if not done by setOutputDevice()
2640 if (!force) {
2641 applyStreamVolumes(desc, newDevices.types(), delayMs);
2642 }
2643 }
2644 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002645 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002646 }
2647}
2648
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002650{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651 ALOGV("%s portId %d", __FUNCTION__, portId);
2652
2653 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2654 if (outputDesc == 0) {
2655 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002656 return BAD_VALUE;
2657 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002658 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002659
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002660 if (client->hasPreferredDevice(true)) {
2661 // playback activity with preferred device impacts routing occurred, inform upper layers
2662 mpClientInterface->onRoutingUpdated();
2663 }
2664
Eric Laurent97ac8712018-07-27 18:59:02 -07002665 ALOGV("stopOutput() output %d, stream %d, session %d",
2666 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002667
Eric Laurent97ac8712018-07-27 18:59:02 -07002668 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002669
Eric Laurent733ce942017-12-07 12:18:25 -08002670 if (status == NO_ERROR ) {
2671 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002672 } else {
2673 return status;
2674 }
2675
2676 if (outputDesc->devices().size() == 1) {
2677 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2678 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002679 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002680 if (info != nullptr && info->getUid() == client->uid()) {
2681 info->decreaseActiveClient();
2682 if (info->getActiveClientCount() == 0) {
2683 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002684 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002685 }
2686 }
jiabin220eea12024-05-17 17:55:20 +00002687 if (com::android::media::audioserver::
2688 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2689 !outputReopened && outputDesc->isBitPerfect()) {
2690 // Only need to update the clients' internal mute when the output is bit-perfect and it
2691 // is not reopened.
2692 updateClientsInternalMute(outputDesc);
2693 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002694 }
2695 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002696}
2697
Eric Laurent97ac8712018-07-27 18:59:02 -07002698status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2699 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002700{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002701 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002702 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002703 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002704 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002705
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002706 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2707
François Gaffie1c878552018-11-22 16:53:21 +01002708 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2709 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002710 // Automatically disable the remote submix input when output is stopped on a
2711 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002712 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002713 if (isSingleDeviceType(
2714 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002715 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002716 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002717 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2718 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002719 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002720 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002721 }
2722 }
2723 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002724 if (client->hasPreferredDevice(true) &&
2725 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002726 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002727 forceDeviceUpdate = true;
2728 }
2729
Eric Laurente552edb2014-03-10 17:42:56 -07002730 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002731 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002732
Eric Laurente552edb2014-03-10 17:42:56 -07002733 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002734 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002735 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002736 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002737
2738 // If the routing does not change, if an output is routed on a device using HwGain
2739 // (aka setAudioPortConfig) and there are still active clients following different
2740 // volume group(s), force reapply volume
2741 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2742 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2743
Eric Laurente552edb2014-03-10 17:42:56 -07002744 // delay the device switch by twice the latency because stopOutput() is executed when
2745 // the track stop() command is received and at that time the audio track buffer can
2746 // still contain data that needs to be drained. The latency only covers the audio HAL
2747 // and kernel buffers. Also the latency does not always include additional delay in the
2748 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302749 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002750 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002751
2752 // force restoring the device selection on other active outputs if it differs from the
2753 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002754 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002755 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002756 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002757 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002758 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002759 desc->isActive() &&
2760 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002761 (newDevices != desc->devices())) {
2762 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2763 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002764
jiabin220eea12024-05-17 17:55:20 +00002765 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002766 // If the device is using preferred mixer attributes, the output need to
2767 // reopen with default configuration when the new selected devices are
2768 // different from current routing devices.
2769 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2770 continue;
2771 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302772 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002773
Eric Laurent57de36c2016-09-28 16:59:11 -07002774 // re-apply device specific volume if not done by setOutputDevice()
2775 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002776 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002777 }
Eric Laurente552edb2014-03-10 17:42:56 -07002778 }
2779 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002780 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002781 // update the outputs if stopping one with a stream that can affect notification routing
2782 handleNotificationRoutingForStream(stream);
2783 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002784
2785 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2786 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002787 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002788 }
2789
François Gaffiec005e562018-11-06 15:04:49 +01002790 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002791 selectOutputForMusicEffects();
2792 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002793
2794 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2795
Eric Laurente552edb2014-03-10 17:42:56 -07002796 return NO_ERROR;
2797 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002798 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002799 return INVALID_OPERATION;
2800 }
2801}
2802
jiabinbce0c1d2020-10-05 11:20:18 -07002803bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002804{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002805 ALOGV("%s portId %d", __FUNCTION__, portId);
2806
2807 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2808 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002809 // If an output descriptor is closed due to a device routing change,
2810 // then there are race conditions with releaseOutput from tracks
2811 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2812 // destroyed shortly thereafter.
2813 //
2814 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002815 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002816 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002817 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002818
2819 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002820
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302821 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2822 if (outputDesc->isClientActive(client)) {
2823 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2824 stopOutput(portId);
2825 }
2826
Eric Laurent8fc147b2018-07-22 19:13:55 -07002827 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2828 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002829 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002831 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002832 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002833 if (--outputDesc->mDirectOpenCount == 0) {
2834 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002835 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002836 }
2837 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302838
Andy Hung39efb7a2018-09-26 15:39:28 -07002839 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002840 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2841 // The output is pending reopened to query dynamic profiles and
2842 // there is no active clients
2843 closeOutput(outputDesc->mIoHandle);
2844 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2845 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2846 if (newOutputDesc == nullptr) {
2847 ALOGE("%s failed to open output", __func__);
2848 }
2849 return true;
2850 }
2851 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002852}
2853
Eric Laurentcaf7f482014-11-25 17:50:47 -08002854status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2855 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002856 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002857 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002858 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002859 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002860 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002861 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002862 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002863 audio_port_handle_t *portId,
2864 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002865{
François Gaffiec005e562018-11-06 15:04:49 +01002866 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002867 "flags %#x attributes=%s requested device ID %d",
2868 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2869 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002870
Eric Laurentad2e7b92017-09-14 20:06:42 -07002871 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002872 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002873 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002874 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002875 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002876 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002877 sp<RecordClientDescriptor> clientDesc;
2878 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002879 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881
2882 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2883 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2884 return INVALID_OPERATION;
2885 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002886
Francois Gaffie716e1432019-01-14 16:58:59 +01002887 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2888 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002889 }
2890
Paul McLean466dc8e2015-04-17 13:15:36 -06002891 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002892 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002893 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002894
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2896 // possible
2897 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2898 *input != AUDIO_IO_HANDLE_NONE) {
2899 ssize_t index = mInputs.indexOfKey(*input);
2900 if (index < 0) {
2901 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2902 status = BAD_VALUE;
2903 goto error;
2904 }
2905 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002906 RecordClientVector clients = inputDesc->getClientsForSession(session);
2907 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002908 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2909 status = BAD_VALUE;
2910 goto error;
2911 }
2912 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2913 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002914 // corresponds to a new client and is only permitted from the same UID.
2915 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 if (clients.size() > 1) {
2917 for (const auto& client : clients) {
2918 // The client map is ordered by key values (portId) and portIds are allocated
2919 // incrementaly. So the first client in this list is the one opened by audio flinger
2920 // when the mmap stream is created and should be ignored as it does not correspond
2921 // to an actual client
2922 if (client == *clients.cbegin()) {
2923 continue;
2924 }
2925 if (uid != client->uid() && !client->isSilenced()) {
2926 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2927 uid, client->portId(), client->uid());
2928 status = INVALID_OPERATION;
2929 goto error;
2930 }
Eric Laurent331679c2018-04-16 17:03:16 -07002931 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002932 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002933 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002934 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002935
Eric Laurentfecbceb2021-02-09 14:46:43 +01002936 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002937 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002938 }
2939
2940 *input = AUDIO_IO_HANDLE_NONE;
2941 *inputType = API_INPUT_INVALID;
2942
Francois Gaffie716e1432019-01-14 16:58:59 +01002943 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002944 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002945 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002946 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002947 ALOGW("%s could not find input mix for attr %s",
2948 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002949 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002950 }
jiabinc1de2df2019-05-07 14:26:40 -07002951 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2952 String8(attr->tags + strlen("addr=")),
2953 AUDIO_FORMAT_DEFAULT);
2954 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002955 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002956 __func__, attributes.source, attributes.tags);
2957 status = BAD_VALUE;
2958 goto error;
2959 }
2960
Kevin Rocard25f9b052019-02-27 15:08:54 -08002961 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2962 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2963 } else {
2964 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2965 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002966 if (virtualDeviceId) {
2967 *virtualDeviceId = policyMix->mVirtualDeviceId;
2968 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002969 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002970 if (explicitRoutingDevice != nullptr) {
2971 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002972 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002973 // Prevent from storing invalid requested device id in clients
2974 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002975 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002976 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2977 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002978 }
François Gaffie11d30102018-11-02 16:09:09 +01002979 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002980 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002981 status = BAD_VALUE;
2982 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002983 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002984 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2985 *inputType = API_INPUT_MIX_CAPTURE;
2986 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002987 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2988 // there is an external policy, but this input is attached to a mix of recorders,
2989 // meaning it receives audio injected into the framework, so the recorder doesn't
2990 // know about it and is therefore considered "legacy"
2991 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002992
2993 if (virtualDeviceId) {
2994 *virtualDeviceId = policyMix->mVirtualDeviceId;
2995 }
François Gaffie11d30102018-11-02 16:09:09 +01002996 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002997 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002998 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002999 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003000 } else {
3001 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003002 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003003
Eric Laurent599c7582015-12-07 18:05:55 -08003004 }
3005
François Gaffiec005e562018-11-06 15:04:49 +01003006 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003007 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003008 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003009 AudioProfileVector profiles;
3010 status_t ret = getProfilesForDevices(
3011 DeviceVector(device), profiles, flags, true /*isInput*/);
3012 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003013 const auto channels = profiles[0]->getChannels();
3014 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3015 config->channel_mask = *channels.begin();
3016 }
3017 const auto sampleRates = profiles[0]->getSampleRates();
3018 if (!sampleRates.empty() &&
3019 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3020 config->sample_rate = *sampleRates.begin();
3021 }
jiabinf1c73972022-04-14 16:28:52 -07003022 config->format = profiles[0]->getFormat();
3023 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003024 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003025 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003026
Marvin Ramine5a122d2023-12-07 13:57:59 +01003027
3028 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3029 *virtualDeviceId = policyMix->mVirtualDeviceId;
3030 }
3031
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032exit:
3033
François Gaffiec005e562018-11-06 15:04:49 +01003034 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3035 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003036
Francois Gaffie716e1432019-01-14 16:58:59 +01003037 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003038 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003039 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040
Mikhail Naganov2996f672019-04-18 12:29:59 -07003041 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003042 requestedDeviceId, attributes.source, flags,
3043 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003044 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003045 // Move (if found) effect for the client session to its input
3046 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003047 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003048
3049 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3050 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003051
Eric Laurent599c7582015-12-07 18:05:55 -08003052 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003053
3054error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003056}
3057
3058
François Gaffie11d30102018-11-02 16:09:09 +01003059audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003060 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003061 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003062 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003063 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003064 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003065{
3066 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003067 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003068 bool isSoundTrigger = false;
3069
François Gaffiec005e562018-11-06 15:04:49 +01003070 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003071 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3072 if (index >= 0) {
3073 input = mSoundTriggerSessions.valueFor(session);
3074 isSoundTrigger = true;
3075 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3076 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3077 } else {
3078 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003079 }
François Gaffiec005e562018-11-06 15:04:49 +01003080 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003081 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003082 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003083 }
3084
Carter Hsua3abb402021-10-26 11:11:20 +08003085 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3086 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3087 }
3088
Eric Laurentfe231122017-11-17 17:48:06 -08003089 // sampling rate and flags may be updated by getInputProfile
3090 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3091 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003092 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003093 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003094 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003095 // find a compatible input profile (not necessarily identical in parameters)
3096 sp<IOProfile> profile = getInputProfile(
3097 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3098 if (profile == nullptr) {
3099 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003100 }
jiabin2fd710d2022-05-02 23:20:22 +00003101
Glenn Kasten05ddca52016-02-11 08:17:12 -08003102 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003103 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003104 if (samplingRate == 0) {
3105 samplingRate = profileSamplingRate;
3106 }
Eric Laurente552edb2014-03-10 17:42:56 -07003107
Eric Laurent322b4d22015-04-03 15:57:54 -07003108 if (profile->getModuleHandle() == 0) {
3109 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003110 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003111 }
3112
Eric Laurentec376dc2021-04-08 20:41:22 +02003113 // Reuse an already opened input if a client with the same session ID already exists
3114 // on that input
3115 for (size_t i = 0; i < mInputs.size(); i++) {
3116 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3117 if (desc->mProfile != profile) {
3118 continue;
3119 }
3120 RecordClientVector clients = desc->clientsList();
3121 for (const auto &client : clients) {
3122 if (session == client->session()) {
3123 return desc->mIoHandle;
3124 }
3125 }
3126 }
3127
Eric Laurent3974e3b2017-12-07 17:58:43 -08003128 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003129 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003130 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003131 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003132 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003133 continue;
3134 }
3135 // if sound trigger, reuse input if used by other sound trigger on same session
3136 // else
3137 // reuse input if active client app is not in IDLE state
3138 //
3139 RecordClientVector clients = desc->clientsList();
3140 bool doClose = false;
3141 for (const auto& client : clients) {
3142 if (isSoundTrigger != client->isSoundTrigger()) {
3143 continue;
3144 }
3145 if (client->isSoundTrigger()) {
3146 if (session == client->session()) {
3147 return desc->mIoHandle;
3148 }
3149 continue;
3150 }
3151 if (client->active() && client->appState() != APP_STATE_IDLE) {
3152 return desc->mIoHandle;
3153 }
3154 doClose = true;
3155 }
3156 if (doClose) {
3157 closeInput(desc->mIoHandle);
3158 } else {
3159 i++;
3160 }
3161 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003162 }
3163
Eric Laurentfe231122017-11-17 17:48:06 -08003164 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003165
Eric Laurentfe231122017-11-17 17:48:06 -08003166 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3167 lConfig.sample_rate = profileSamplingRate;
3168 lConfig.channel_mask = profileChannelMask;
3169 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003170
François Gaffie11d30102018-11-02 16:09:09 +01003171 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003172
3173 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003174 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003175 (profileSamplingRate != lConfig.sample_rate) ||
3176 !audio_formats_match(profileFormat, lConfig.format) ||
3177 (profileChannelMask != lConfig.channel_mask)) {
3178 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003179 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003180 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003181 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003182 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003183 }
Eric Laurent599c7582015-12-07 18:05:55 -08003184 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003185 }
3186
Eric Laurentc722f302014-12-10 11:21:49 -08003187 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003188
Eric Laurent599c7582015-12-07 18:05:55 -08003189 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003190 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003191
Eric Laurent599c7582015-12-07 18:05:55 -08003192 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003193}
3194
Eric Laurent4eb58f12018-12-07 16:41:02 -08003195status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003196{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003197 ALOGV("%s portId %d", __FUNCTION__, portId);
3198
3199 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3200 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003201 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003202 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003203 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003204 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003205 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003206 if (client->active()) {
3207 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3208 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003209 }
3210
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211 audio_session_t session = client->session();
3212
Eric Laurent4eb58f12018-12-07 16:41:02 -08003213 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003214
Eric Laurent4eb58f12018-12-07 16:41:02 -08003215 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003216
Eric Laurent4eb58f12018-12-07 16:41:02 -08003217 status_t status = inputDesc->start();
3218 if (status != NO_ERROR) {
3219 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003220 }
Eric Laurente552edb2014-03-10 17:42:56 -07003221
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003222 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003223 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003224 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003225
Eric Laurent8f42ea12018-08-08 09:08:25 -07003226 // indicate active capture to sound trigger service if starting capture from a mic on
3227 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003228 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003229 if (device != nullptr) {
3230 status = setInputDevice(input, device, true /* force */);
3231 } else {
3232 ALOGW("%s no new input device can be found for descriptor %d",
3233 __FUNCTION__, inputDesc->getId());
3234 status = BAD_VALUE;
3235 }
Eric Laurente552edb2014-03-10 17:42:56 -07003236
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003237 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003238 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003239 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003240 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003241 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3242 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003243 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003244 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003245
François Gaffie11d30102018-11-02 16:09:09 +01003246 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3247 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003248 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003249 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003250 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003251
Eric Laurent8f42ea12018-08-08 09:08:25 -07003252 // automatically enable the remote submix output when input is started if not
3253 // used by a policy mix of type MIX_TYPE_RECORDERS
3254 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003255 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003256 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003257 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003258 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003259 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3260 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003261 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 if (address != "") {
3263 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3264 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003265 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003266 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003267 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003268 } else if (status != NO_ERROR) {
3269 // Restore client activity state.
3270 inputDesc->setClientActive(client, false);
3271 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003272 }
3273
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003274 ALOGV("%s input %d source = %d status = %d exit",
3275 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003276
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003277 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003278}
3279
Eric Laurent8fc147b2018-07-22 19:13:55 -07003280status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003281{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003282 ALOGV("%s portId %d", __FUNCTION__, portId);
3283
3284 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3285 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003286 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003287 return BAD_VALUE;
3288 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003289 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003290 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003291 if (!client->active()) {
3292 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003293 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003294 }
Carter Hsue6139d52021-07-08 10:30:20 +08003295 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003297
Eric Laurent8f42ea12018-08-08 09:08:25 -07003298 inputDesc->stop();
3299 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003300 auto current_source = inputDesc->source();
3301 setInputDevice(input, getNewInputDevice(inputDesc),
3302 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003303 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003304 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003305 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003306 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003307 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3308 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003309 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003310 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003311
3312 // automatically disable the remote submix output when input is stopped if not
3313 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003314 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003316 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003317 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003318 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3319 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003320 }
3321 if (address != "") {
3322 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3323 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003324 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003325 }
3326 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 resetInputDevice(input);
3328
3329 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3330 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003331 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3332 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003334 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003335 }
3336 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003337 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003338 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003339}
3340
Eric Laurent8fc147b2018-07-22 19:13:55 -07003341void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003342{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003343 ALOGV("%s portId %d", __FUNCTION__, portId);
3344
3345 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3346 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003348 return;
3349 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003350 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003351 audio_io_handle_t input = inputDesc->mIoHandle;
3352
Eric Laurent8f42ea12018-08-08 09:08:25 -07003353 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003354
Andy Hung39efb7a2018-09-26 15:39:28 -07003355 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003356
3357 // If no more clients are present in this session, park effects to an orphan chain
3358 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3359 if (clientsOnSession.size() == 0) {
3360 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3361 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003362 if (inputDesc->getClientCount() > 0) {
3363 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003364 return;
3365 }
3366
Eric Laurent05b90f82014-08-27 15:32:29 -07003367 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003368 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003369 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003370}
3371
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003373{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003374 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003375
3376 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003377 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003378 }
3379}
3380
Eric Laurent8f42ea12018-08-08 09:08:25 -07003381void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3382{
3383 stopInput(portId);
3384 releaseInput(portId);
3385}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003386
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003387bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3388 if (input->clientsList().size() == 0
3389 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3390 return true;
3391 }
3392 for (const auto& client : input->clientsList()) {
3393 sp<DeviceDescriptor> device =
3394 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3395 client->session());
3396 if (!input->supportedDevices().contains(device)) {
3397 return true;
3398 }
3399 }
3400 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3401 return false;
3402}
3403
Eric Laurent0dd51852019-04-19 18:18:58 -07003404void AudioPolicyManager::checkCloseInputs() {
3405 // After connecting or disconnecting an input device, close input if:
3406 // - it has no client (was just opened to check profile) OR
3407 // - none of its supported devices are connected anymore OR
3408 // - one of its clients cannot be routed to one of its supported
3409 // devices anymore. Otherwise update device selection
3410 std::vector<audio_io_handle_t> inputsToClose;
3411 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003412 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003413 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003414 }
3415 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003416 for (const audio_io_handle_t handle : inputsToClose) {
3417 ALOGV("%s closing input %d", __func__, handle);
3418 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003419 }
Eric Laurentd4692962014-05-05 18:13:44 -07003420}
3421
Vlad Popa87e0e582024-05-20 18:49:20 -07003422status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3423 const char *address __unused,
3424 bool enabled,
3425 audio_stream_type_t streamToDriveAbs)
3426{
3427 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3428 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3429 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3430 toString(streamToDriveAbs).c_str());
3431 return BAD_VALUE;
3432 }
3433
3434 if (enabled) {
3435 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3436 } else {
3437 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3438 }
3439
3440 return NO_ERROR;
3441}
3442
François Gaffie251c7f02018-11-07 10:41:08 +01003443void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003444{
3445 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003446 if (indexMin < 0 || indexMax < 0) {
3447 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3448 return;
3449 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003450 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003451
3452 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003453 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3454 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003455 continue;
3456 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003457 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003458 }
Eric Laurente552edb2014-03-10 17:42:56 -07003459}
3460
Eric Laurente0720872014-03-11 09:30:41 -07003461status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003462 int index,
3463 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003464{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003465 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003466 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3467 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3468 return NO_ERROR;
3469 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003470 ALOGV("%s: stream %s attributes=%s", __func__,
3471 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003472 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003473}
3474
Eric Laurente0720872014-03-11 09:30:41 -07003475status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003476 int *index,
3477 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003478{
François Gaffiec005e562018-11-06 15:04:49 +01003479 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3480 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003481 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003482 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003483 deviceTypes = mEngine->getOutputDevicesForStream(
3484 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003485 }
jiabin9a3361e2019-10-01 09:38:30 -07003486 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003487}
3488
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003489status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003490 int index,
3491 audio_devices_t device)
3492{
3493 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003494 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3495 if (group == VOLUME_GROUP_NONE) {
3496 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003497 return BAD_VALUE;
3498 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003499 ALOGV("%s: group %d matching with %s index %d",
3500 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003501 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003502 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003503 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003504 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3505 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3506 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3507 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003508 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3509
3510 status = setVolumeCurveIndex(index, device, curves);
3511 if (status != NO_ERROR) {
3512 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3513 return status;
3514 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003515
jiabin9a3361e2019-10-01 09:38:30 -07003516 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003517 auto curCurvAttrs = curves.getAttributes();
3518 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3519 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003520 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003521 } else if (!curves.getStreamTypes().empty()) {
3522 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003523 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003524 } else {
3525 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3526 return BAD_VALUE;
3527 }
jiabin9a3361e2019-10-01 09:38:30 -07003528 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3529 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003530
François Gaffiecfe17322018-11-07 13:41:29 +01003531 // update volume on all outputs and streams matching the following:
3532 // - The requested stream (or a stream matching for volume control) is active on the output
3533 // - The device (or devices) selected by the engine for this stream includes
3534 // the requested device
3535 // - For non default requested device, currently selected device on the output is either the
3536 // requested device or one of the devices selected by the engine for this stream
3537 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3538 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003539 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003540 for (size_t i = 0; i < mOutputs.size(); i++) {
3541 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003542 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003543
jiabin9a3361e2019-10-01 09:38:30 -07003544 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3545 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003546 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003547
3548 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003549 continue;
3550 }
3551 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3552 curDevices.find(device) == curDevices.end()) {
3553 continue;
3554 }
3555 bool applyVolume = false;
3556 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3557 curSrcDevices.insert(device);
3558 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003559 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3560 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003561 } else {
3562 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3563 }
3564 if (!applyVolume) {
3565 continue; // next output
3566 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003567 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3568 // If a higher priority strategy is active, and the output is routed to a device with a
3569 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003570 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003571 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003572 // If the volume source is active with higher priority source, ensure at least Sw Muted
3573 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003574 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3575 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3576 false /*preferredDevice*/);
3577 if (activeClients.empty()) {
3578 continue;
3579 }
3580 bool isPreempted = false;
3581 bool isHigherPriority = productStrategy < strategy;
3582 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003583 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003584 ALOGV("%s: Strategy=%d (\nrequester:\n"
3585 " group %d, volumeGroup=%d attributes=%s)\n"
3586 " higher priority source active:\n"
3587 " volumeGroup=%d attributes=%s) \n"
3588 " on output %zu, bailing out", __func__, productStrategy,
3589 group, group, toString(attributes).c_str(),
3590 client->volumeSource(), toString(client->attributes()).c_str(), i);
3591 applyVolume = false;
3592 isPreempted = true;
3593 break;
3594 }
3595 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003596 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003597 applyVolume = true;
3598 }
3599 }
3600 if (isPreempted || applyVolume) {
3601 break;
3602 }
3603 }
3604 if (!applyVolume) {
3605 continue; // next output
3606 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003607 }
François Gaffieed91f582020-01-31 10:35:37 +01003608 //FIXME: workaround for truncated touch sounds
3609 // delayed volume change for system stream to be removed when the problem is
3610 // handled by system UI
3611 status_t volStatus = checkAndSetVolume(
3612 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003613 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003614 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3615 if (volStatus != NO_ERROR) {
3616 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003617 }
3618 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003619
3620 // update voice volume if the an active call route exists
3621 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3622 && (curSrcDevices.find(
3623 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3624 != curSrcDevices.end())) {
3625 bool isVoiceVolSrc;
3626 bool isBtScoVolSrc;
3627 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3628 isVoiceVolSrc, isBtScoVolSrc, __func__)
3629 && (isVoiceVolSrc || isBtScoVolSrc)) {
3630 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3631 }
3632 }
3633
François Gaffiecfe17322018-11-07 13:41:29 +01003634 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3635 return status;
3636}
3637
François Gaffieaaac0fd2018-11-22 17:56:39 +01003638status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003639 audio_devices_t device,
3640 IVolumeCurves &volumeCurves)
3641{
3642 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3643 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003644 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3645 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003646 (index > volumeCurves.getVolumeIndexMax())) {
3647 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3648 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3649 return BAD_VALUE;
3650 }
3651 if (!audio_is_output_device(device)) {
3652 return BAD_VALUE;
3653 }
3654
3655 // Force max volume if stream cannot be muted
3656 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3657
François Gaffieaaac0fd2018-11-22 17:56:39 +01003658 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003659 volumeCurves.addCurrentVolumeIndex(device, index);
3660 return NO_ERROR;
3661}
3662
3663status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3664 int &index,
3665 audio_devices_t device)
3666{
3667 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3668 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003669 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003670 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003671 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003672 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003673 }
jiabin9a3361e2019-10-01 09:38:30 -07003674 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003675}
3676
3677status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3678 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003679 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003680{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003681 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003682 return BAD_VALUE;
3683 }
jiabin9a3361e2019-10-01 09:38:30 -07003684 index = curves.getVolumeIndex(deviceTypes);
3685 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003686 return NO_ERROR;
3687}
3688
3689status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3690 int &index)
3691{
3692 index = getVolumeCurves(attr).getVolumeIndexMin();
3693 return NO_ERROR;
3694}
3695
3696status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3697 int &index)
3698{
3699 index = getVolumeCurves(attr).getVolumeIndexMax();
3700 return NO_ERROR;
3701}
3702
Eric Laurent36829f92017-04-07 19:04:42 -07003703audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003704{
3705 // select one output among several suitable for global effects.
3706 // The priority is as follows:
3707 // 1: An offloaded output. If the effect ends up not being offloadable,
3708 // AudioFlinger will invalidate the track and the offloaded output
3709 // will be closed causing the effect to be moved to a PCM output.
3710 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003711 // 3: The primary output
3712 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003713
François Gaffiec005e562018-11-06 15:04:49 +01003714 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3715 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003716 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003717
Eric Laurent36829f92017-04-07 19:04:42 -07003718 if (outputs.size() == 0) {
3719 return AUDIO_IO_HANDLE_NONE;
3720 }
Eric Laurente552edb2014-03-10 17:42:56 -07003721
Eric Laurent36829f92017-04-07 19:04:42 -07003722 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3723 bool activeOnly = true;
3724
3725 while (output == AUDIO_IO_HANDLE_NONE) {
3726 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3727 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3728 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3729
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003730 for (audio_io_handle_t output : outputs) {
3731 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003732 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003733 continue;
3734 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003735 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3736 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003737 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003738 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003739 }
3740 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003741 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003742 }
3743 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003744 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003745 }
3746 }
3747 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3748 output = outputOffloaded;
3749 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3750 output = outputDeepBuffer;
3751 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3752 output = outputPrimary;
3753 } else {
3754 output = outputs[0];
3755 }
3756 activeOnly = false;
3757 }
3758
3759 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003760 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3761 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003762 mMusicEffectOutput = output;
3763 }
3764
3765 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003766 return output;
3767}
3768
Eric Laurent36829f92017-04-07 19:04:42 -07003769audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3770{
3771 return selectOutputForMusicEffects();
3772}
3773
Eric Laurente0720872014-03-11 09:30:41 -07003774status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003775 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003776 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003777 int session,
3778 int id)
3779{
Shunkai Yao29d10572024-03-19 04:31:47 +00003780 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003781 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003782 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003783 index = mInputs.indexOfKey(io);
3784 if (index < 0) {
3785 ALOGW("registerEffect() unknown io %d", io);
3786 return INVALID_OPERATION;
3787 }
Eric Laurente552edb2014-03-10 17:42:56 -07003788 }
3789 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003790 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3791 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3792 || strategy == PRODUCT_STRATEGY_NONE));
3793 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003794}
3795
Eric Laurentc241b0d2018-11-28 09:08:49 -08003796status_t AudioPolicyManager::unregisterEffect(int id)
3797{
3798 if (mEffects.getEffect(id) == nullptr) {
3799 return INVALID_OPERATION;
3800 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003801 if (mEffects.isEffectEnabled(id)) {
3802 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3803 setEffectEnabled(id, false);
3804 }
3805 return mEffects.unregisterEffect(id);
3806}
3807
3808status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3809{
3810 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3811 if (effect == nullptr) {
3812 return INVALID_OPERATION;
3813 }
3814
3815 status_t status = mEffects.setEffectEnabled(id, enabled);
3816 if (status == NO_ERROR) {
3817 mInputs.trackEffectEnabled(effect, enabled);
3818 }
3819 return status;
3820}
3821
Eric Laurent6c796322019-04-09 14:13:17 -07003822
3823status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3824{
3825 mEffects.moveEffects(ids, io);
3826 return NO_ERROR;
3827}
3828
Eric Laurentc75307b2015-03-17 15:29:32 -07003829bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3830{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003831 auto vs = toVolumeSource(stream, false);
3832 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003833}
3834
3835bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3836{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003837 auto vs = toVolumeSource(stream, false);
3838 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003839}
3840
Eric Laurente0720872014-03-11 09:30:41 -07003841bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003842{
3843 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003844 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003845 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003846 return true;
3847 }
3848 }
3849 return false;
3850}
3851
Eric Laurent275e8e92014-11-30 15:14:47 -08003852// Register a list of custom mixes with their attributes and format.
3853// When a mix is registered, corresponding input and output profiles are
3854// added to the remote submix hw module. The profile contains only the
3855// parameters (sampling rate, format...) specified by the mix.
3856// The corresponding input remote submix device is also connected.
3857//
3858// When a remote submix device is connected, the address is checked to select the
3859// appropriate profile and the corresponding input or output stream is opened.
3860//
3861// When capture starts, getInputForAttr() will:
3862// - 1 look for a mix matching the address passed in attribtutes tags if any
3863// - 2 if none found, getDeviceForInputSource() will:
3864// - 2.1 look for a mix matching the attributes source
3865// - 2.2 if none found, default to device selection by policy rules
3866// At this time, the corresponding output remote submix device is also connected
3867// and active playback use cases can be transferred to this mix if needed when reconnecting
3868// after AudioTracks are invalidated
3869//
3870// When playback starts, getOutputForAttr() will:
3871// - 1 look for a mix matching the address passed in attribtutes tags if any
3872// - 2 if none found, look for a mix matching the attributes usage
3873// - 3 if none found, default to device and output selection by policy rules.
3874
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003875status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003876{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3878 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003879 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003880 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003881 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003882 // examine each mix's route type
3883 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003884 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003885 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3886 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3887 ALOGE("Unsupported Policy Mix %zu of %zu: "
3888 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3889 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003890 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003891 break;
3892 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003893 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3894 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003895 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003896 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3897 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003898 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003899 rSubmixModule = mHwModules.getModuleFromName(
3900 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3901 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003902 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 i);
3904 res = INVALID_OPERATION;
3905 break;
3906 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003907 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003908
Eric Laurent97ac8712018-07-27 18:59:02 -07003909 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003910 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003911 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003912 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003913 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3914 } else {
3915 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3916 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003917 }
François Gaffie036e1e92015-03-19 10:16:24 +01003918
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003919 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003920 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003921 res = INVALID_OPERATION;
3922 break;
3923 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003924 audio_config_t outputConfig = mix.mFormat;
3925 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003926 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3927 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003928 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3929 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003930 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003931 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3932 audio_is_linear_pcm(outputConfig.format)
3933 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003934 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003935 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3936 audio_is_linear_pcm(inputConfig.format)
3937 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003938
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003939 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003940 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003941 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003942 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003943 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003944 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003945 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003946 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3947 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003948 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003949 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003950 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003951
3952 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3953 mix.mDeviceType, mix.mDeviceAddress,
3954 String8(), AUDIO_FORMAT_DEFAULT);
3955 if (device == nullptr) {
3956 res = INVALID_OPERATION;
3957 break;
3958 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003959
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003960 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003961 // First try to find an already opened output supporting the device
3962 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003963 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003964
Eric Laurentc529cf62020-04-17 18:19:10 -07003965 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003966 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003967 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003968 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003969 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003970 } else {
3971 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003972 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003973 }
3974 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003975 // If no output found, try to find a direct output profile supporting the device
3976 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3977 sp<HwModule> module = mHwModules[i];
3978 for (size_t j = 0;
3979 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3980 j++) {
3981 sp<IOProfile> profile = module->getOutputProfiles()[j];
3982 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3983 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3984 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003985 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003986 res = INVALID_OPERATION;
3987 } else {
3988 foundOutput = true;
3989 }
3990 }
3991 }
3992 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003993 if (res != NO_ERROR) {
3994 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003995 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003996 res = INVALID_OPERATION;
3997 break;
3998 } else if (!foundOutput) {
3999 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004000 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004001 res = INVALID_OPERATION;
4002 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004003 } else {
4004 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004005 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 }
Eric Laurentc722f302014-12-10 11:21:49 -08004007 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004008 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004009 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004010 if (audio_flags::audio_mix_ownership()) {
4011 // Only unregister mixes that were actually registered to not accidentally unregister
4012 // mixes that already existed previously.
4013 unregisterPolicyMixes(registeredMixes);
4014 registeredMixes.clear();
4015 } else {
4016 unregisterPolicyMixes(mixes);
4017 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004018 } else if (checkOutputs) {
4019 checkForDeviceAndOutputChanges();
4020 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004021 }
4022 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004023}
4024
4025status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4026{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004027 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004028 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004029 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 sp<HwModule> rSubmixModule;
4031 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004032 for (const auto& mix : mixes) {
4033 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004034
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004036 rSubmixModule = mHwModules.getModuleFromName(
4037 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4038 if (rSubmixModule == 0) {
4039 res = INVALID_OPERATION;
4040 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004041 }
4042 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004043
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004044 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004045
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004046 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004047 res = INVALID_OPERATION;
4048 continue;
4049 }
4050
Marvin Ramin0783e202024-03-05 12:45:50 +01004051 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004052 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004053 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4054 status_t currentRes =
4055 setDeviceConnectionStateInt(device,
4056 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4057 address.c_str(),
4058 "remote-submix",
4059 AUDIO_FORMAT_DEFAULT);
4060 if (!audio_flags::audio_mix_ownership()) {
4061 res = currentRes;
4062 }
4063 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004064 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004065 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004066 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004067 }
4068 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004069 }
jiabin5740f082019-08-19 15:08:30 -07004070 rSubmixModule->removeOutputProfile(address.c_str());
4071 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004072
Kevin Rocard153f92d2018-12-18 18:33:28 -08004073 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004074 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 res = INVALID_OPERATION;
4076 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004077 } else {
4078 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004079 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004080 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004081 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004082
4083 if (res == NO_ERROR && checkOutputs) {
4084 checkForDeviceAndOutputChanges();
4085 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004086 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004087 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004088}
4089
Marvin Raminbdefaf02023-11-01 09:10:32 +01004090status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4091 if (!audio_flags::audio_mix_test_api()) {
4092 return INVALID_OPERATION;
4093 }
4094
4095 _aidl_return.clear();
4096 _aidl_return.reserve(mPolicyMixes.size());
4097 for (const auto &policyMix: mPolicyMixes) {
4098 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4099 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4100 policyMix->mCbFlags);
4101 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004102 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004103 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004104 }
4105
Vlad Popaa5d73f32024-03-08 16:05:38 -08004106 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004107 return OK;
4108}
4109
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004110status_t AudioPolicyManager::updatePolicyMix(
4111 const AudioMix& mix,
4112 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4113 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4114 if (res == NO_ERROR) {
4115 checkForDeviceAndOutputChanges();
4116 updateCallAndOutputRouting();
4117 }
4118 return res;
4119}
4120
Mikhail Naganov100f0122018-11-29 11:22:16 -08004121void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4122{
4123 size_t i = 0;
4124 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4125 for (const auto& fmt : mManualSurroundFormats) {
4126 if (i++ != 0) dst->append(", ");
4127 std::string sfmt;
4128 FormatConverter::toString(fmt, sfmt);
4129 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4130 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4131 }
4132}
4133
Eric Laurentc529cf62020-04-17 18:19:10 -07004134// Returns true if all devices types match the predicate and are supported by one HW module
4135bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004136 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004137 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004138 const char *context,
4139 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004140 for (size_t i = 0; i < devices.size(); i++) {
4141 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004142 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004143 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004144 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004145 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004146 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004147 return false;
4148 }
4149 }
4150 return true;
4151}
4152
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004153void AudioPolicyManager::changeOutputDevicesMuteState(
4154 const AudioDeviceTypeAddrVector& devices) {
4155 ALOGVV("%s() num devices %zu", __func__, devices.size());
4156
4157 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4158 getSoftwareOutputsForDevices(devices);
4159
4160 for (size_t i = 0; i < outputs.size(); i++) {
4161 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4162 DeviceVector prevDevices = outputDesc->devices();
4163 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4164 }
4165}
4166
4167std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4168 const AudioDeviceTypeAddrVector& devices) const
4169{
4170 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4171 DeviceVector deviceDescriptors;
4172 for (size_t j = 0; j < devices.size(); j++) {
4173 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4174 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4175 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4176 ALOGE("%s: device type %#x address %s not supported or not an output device",
4177 __func__, devices[j].mType, devices[j].getAddress());
4178 continue;
4179 }
4180 deviceDescriptors.add(desc);
4181 }
4182 for (size_t i = 0; i < mOutputs.size(); i++) {
4183 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4184 continue;
4185 }
4186 outputs.push_back(mOutputs.valueAt(i));
4187 }
4188 return outputs;
4189}
4190
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004191status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004192 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004193 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004194 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4195 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004196 }
4197 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004198 if (res != NO_ERROR) {
4199 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4200 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004201 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004202
4203 checkForDeviceAndOutputChanges();
4204 updateCallAndOutputRouting();
4205
4206 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004207}
4208
4209status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4210 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004211 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4212 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004213 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004214 __FUNCTION__, uid);
4215 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004216 }
4217
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 checkForDeviceAndOutputChanges();
4219 updateCallAndOutputRouting();
4220
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004221 return res;
4222}
4223
Eric Laurent2517af32020-11-25 15:31:27 +01004224
jiabin0a488932020-08-07 17:32:40 -07004225status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4226 device_role_t role,
4227 const AudioDeviceTypeAddrVector &devices) {
4228 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4229 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004230
Eric Laurentc529cf62020-04-17 18:19:10 -07004231 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004232 return BAD_VALUE;
4233 }
jiabin0a488932020-08-07 17:32:40 -07004234 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004235 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004236 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4237 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004238 return status;
4239 }
4240
4241 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004242
4243 bool forceVolumeReeval = false;
4244 // FIXME: workaround for truncated touch sounds
4245 // to be removed when the problem is handled by system UI
4246 uint32_t delayMs = 0;
4247 if (strategy == mCommunnicationStrategy) {
4248 forceVolumeReeval = true;
4249 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4250 updateInputRouting();
4251 }
4252 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004253
4254 return NO_ERROR;
4255}
4256
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004257void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4258 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004259{
4260 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004261 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004262 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004263 // Only apply special touch sound delay once
4264 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004265 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004266 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004267 for (size_t i = 0; i < mOutputs.size(); i++) {
4268 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4269 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004270 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4271 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004272 // As done in setDeviceConnectionState, we could also fix default device issue by
4273 // preventing the force re-routing in case of default dev that distinguishes on address.
4274 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004275 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004276 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004277 // If the device is using preferred mixer attributes, the output need to reopen
4278 // with default configuration when the new selected devices are different from
4279 // current routing devices.
4280 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4281 continue;
4282 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304283
4284 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4285 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004286 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004287 // Only apply special touch sound delay once
4288 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004289 }
4290 if (forceVolumeReeval && !newDevices.isEmpty()) {
4291 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4292 }
4293 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004294 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004295 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004296}
4297
Eric Laurent2517af32020-11-25 15:31:27 +01004298void AudioPolicyManager::updateInputRouting() {
4299 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304300 // Skip for hotword recording as the input device switch
4301 // is handled within sound trigger HAL
4302 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4303 continue;
4304 }
Eric Laurent2517af32020-11-25 15:31:27 +01004305 auto newDevice = getNewInputDevice(activeDesc);
4306 // Force new input selection if the new device can not be reached via current input
4307 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4308 setInputDevice(activeDesc->mIoHandle, newDevice);
4309 } else {
4310 closeInput(activeDesc->mIoHandle);
4311 }
4312 }
4313}
4314
Paul Wang5d7cdb52022-11-22 09:45:06 +00004315status_t
4316AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4317 device_role_t role,
4318 const AudioDeviceTypeAddrVector &devices) {
4319 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4320 dumpAudioDeviceTypeAddrVector(devices).c_str());
4321
Eric Laurent78fedbf2023-03-09 14:40:44 +01004322 if (!areAllDevicesSupported(
4323 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004324 return BAD_VALUE;
4325 }
4326 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4327 if (status != NO_ERROR) {
4328 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4329 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4330 return status;
4331 }
4332
4333 checkForDeviceAndOutputChanges();
4334
4335 bool forceVolumeReeval = false;
4336 // TODO(b/263479999): workaround for truncated touch sounds
4337 // to be removed when the problem is handled by system UI
4338 uint32_t delayMs = 0;
4339 if (strategy == mCommunnicationStrategy) {
4340 forceVolumeReeval = true;
4341 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4342 updateInputRouting();
4343 }
4344 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4345
4346 return NO_ERROR;
4347}
4348
4349status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4350 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004351{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004352 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004353
Paul Wang5d7cdb52022-11-22 09:45:06 +00004354 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004355 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004356 ALOGW_IF(status != NAME_NOT_FOUND,
4357 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004358 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004359 return status;
4360 }
4361
4362 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004363
4364 bool forceVolumeReeval = false;
4365 // FIXME: workaround for truncated touch sounds
4366 // to be removed when the problem is handled by system UI
4367 uint32_t delayMs = 0;
4368 if (strategy == mCommunnicationStrategy) {
4369 forceVolumeReeval = true;
4370 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4371 updateInputRouting();
4372 }
4373 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004374
4375 return NO_ERROR;
4376}
4377
jiabin0a488932020-08-07 17:32:40 -07004378status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4379 device_role_t role,
4380 AudioDeviceTypeAddrVector &devices) {
4381 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004382}
4383
Jiabin Huang3b98d322020-09-03 17:54:16 +00004384status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4385 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4386 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4387 dumpAudioDeviceTypeAddrVector(devices).c_str());
4388
Mikhail Naganov55773032020-10-01 15:08:13 -07004389 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004390 return BAD_VALUE;
4391 }
4392 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4393 ALOGW_IF(status != NO_ERROR,
4394 "Engine could not set preferred devices %s for audio source %d role %d",
4395 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4396
4397 return status;
4398}
4399
4400status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4401 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4402 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4403 dumpAudioDeviceTypeAddrVector(devices).c_str());
4404
Mikhail Naganov55773032020-10-01 15:08:13 -07004405 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004406 return BAD_VALUE;
4407 }
4408 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4409 ALOGW_IF(status != NO_ERROR,
4410 "Engine could not add preferred devices %s for audio source %d role %d",
4411 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4412
Eric Laurent2517af32020-11-25 15:31:27 +01004413 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004414 return status;
4415}
4416
4417status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4418 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4419{
4420 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4421 dumpAudioDeviceTypeAddrVector(devices).c_str());
4422
Eric Laurent78fedbf2023-03-09 14:40:44 +01004423 if (!areAllDevicesSupported(
4424 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004425 return BAD_VALUE;
4426 }
4427
4428 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4429 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004430 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004431 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004432 if (status == NO_ERROR) {
4433 updateInputRouting();
4434 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004435 return status;
4436}
4437
4438status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4439 device_role_t role) {
4440 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4441
4442 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004443 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004444 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004445 if (status == NO_ERROR) {
4446 updateInputRouting();
4447 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004448 return status;
4449}
4450
4451status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4452 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4453 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4454}
4455
Oscar Azucena90e77632019-11-27 17:12:28 -08004456status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004457 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004458 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004459 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4460 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004461 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004462 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4463 if (status != NO_ERROR) {
4464 ALOGE("%s() could not set device affinity for userId %d",
4465 __FUNCTION__, userId);
4466 return status;
4467 }
4468
4469 // reevaluate outputs for all devices
4470 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004471 changeOutputDevicesMuteState(devices);
4472 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4473 true /* skipDelays */);
4474 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004475
4476 return NO_ERROR;
4477}
4478
4479status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004480 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004481 AudioDeviceTypeAddrVector devices;
4482 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004483 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4484 if (status != NO_ERROR) {
4485 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4486 __FUNCTION__, userId);
4487 return status;
4488 }
4489
4490 // reevaluate outputs for all devices
4491 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004492 changeOutputDevicesMuteState(devices);
4493 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4494 true /* skipDelays */);
4495 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004496
4497 return NO_ERROR;
4498}
4499
Andy Hungc29d82b2018-10-05 12:23:17 -07004500void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004501{
Andy Hungc29d82b2018-10-05 12:23:17 -07004502 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004503 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004504 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004505 std::string stateLiteral;
4506 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004507 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004508 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4509 "communications", "media", "record", "dock", "system",
4510 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4511 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4512 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004513 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4514 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4515 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4516 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4517 dst->append(" (MANUAL: ");
4518 dumpManualSurroundFormats(dst);
4519 dst->append(")");
4520 }
4521 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004522 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004523 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4524 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004525 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004526 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004527
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004528 dst->append("\n");
4529 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4530 dst->append("\n");
4531 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004532 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004533 mOutputs.dump(dst);
4534 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004535 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004536 mAudioPatches.dump(dst);
4537 mPolicyMixes.dump(dst);
4538 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004539
Kevin Rocardb99cc752019-03-21 20:52:24 -07004540 dst->appendFormat(" AllowedCapturePolicies:\n");
4541 for (auto& policy : mAllowedCapturePolicies) {
4542 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4543 }
4544
jiabina84c3d32022-12-02 18:59:55 +00004545 dst->appendFormat(" Preferred mixer audio configuration:\n");
4546 for (const auto it : mPreferredMixerAttrInfos) {
4547 dst->appendFormat(" - device port id: %d\n", it.first);
4548 for (const auto preferredMixerInfoIt : it.second) {
4549 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4550 preferredMixerInfoIt.second->dump(dst);
4551 }
4552 }
4553
François Gaffiec005e562018-11-06 15:04:49 +01004554 dst->appendFormat("\nPolicy Engine dump:\n");
4555 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004556
4557 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4558 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4559 dst->appendFormat(" - device type: %s, driving stream %d\n",
4560 dumpDeviceTypes({it.first}).c_str(),
4561 mEngine->getVolumeGroupForAttributes(it.second));
4562 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004563}
4564
4565status_t AudioPolicyManager::dump(int fd)
4566{
4567 String8 result;
4568 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004569 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004570 return NO_ERROR;
4571}
4572
Kevin Rocardb99cc752019-03-21 20:52:24 -07004573status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4574{
4575 mAllowedCapturePolicies[uid] = capturePolicy;
4576 return NO_ERROR;
4577}
4578
Eric Laurente552edb2014-03-10 17:42:56 -07004579// This function checks for the parameters which can be offloaded.
4580// This can be enhanced depending on the capability of the DSP and policy
4581// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004582audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004583{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004584 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004585 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004586 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004587 offloadInfo.format,
4588 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4589 offloadInfo.has_video);
4590
jiabin2b9d5a12021-12-10 01:06:29 +00004591 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004592 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004593 }
4594
4595 // See if there is a profile to support this.
4596 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004597 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004598 offloadInfo.sample_rate,
4599 offloadInfo.format,
4600 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004601 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4602 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004603 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4604 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4605 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004606 if (profile == nullptr) {
4607 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4608 }
4609 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4610 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4611 }
4612 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004613}
4614
Michael Chana94fbb22018-04-24 14:31:19 +10004615bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4616 const audio_attributes_t& attributes) {
4617 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004618 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004619 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4620 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004621 config.sample_rate,
4622 config.format,
4623 config.channel_mask,
4624 output_flags,
4625 true /* directOnly */);
4626 ALOGV("%s() profile %sfound with name: %s, "
4627 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4628 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004629 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004630 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004631
4632 // also try the MSD module if compatible profile not found
4633 if (profile == nullptr) {
4634 profile = getMsdProfileForOutput(outputDevices,
4635 config.sample_rate,
4636 config.format,
4637 config.channel_mask,
4638 output_flags,
4639 true /* directOnly */);
4640 ALOGV("%s() MSD profile %sfound with name: %s, "
4641 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4642 __FUNCTION__, profile != 0 ? "" : "NOT ",
4643 (profile != 0 ? profile->getTagName().c_str() : "null"),
4644 config.sample_rate, config.format, config.channel_mask, output_flags);
4645 }
4646 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004647}
4648
jiabin2b9d5a12021-12-10 01:06:29 +00004649bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4650 bool durationIgnored) {
4651 if (mMasterMono) {
4652 return false; // no offloading if mono is set.
4653 }
4654
4655 // Check if offload has been disabled
4656 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4657 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4658 return false;
4659 }
4660
4661 // Check if stream type is music, then only allow offload as of now.
4662 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4663 {
4664 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4665 return false;
4666 }
4667
4668 //TODO: enable audio offloading with video when ready
4669 const bool allowOffloadWithVideo =
4670 property_get_bool("audio.offload.video", false /* default_value */);
4671 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4672 ALOGV("%s: has_video == true, returning false", __func__);
4673 return false;
4674 }
4675
4676 //If duration is less than minimum value defined in property, return false
4677 const int min_duration_secs = property_get_int32(
4678 "audio.offload.min.duration.secs", -1 /* default_value */);
4679 if (!durationIgnored) {
4680 if (min_duration_secs >= 0) {
4681 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4682 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4683 __func__, min_duration_secs);
4684 return false;
4685 }
4686 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4687 ALOGV("%s: Offload denied by duration < default min(=%u)",
4688 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4689 return false;
4690 }
4691 }
4692
4693 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4694 // creating an offloaded track and tearing it down immediately after start when audioflinger
4695 // detects there is an active non offloadable effect.
4696 // FIXME: We should check the audio session here but we do not have it in this context.
4697 // This may prevent offloading in rare situations where effects are left active by apps
4698 // in the background.
4699 if (mEffects.isNonOffloadableEffectEnabled()) {
4700 return false;
4701 }
4702
4703 return true;
4704}
4705
4706audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4707 const audio_config_t *config) {
4708 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4709 offloadInfo.format = config->format;
4710 offloadInfo.sample_rate = config->sample_rate;
4711 offloadInfo.channel_mask = config->channel_mask;
4712 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4713 offloadInfo.has_video = false;
4714 offloadInfo.is_streaming = false;
4715 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4716
4717 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4718 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4719 audio_flags_to_audio_output_flags(attr->flags, &flags);
4720 // only retain flags that will drive compressed offload or passthrough
4721 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4722 if (offloadPossible) {
4723 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4724 }
4725 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4726
Dorin Drimusfae3c642022-03-17 18:36:30 +01004727 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004728 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004729 DeviceVector outputDevices = engineOutputDevices;
4730 // the MSD module checks for different conditions and output devices
4731 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4732 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4733 continue;
4734 }
4735 outputDevices = getMsdAudioOutDevices();
4736 }
jiabin2b9d5a12021-12-10 01:06:29 +00004737 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004738 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004739 config->sample_rate, nullptr /*updatedSamplingRate*/,
4740 config->format, nullptr /*updatedFormat*/,
4741 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004742 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004743 continue;
4744 }
4745 // reject profiles not corresponding to a device currently available
4746 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4747 continue;
4748 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004749 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4750 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004751 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004752 != AUDIO_DIRECT_NOT_SUPPORTED) {
4753 // Already reports offload gapless supported. No need to report offload support.
4754 continue;
4755 }
4756 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4757 != AUDIO_OUTPUT_FLAG_NONE) {
4758 // If offload gapless is reported, no need to report offload support.
4759 directMode = (audio_direct_mode_t) ((directMode &
4760 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4761 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4762 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004763 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004764 }
4765 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004766 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004767 }
4768 }
4769 }
4770 return directMode;
4771}
4772
Dorin Drimusf2196d82022-01-03 12:11:18 +01004773status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4774 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004775 if (mEffects.isNonOffloadableEffectEnabled()) {
4776 return OK;
4777 }
jiabinf1c73972022-04-14 16:28:52 -07004778 DeviceVector devices;
4779 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004780 if (status != OK) {
4781 return status;
4782 }
4783 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4784 if (devices.empty()) {
4785 return OK; // no output devices for the attributes
4786 }
jiabinf1c73972022-04-14 16:28:52 -07004787 return getProfilesForDevices(devices, audioProfilesVector,
4788 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004789}
4790
jiabina84c3d32022-12-02 18:59:55 +00004791status_t AudioPolicyManager::getSupportedMixerAttributes(
4792 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4793 ALOGV("%s, portId=%d", __func__, portId);
4794 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4795 if (deviceDescriptor == nullptr) {
4796 ALOGE("%s the requested device is currently unavailable", __func__);
4797 return BAD_VALUE;
4798 }
jiabin96daffc2023-05-11 17:51:55 +00004799 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4800 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4801 deviceDescriptor->type());
4802 return BAD_VALUE;
4803 }
jiabina84c3d32022-12-02 18:59:55 +00004804 for (const auto& hwModule : mHwModules) {
4805 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4806 if (curProfile->supportsDevice(deviceDescriptor)) {
4807 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4808 }
4809 }
4810 }
4811 return NO_ERROR;
4812}
4813
4814status_t AudioPolicyManager::setPreferredMixerAttributes(
4815 const audio_attributes_t *attr,
4816 audio_port_handle_t portId,
4817 uid_t uid,
4818 const audio_mixer_attributes_t *mixerAttributes) {
4819 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4820 "mixerBehavior=%d}, uid=%d, portId=%u",
4821 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4822 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4823 mixerAttributes->mixer_behavior, uid, portId);
4824 if (attr->usage != AUDIO_USAGE_MEDIA) {
4825 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4826 return BAD_VALUE;
4827 }
4828 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4829 if (deviceDescriptor == nullptr) {
4830 ALOGE("%s the requested device is currently unavailable", __func__);
4831 return BAD_VALUE;
4832 }
4833 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4834 ALOGE("%s(%d), type=%d, is not a usb output device",
4835 __func__, portId, deviceDescriptor->type());
4836 return BAD_VALUE;
4837 }
4838
4839 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4840 audio_flags_to_audio_output_flags(attr->flags, &flags);
4841 flags = (audio_output_flags_t) (flags |
4842 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4843 sp<IOProfile> profile = nullptr;
4844 DeviceVector devices(deviceDescriptor);
4845 for (const auto& hwModule : mHwModules) {
4846 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4847 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004848 && curProfile->getCompatibilityScore(
4849 devices,
4850 mixerAttributes->config.sample_rate,
4851 nullptr /*updatedSamplingRate*/,
4852 mixerAttributes->config.format,
4853 nullptr /*updatedFormat*/,
4854 mixerAttributes->config.channel_mask,
4855 nullptr /*updatedChannelMask*/,
4856 flags,
4857 false /*exactMatchRequiredForInputFlags*/)
4858 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004859 profile = curProfile;
4860 break;
4861 }
4862 }
4863 }
4864 if (profile == nullptr) {
4865 ALOGE("%s, there is no compatible profile found", __func__);
4866 return BAD_VALUE;
4867 }
4868
4869 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4870 sp<PreferredMixerAttributesInfo>::make(
4871 uid, portId, profile, flags, *mixerAttributes);
4872 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4873 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4874
4875 // If 1) there is any client from the preferred mixer configuration owner that is currently
4876 // active and matches the strategy and 2) current output is on the preferred device and the
4877 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4878 // configuration.
4879 std::vector<audio_io_handle_t> outputsToReopen;
4880 for (size_t i = 0; i < mOutputs.size(); i++) {
4881 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004882 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4883 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004884 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004885 } else {
4886 for (const auto &client: output->getActiveClients()) {
4887 if (client->uid() == uid && client->strategy() == strategy) {
4888 client->setIsInvalid();
4889 outputsToReopen.push_back(output->mIoHandle);
4890 }
jiabina84c3d32022-12-02 18:59:55 +00004891 }
4892 }
4893 }
4894 }
4895 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4896 config.sample_rate = mixerAttributes->config.sample_rate;
4897 config.channel_mask = mixerAttributes->config.channel_mask;
4898 config.format = mixerAttributes->config.format;
4899 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004900 sp<SwAudioOutputDescriptor> desc =
4901 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4902 if (desc == nullptr) {
4903 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4904 continue;
4905 }
jiabin220eea12024-05-17 17:55:20 +00004906 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004907 }
4908
4909 return NO_ERROR;
4910}
4911
4912sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004913 audio_port_handle_t devicePortId,
4914 product_strategy_t strategy,
4915 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004916 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4917 if (it == mPreferredMixerAttrInfos.end()) {
4918 return nullptr;
4919 }
jiabind9a58d32023-06-01 17:57:30 +00004920 if (activeBitPerfectPreferred) {
4921 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004922 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004923 return info;
4924 }
4925 }
jiabina84c3d32022-12-02 18:59:55 +00004926 }
jiabind9a58d32023-06-01 17:57:30 +00004927 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4928 return strategyMatchedMixerAttrInfoIt == it->second.end()
4929 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004930}
4931
4932status_t AudioPolicyManager::getPreferredMixerAttributes(
4933 const audio_attributes_t *attr,
4934 audio_port_handle_t portId,
4935 audio_mixer_attributes_t* mixerAttributes) {
4936 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4937 portId, mEngine->getProductStrategyForAttributes(*attr));
4938 if (info == nullptr) {
4939 return NAME_NOT_FOUND;
4940 }
4941 *mixerAttributes = info->getMixerAttributes();
4942 return NO_ERROR;
4943}
4944
4945status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4946 audio_port_handle_t portId,
4947 uid_t uid) {
4948 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4949 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4950 if (preferredMixerAttrInfo == nullptr) {
4951 return NAME_NOT_FOUND;
4952 }
4953 if (preferredMixerAttrInfo->getUid() != uid) {
4954 ALOGE("%s, requested uid=%d, owned uid=%d",
4955 __func__, uid, preferredMixerAttrInfo->getUid());
4956 return PERMISSION_DENIED;
4957 }
4958 mPreferredMixerAttrInfos[portId].erase(strategy);
4959 if (mPreferredMixerAttrInfos[portId].empty()) {
4960 mPreferredMixerAttrInfos.erase(portId);
4961 }
4962
4963 // Reconfig existing output
4964 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4965 for (size_t i = 0; i < mOutputs.size(); i++) {
4966 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4967 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4968 }
4969 }
4970 for (const auto output : potentialOutputsToReopen) {
4971 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4972 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4973 preferredMixerAttrInfo->getFlags())) {
4974 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4975 }
4976 }
4977 return NO_ERROR;
4978}
4979
Eric Laurent6a94d692014-05-20 11:18:06 -07004980status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4981 audio_port_type_t type,
4982 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004983 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 unsigned int *generation)
4985{
jiabin19cdba52020-11-24 11:28:58 -08004986 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4987 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 return BAD_VALUE;
4989 }
4990 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004991 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 *num_ports = 0;
4993 }
4994
4995 size_t portsWritten = 0;
4996 size_t portsMax = *num_ports;
4997 *num_ports = 0;
4998 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004999 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5000 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005002 for (const auto& dev : mAvailableOutputDevices) {
5003 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005004 continue;
5005 }
5006 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005007 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005008 }
5009 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 }
5012 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005013 for (const auto& dev : mAvailableInputDevices) {
5014 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005015 continue;
5016 }
5017 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005018 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005019 }
5020 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005022 }
5023 }
5024 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5025 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5026 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5027 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5028 }
5029 *num_ports += mInputs.size();
5030 }
5031 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005032 size_t numOutputs = 0;
5033 for (size_t i = 0; i < mOutputs.size(); i++) {
5034 if (!mOutputs[i]->isDuplicated()) {
5035 numOutputs++;
5036 if (portsWritten < portsMax) {
5037 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5038 }
5039 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 }
Eric Laurent84c70242014-06-23 08:46:27 -07005041 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 }
5043 }
jiabina84c3d32022-12-02 18:59:55 +00005044
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005046 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 return NO_ERROR;
5048}
5049
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005050status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5051 std::vector<media::AudioPortFw>* _aidl_return) {
5052 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5053 audio_port_v7 port;
5054 dev->toAudioPort(&port);
5055 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5056 _aidl_return->push_back(std::move(aidlPort));
5057 return OK;
5058 };
5059
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005060 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005061 for (const auto& dev : module->getDeclaredDevices()) {
5062 if (role == media::AudioPortRole::NONE ||
5063 ((role == media::AudioPortRole::SOURCE)
5064 == audio_is_input_device(dev->type()))) {
5065 RETURN_STATUS_IF_ERROR(pushPort(dev));
5066 }
5067 }
5068 }
5069 return OK;
5070}
5071
jiabin19cdba52020-11-24 11:28:58 -08005072status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005073{
Eric Laurent99fcae42018-05-17 16:59:18 -07005074 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5075 return BAD_VALUE;
5076 }
5077 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5078 if (dev != 0) {
5079 dev->toAudioPort(port);
5080 return NO_ERROR;
5081 }
5082 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5083 if (dev != 0) {
5084 dev->toAudioPort(port);
5085 return NO_ERROR;
5086 }
5087 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5088 if (out != 0) {
5089 out->toAudioPort(port);
5090 return NO_ERROR;
5091 }
5092 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5093 if (in != 0) {
5094 in->toAudioPort(port);
5095 return NO_ERROR;
5096 }
5097 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005098}
5099
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005100status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5101 audio_patch_handle_t *handle,
5102 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005103{
François Gaffieafd4cea2019-11-18 15:50:22 +01005104 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005105 if (handle == NULL || patch == NULL) {
5106 return BAD_VALUE;
5107 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005108 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005109 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005110 return BAD_VALUE;
5111 }
5112 // only one source per audio patch supported for now
5113 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 return INVALID_OPERATION;
5115 }
Eric Laurent874c42872014-08-08 15:13:39 -07005116 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005117 return INVALID_OPERATION;
5118 }
Eric Laurent874c42872014-08-08 15:13:39 -07005119 for (size_t i = 0; i < patch->num_sinks; i++) {
5120 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5121 return INVALID_OPERATION;
5122 }
5123 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005124
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5126 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5127 if (srcDevice == nullptr || sinkDevice == nullptr) {
5128 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5129 return BAD_VALUE;
5130 }
5131 ALOGV("%s between source %s and sink %s", __func__,
5132 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5133 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5134 // Default attributes, default volume priority, not to infer with non raw audio patches.
5135 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5136 const struct audio_port_config *source = &patch->sources[0];
5137 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005138 new SourceClientDescriptor(
5139 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5140 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005141 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005142 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005143
5144 status_t status =
5145 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5146
5147 if (status != NO_ERROR) {
5148 return INVALID_OPERATION;
5149 }
5150 mAudioSources.add(portId, sourceDesc);
5151 return NO_ERROR;
5152}
5153
5154status_t AudioPolicyManager::connectAudioSourceToSink(
5155 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5156 const struct audio_patch *patch,
5157 audio_patch_handle_t &handle,
5158 uid_t uid, uint32_t delayMs)
5159{
5160 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5161 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5162 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5163 return INVALID_OPERATION;
5164 }
5165 sourceDesc->connect(handle, sinkDevice);
5166 if (isMsdPatch(handle)) {
5167 return NO_ERROR;
5168 }
5169 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5170 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5171 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5172 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5173 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5174 goto FailurePatchAdded;
5175 }
5176 status = swOutput->start();
5177 if (status != NO_ERROR) {
5178 goto FailureSourceAdded;
5179 }
5180 swOutput->addClient(sourceDesc);
5181 status = startSource(swOutput, sourceDesc, &delayMs);
5182 if (status != NO_ERROR) {
5183 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5184 goto FailureSourceActive;
5185 }
5186 if (delayMs != 0) {
5187 usleep(delayMs * 1000);
5188 }
5189 return NO_ERROR;
5190
5191FailureSourceActive:
5192 swOutput->stop();
5193 releaseOutput(sourceDesc->portId());
5194FailureSourceAdded:
5195 sourceDesc->setSwOutput(nullptr);
5196FailurePatchAdded:
5197 releaseAudioPatchInternal(handle);
5198 return INVALID_OPERATION;
5199}
5200
5201status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5202 audio_patch_handle_t *handle,
5203 uid_t uid, uint32_t delayMs,
5204 const sp<SourceClientDescriptor>& sourceDesc)
5205{
5206 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 sp<AudioPatch> patchDesc;
5208 ssize_t index = mAudioPatches.indexOfKey(*handle);
5209
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5211 patch->sources[0].role,
5212 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005213#if LOG_NDEBUG == 0
5214 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5216 patch->sinks[i].role,
5217 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005218 }
5219#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005220
5221 if (index >= 0) {
5222 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005223 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5224 __func__, mUidCached, patchDesc->getUid(), uid);
5225 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 return INVALID_OPERATION;
5227 }
5228 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005229 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 }
5231
5232 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005233 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005235 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 return BAD_VALUE;
5237 }
Eric Laurent84c70242014-06-23 08:46:27 -07005238 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5239 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 if (patchDesc != 0) {
5241 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005242 ALOGV("%s source id differs for patch current id %d new id %d",
5243 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 return BAD_VALUE;
5245 }
5246 }
Eric Laurent874c42872014-08-08 15:13:39 -07005247 DeviceVector devices;
5248 for (size_t i = 0; i < patch->num_sinks; i++) {
5249 // Only support mix to devices connection
5250 // TODO add support for mix to mix connection
5251 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005252 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005253 return INVALID_OPERATION;
5254 }
5255 sp<DeviceDescriptor> devDesc =
5256 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5257 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005259 return BAD_VALUE;
5260 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005261
jiabin66acc432024-02-06 00:57:36 +00005262 if (outputDesc->mProfile->getCompatibilityScore(
5263 DeviceVector(devDesc),
5264 patch->sources[0].sample_rate,
5265 nullptr, // updatedSamplingRate
5266 patch->sources[0].format,
5267 nullptr, // updatedFormat
5268 patch->sources[0].channel_mask,
5269 nullptr, // updatedChannelMask
5270 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005271 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005272 return INVALID_OPERATION;
5273 }
5274 devices.add(devDesc);
5275 }
5276 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 return INVALID_OPERATION;
5278 }
Eric Laurent874c42872014-08-08 15:13:39 -07005279
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005281 ALOGV("%s setting device %s on output %d",
5282 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305283 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 index = mAudioPatches.indexOfKey(*handle);
5285 if (index >= 0) {
5286 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 }
5289 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 patchDesc->setUid(uid);
5291 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005293 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 return INVALID_OPERATION;
5295 }
5296 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5297 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5298 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005299 // only one sink supported when connecting an input device to a mix
5300 if (patch->num_sinks > 1) {
5301 return INVALID_OPERATION;
5302 }
François Gaffie53615e22015-03-19 09:24:12 +01005303 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 if (inputDesc == NULL) {
5305 return BAD_VALUE;
5306 }
5307 if (patchDesc != 0) {
5308 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5309 return BAD_VALUE;
5310 }
5311 }
François Gaffie11d30102018-11-02 16:09:09 +01005312 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005314 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 return BAD_VALUE;
5316 }
5317
jiabin66acc432024-02-06 00:57:36 +00005318 if (inputDesc->mProfile->getCompatibilityScore(
5319 DeviceVector(device),
5320 patch->sinks[0].sample_rate,
5321 nullptr, /*updatedSampleRate*/
5322 patch->sinks[0].format,
5323 nullptr, /*updatedFormat*/
5324 patch->sinks[0].channel_mask,
5325 nullptr, /*updatedChannelMask*/
5326 // FIXME for the parameter type,
5327 // and the NONE
5328 (audio_output_flags_t)
5329 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 return INVALID_OPERATION;
5331 }
5332 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005333 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005334 device->toString().c_str(), inputDesc->mIoHandle);
5335 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005336 index = mAudioPatches.indexOfKey(*handle);
5337 if (index >= 0) {
5338 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005339 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 }
5341 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005342 patchDesc->setUid(uid);
5343 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005345 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 return INVALID_OPERATION;
5347 }
5348 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5349 // device to device connection
5350 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005351 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 return BAD_VALUE;
5353 }
5354 }
François Gaffie11d30102018-11-02 16:09:09 +01005355 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005356 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005357 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005358 return BAD_VALUE;
5359 }
Eric Laurent874c42872014-08-08 15:13:39 -07005360
Eric Laurent6a94d692014-05-20 11:18:06 -07005361 //update source and sink with our own data as the data passed in the patch may
5362 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005363 PatchBuilder patchBuilder;
5364 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005365
5366 // if first sink is to MSD, establish single MSD patch
5367 if (getMsdAudioOutDevices().contains(
5368 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5369 ALOGV("%s patching to MSD", __FUNCTION__);
5370 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5371 goto installPatch;
5372 }
5373
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5375 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005376
Eric Laurent874c42872014-08-08 15:13:39 -07005377 for (size_t i = 0; i < patch->num_sinks; i++) {
5378 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005380 return INVALID_OPERATION;
5381 }
François Gaffie11d30102018-11-02 16:09:09 +01005382 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005383 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005384 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005385 return BAD_VALUE;
5386 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005387 audio_port_config sinkPortConfig = {};
5388 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5389 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005390
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005391 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5392 // volume management purpose (tracking activity)
5393 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5394 // in config XML to reach the sink so that is can be declared as available.
5395 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005396 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005397 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005398 // take care of dynamic routing for SwOutput selection,
5399 audio_attributes_t attributes = sourceDesc->attributes();
5400 audio_stream_type_t stream = sourceDesc->stream();
5401 audio_attributes_t resultAttr;
5402 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5403 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005404 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5405 config.channel_mask =
5406 (audio_channel_mask_get_representation(sourceMask)
5407 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5408 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005409 config.format = sourceDesc->config().format;
5410 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5411 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5412 bool isRequestedDeviceForExclusiveUse = false;
5413 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005414 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005415 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005416 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5417 &stream, sourceDesc->uid(), &config, &flags,
5418 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005419 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005420 if (output == AUDIO_IO_HANDLE_NONE) {
5421 ALOGV("%s no output for device %s",
5422 __FUNCTION__, sinkDevice->toString().c_str());
5423 return INVALID_OPERATION;
5424 }
5425 outputDesc = mOutputs.valueFor(output);
5426 if (outputDesc->isDuplicated()) {
5427 ALOGE("%s output is duplicated", __func__);
5428 return INVALID_OPERATION;
5429 }
François Gaffie7e39df22022-04-26 12:48:49 +02005430 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5431 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005432 } else {
5433 // Same for "raw patches" aka created from createAudioPatch API
5434 SortedVector<audio_io_handle_t> outputs =
5435 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5436 // if the sink device is reachable via an opened output stream, request to
5437 // go via this output stream by adding a second source to the patch
5438 // description
5439 output = selectOutput(outputs);
5440 if (output == AUDIO_IO_HANDLE_NONE) {
5441 ALOGE("%s no output available for internal patch sink", __func__);
5442 return INVALID_OPERATION;
5443 }
5444 outputDesc = mOutputs.valueFor(output);
5445 if (outputDesc->isDuplicated()) {
5446 ALOGV("%s output for device %s is duplicated",
5447 __func__, sinkDevice->toString().c_str());
5448 return INVALID_OPERATION;
5449 }
François Gaffie7e39df22022-04-26 12:48:49 +02005450 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005451 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005452 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005453 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005454 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005455 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005456 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5457 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005458 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5459 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005460 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005461 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005463 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005464 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005465 return INVALID_OPERATION;
5466 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005467 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005468 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005469 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005470 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005471 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005472 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005473 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005474 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5475 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005476 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005477 }
Eric Laurent83b88082014-06-20 18:31:16 -07005478 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005479 }
5480 // TODO: check from routing capabilities in config file and other conflicting patches
5481
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005482installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005483 status_t status = installPatch(
5484 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005485 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005486 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005487 return INVALID_OPERATION;
5488 }
5489 } else {
5490 return BAD_VALUE;
5491 }
5492 } else {
5493 return BAD_VALUE;
5494 }
5495 return NO_ERROR;
5496}
5497
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005498status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005499{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005500 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 ssize_t index = mAudioPatches.indexOfKey(handle);
5502
5503 if (index < 0) {
5504 return BAD_VALUE;
5505 }
5506 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005507 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5508 __func__, mUidCached, patchDesc->getUid(), uid);
5509 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 return INVALID_OPERATION;
5511 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005512 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5513 for (size_t i = 0; i < mAudioSources.size(); i++) {
5514 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5515 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5516 portId = sourceDesc->portId();
5517 break;
5518 }
5519 }
5520 return portId != AUDIO_PORT_HANDLE_NONE ?
5521 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005522}
Eric Laurent6a94d692014-05-20 11:18:06 -07005523
François Gaffieafd4cea2019-11-18 15:50:22 +01005524status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005525 uint32_t delayMs,
5526 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005527{
5528 ALOGV("%s patch %d", __func__, handle);
5529 if (mAudioPatches.indexOfKey(handle) < 0) {
5530 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5531 return BAD_VALUE;
5532 }
5533 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005535 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005536 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005537 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005538 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005539 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 return BAD_VALUE;
5541 }
5542
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305543 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005544 getNewOutputDevices(outputDesc, true /*fromCache*/),
5545 true,
5546 0,
5547 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005548 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5549 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005550 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005551 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005552 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005553 return BAD_VALUE;
5554 }
5555 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005556 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 true,
5558 NULL);
5559 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 status_t status =
5561 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5562 ALOGV("%s patch panel returned %d patchHandle %d",
5563 __func__, status, patchDesc->getAfHandle());
5564 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005566 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005567 // SW or HW Bridge
5568 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5569 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005570 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005571 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5572 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5573 outputDesc = sourceDesc->swOutput().promote();
5574 }
5575 if (outputDesc == nullptr) {
5576 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5577 // releaseOutput has already called closeOutput in case of direct output
5578 return NO_ERROR;
5579 }
François Gaffie7e39df22022-04-26 12:48:49 +02005580 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005581 // While using a HwBridge, force reconsidering device only if not reusing an existing
5582 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005583 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005584 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5585 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5586 // Reconsider device only for cases:
5587 // 1 / Active Output
5588 // 2 / Inactive Output previously hosting HwBridge
5589 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5590 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5591 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305592 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005593 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5594 outputDesc->devices(),
5595 force,
5596 0,
5597 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005598 } else {
5599 return BAD_VALUE;
5600 }
5601 } else {
5602 return BAD_VALUE;
5603 }
5604 return NO_ERROR;
5605}
5606
5607status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5608 struct audio_patch *patches,
5609 unsigned int *generation)
5610{
François Gaffie53615e22015-03-19 09:24:12 +01005611 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005612 return BAD_VALUE;
5613 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005614 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005615 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005616}
5617
Eric Laurente1715a42014-05-20 11:30:42 -07005618status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005619{
Eric Laurente1715a42014-05-20 11:30:42 -07005620 ALOGV("setAudioPortConfig()");
5621
5622 if (config == NULL) {
5623 return BAD_VALUE;
5624 }
5625 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5626 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005627 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5628 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005629 }
5630
Eric Laurenta121f902014-06-03 13:32:54 -07005631 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005632 if (config->type == AUDIO_PORT_TYPE_MIX) {
5633 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005634 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005635 if (outputDesc == NULL) {
5636 return BAD_VALUE;
5637 }
Eric Laurent84c70242014-06-23 08:46:27 -07005638 ALOG_ASSERT(!outputDesc->isDuplicated(),
5639 "setAudioPortConfig() called on duplicated output %d",
5640 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005641 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005642 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005643 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005644 if (inputDesc == NULL) {
5645 return BAD_VALUE;
5646 }
Eric Laurenta121f902014-06-03 13:32:54 -07005647 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005648 } else {
5649 return BAD_VALUE;
5650 }
5651 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5652 sp<DeviceDescriptor> deviceDesc;
5653 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5654 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5655 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5656 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5657 } else {
5658 return BAD_VALUE;
5659 }
5660 if (deviceDesc == NULL) {
5661 return BAD_VALUE;
5662 }
Eric Laurenta121f902014-06-03 13:32:54 -07005663 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005664 } else {
5665 return BAD_VALUE;
5666 }
5667
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005668 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005669 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5670 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005671 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005672 audioPortConfig->toAudioPortConfig(&newConfig, config);
5673 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005674 }
Eric Laurenta121f902014-06-03 13:32:54 -07005675 if (status != NO_ERROR) {
5676 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005677 }
Eric Laurente1715a42014-05-20 11:30:42 -07005678
5679 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005680}
5681
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005682void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5683{
Eric Laurentd60560a2015-04-10 11:31:20 -07005684 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005685 clearAudioPatches(uid);
5686 clearSessionRoutes(uid);
5687}
5688
Eric Laurent6a94d692014-05-20 11:18:06 -07005689void AudioPolicyManager::clearAudioPatches(uid_t uid)
5690{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005691 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005692 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005693 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005694 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005695 }
5696 }
5697}
5698
François Gaffiec005e562018-11-06 15:04:49 +01005699void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005700{
François Gaffiec005e562018-11-06 15:04:49 +01005701 // Take the first attributes following the product strategy as it is used to retrieve the routed
5702 // device. All attributes wihin a strategy follows the same "routing strategy"
5703 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5704 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005705 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005706 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005707 for (size_t j = 0; j < mOutputs.size(); j++) {
5708 if (mOutputs.keyAt(j) == ouptutToSkip) {
5709 continue;
5710 }
5711 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005712 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005713 continue;
5714 }
5715 // If the default device for this strategy is on another output mix,
5716 // invalidate all tracks in this strategy to force re connection.
5717 // Otherwise select new device on the output mix.
5718 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005719 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005720 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005721 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005722 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005723 // If the device is using preferred mixer attributes, the output need to reopen
5724 // with default configuration when the new selected devices are different from
5725 // current routing devices.
5726 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5727 continue;
5728 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305729 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005730 }
5731 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005732 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005733}
5734
5735void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5736{
5737 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005738 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005739 for (size_t i = 0; i < mOutputs.size(); i++) {
5740 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005741 for (const auto& client : outputDesc->getClientIterable()) {
5742 if (client->hasPreferredDevice() && client->uid() == uid) {
5743 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005744 auto clientStrategy = client->strategy();
5745 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5746 end(affectedStrategies)) {
5747 continue;
5748 }
5749 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005750 }
5751 }
5752 }
5753 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005754 for (const auto& strategy : affectedStrategies) {
5755 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005756 }
5757
5758 // remove input routes associated with this uid
5759 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005760 for (size_t i = 0; i < mInputs.size(); i++) {
5761 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005762 for (const auto& client : inputDesc->getClientIterable()) {
5763 if (client->hasPreferredDevice() && client->uid() == uid) {
5764 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5765 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005766 }
5767 }
5768 }
5769 // reroute inputs if necessary
5770 SortedVector<audio_io_handle_t> inputsToClose;
5771 for (size_t i = 0; i < mInputs.size(); i++) {
5772 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005773 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005774 inputsToClose.add(inputDesc->mIoHandle);
5775 }
5776 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005777 for (const auto& input : inputsToClose) {
5778 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005779 }
5780}
5781
Eric Laurentd60560a2015-04-10 11:31:20 -07005782void AudioPolicyManager::clearAudioSources(uid_t uid)
5783{
5784 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005785 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5786 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005787 stopAudioSource(mAudioSources.keyAt(i));
5788 }
5789 }
5790}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005791
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005792status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5793 audio_io_handle_t *ioHandle,
5794 audio_devices_t *device)
5795{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005796 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5797 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005798 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005799 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5800 if (deviceDesc == nullptr) {
5801 return INVALID_OPERATION;
5802 }
5803 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005804
François Gaffiedf372692015-03-19 10:43:27 +01005805 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005806}
5807
Eric Laurentd60560a2015-04-10 11:31:20 -07005808status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005809 const audio_attributes_t *attributes,
5810 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005811 uid_t uid) {
5812 return startAudioSourceInternal(source, attributes, portId, uid,
5813 false /*internal*/, false /*isCallRx*/);
5814}
5815
5816status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5817 const audio_attributes_t *attributes,
5818 audio_port_handle_t *portId,
5819 uid_t uid, bool internal, bool isCallRx)
Eric Laurent554a2772015-04-10 11:29:24 -07005820{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005821 ALOGV("%s", __FUNCTION__);
5822 *portId = AUDIO_PORT_HANDLE_NONE;
5823
5824 if (source == NULL || attributes == NULL || portId == NULL) {
5825 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5826 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005827 return BAD_VALUE;
5828 }
5829
Eric Laurentd60560a2015-04-10 11:31:20 -07005830 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5831 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005832 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5833 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005834 return INVALID_OPERATION;
5835 }
5836
François Gaffie11d30102018-11-02 16:09:09 +01005837 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005838 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005839 String8(source->ext.device.address),
5840 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005841 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005842 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005843 return BAD_VALUE;
5844 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005845
jiabin4ef93452019-09-10 14:29:54 -07005846 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005847
François Gaffieaaac0fd2018-11-22 17:56:39 +01005848 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005849 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005850 mEngine->getStreamTypeForAttributes(*attributes),
5851 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005852 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005853
5854 status_t status = connectAudioSource(sourceDesc);
5855 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005856 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005857 }
5858 return status;
5859}
5860
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005861status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005862{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005863 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005864
5865 // make sure we only have one patch per source.
5866 disconnectAudioSource(sourceDesc);
5867
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005868 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005869 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5870 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5871 sourceDesc->srcDevice()->type(),
5872 String8(sourceDesc->srcDevice()->address().c_str()),
5873 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005874 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005875 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005876 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005877 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005878 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5879 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5880 return INVALID_OPERATION;
5881 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005882 PatchBuilder patchBuilder;
5883 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5884 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005885
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005886 return connectAudioSourceToSink(
5887 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005888}
5889
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005890status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005891{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005892 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5893 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005894 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005895 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005896 return BAD_VALUE;
5897 }
5898 status_t status = disconnectAudioSource(sourceDesc);
5899
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005900 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005901 return status;
5902}
5903
Andy Hung2ddee192015-12-18 17:34:44 -08005904status_t AudioPolicyManager::setMasterMono(bool mono)
5905{
5906 if (mMasterMono == mono) {
5907 return NO_ERROR;
5908 }
5909 mMasterMono = mono;
5910 // if enabling mono we close all offloaded devices, which will invalidate the
5911 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5912 // for recreating the new AudioTrack as non-offloaded PCM.
5913 //
5914 // If disabling mono, we leave all tracks as is: we don't know which clients
5915 // and tracks are able to be recreated as offloaded. The next "song" should
5916 // play back offloaded.
5917 if (mMasterMono) {
5918 Vector<audio_io_handle_t> offloaded;
5919 for (size_t i = 0; i < mOutputs.size(); ++i) {
5920 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5921 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5922 offloaded.push(desc->mIoHandle);
5923 }
5924 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005925 for (const auto& handle : offloaded) {
5926 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005927 }
5928 }
5929 // update master mono for all remaining outputs
5930 for (size_t i = 0; i < mOutputs.size(); ++i) {
5931 updateMono(mOutputs.keyAt(i));
5932 }
5933 return NO_ERROR;
5934}
5935
5936status_t AudioPolicyManager::getMasterMono(bool *mono)
5937{
5938 *mono = mMasterMono;
5939 return NO_ERROR;
5940}
5941
Eric Laurentac9cef52017-06-09 15:46:26 -07005942float AudioPolicyManager::getStreamVolumeDB(
5943 audio_stream_type_t stream, int index, audio_devices_t device)
5944{
jiabin9a3361e2019-10-01 09:38:30 -07005945 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005946}
5947
jiabin81772902018-04-02 17:52:27 -07005948status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5949 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005950 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005951{
Kriti Dang6537def2021-03-02 13:46:59 +01005952 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5953 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005954 return BAD_VALUE;
5955 }
Kriti Dang6537def2021-03-02 13:46:59 +01005956 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5957 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005958
5959 size_t formatsWritten = 0;
5960 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005961
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005962 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005963 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5964 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005965 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005966 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005967 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005968 bool formatEnabled = true;
5969 switch (forceUse) {
5970 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005971 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005972 break;
5973 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5974 formatEnabled = false;
5975 break;
5976 default: // AUTO or ALWAYS => true
5977 break;
jiabin81772902018-04-02 17:52:27 -07005978 }
5979 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5980 }
jiabin81772902018-04-02 17:52:27 -07005981 }
5982 return NO_ERROR;
5983}
5984
Kriti Dang6537def2021-03-02 13:46:59 +01005985status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5986 audio_format_t *surroundFormats) {
5987 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5988 return BAD_VALUE;
5989 }
5990 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5991 __func__, *numSurroundFormats, surroundFormats);
5992
5993 size_t formatsWritten = 0;
5994 size_t formatsMax = *numSurroundFormats;
5995 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5996
5997 // Return formats from all device profiles that have already been resolved by
5998 // checkOutputsForDevice().
5999 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6000 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6001 audio_devices_t deviceType = device->type();
6002 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6003 // returns formats reported by HDMI devices.
6004 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6005 continue;
6006 }
6007 // Formats reported by sink devices
6008 std::unordered_set<audio_format_t> formatset;
6009 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6010 formatset.insert(it->second.begin(), it->second.end());
6011 }
6012
6013 // Formats hard-coded in the in policy configuration file (if any).
6014 FormatVector encodedFormats = device->encodedFormats();
6015 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6016 // Filter the formats which are supported by the vendor hardware.
6017 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006018 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006019 formats.insert(*it);
6020 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006021 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006022 if (pair.second.count(*it) != 0) {
6023 formats.insert(pair.first);
6024 break;
6025 }
6026 }
6027 }
6028 }
6029 }
6030 *numSurroundFormats = formats.size();
6031 for (const auto& format: formats) {
6032 if (formatsWritten < formatsMax) {
6033 surroundFormats[formatsWritten++] = format;
6034 }
6035 }
6036 return NO_ERROR;
6037}
6038
jiabin81772902018-04-02 17:52:27 -07006039status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6040{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006041 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006042 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6043 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006044 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006045 return BAD_VALUE;
6046 }
6047
Mikhail Naganov100f0122018-11-29 11:22:16 -08006048 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6049 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006050 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006051 return INVALID_OPERATION;
6052 }
6053
Mikhail Naganov100f0122018-11-29 11:22:16 -08006054 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006055 return NO_ERROR;
6056 }
6057
Mikhail Naganov100f0122018-11-29 11:22:16 -08006058 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006059 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006060 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006061 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006062 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006063 }
6064 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006065 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006066 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006067 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006068 }
6069 }
6070
6071 sp<SwAudioOutputDescriptor> outputDesc;
6072 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006073 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6074 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006075 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6076 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006077 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006078 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006079 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6080 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6081 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006082 name.c_str(),
6083 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006084 if (status != NO_ERROR) {
6085 continue;
6086 }
6087 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6088 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6089 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006090 name.c_str(),
6091 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006092 profileUpdated |= (status == NO_ERROR);
6093 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006094 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006095 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006096 AUDIO_DEVICE_IN_HDMI);
6097 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6098 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006099 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006100 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006101 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6102 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6103 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006104 name.c_str(),
6105 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006106 if (status != NO_ERROR) {
6107 continue;
6108 }
6109 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6110 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6111 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006112 name.c_str(),
6113 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006114 profileUpdated |= (status == NO_ERROR);
6115 }
6116
jiabin81772902018-04-02 17:52:27 -07006117 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006118 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006119 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006120 }
6121
6122 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6123}
6124
Eric Laurent5ada82e2019-08-29 17:53:54 -07006125void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006126{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006127 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006128 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006129 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006130 }
6131}
6132
jiabin6012f912018-11-02 17:06:30 -07006133bool AudioPolicyManager::isHapticPlaybackSupported()
6134{
6135 for (const auto& hwModule : mHwModules) {
6136 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6137 for (const auto &outProfile : outputProfiles) {
6138 struct audio_port audioPort;
6139 outProfile->toAudioPort(&audioPort);
6140 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6141 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6142 return true;
6143 }
6144 }
6145 }
6146 }
6147 return false;
6148}
6149
Carter Hsu325a8eb2022-01-19 19:56:51 +08006150bool AudioPolicyManager::isUltrasoundSupported()
6151{
6152 bool hasUltrasoundOutput = false;
6153 bool hasUltrasoundInput = false;
6154 for (const auto& hwModule : mHwModules) {
6155 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6156 if (!hasUltrasoundOutput) {
6157 for (const auto &outProfile : outputProfiles) {
6158 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6159 hasUltrasoundOutput = true;
6160 break;
6161 }
6162 }
6163 }
6164
6165 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6166 if (!hasUltrasoundInput) {
6167 for (const auto &inputProfile : inputProfiles) {
6168 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6169 hasUltrasoundInput = true;
6170 break;
6171 }
6172 }
6173 }
6174
6175 if (hasUltrasoundOutput && hasUltrasoundInput)
6176 return true;
6177 }
6178 return false;
6179}
6180
Atneya Nair698f5ef2022-12-15 16:15:09 -08006181bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6182{
6183 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6184 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6185 for (const auto& hwModule : mHwModules) {
6186 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6187 for (const auto &inputProfile : inputProfiles) {
6188 if ((inputProfile->getFlags() & mask) == mask) {
6189 return true;
6190 }
6191 }
6192 }
6193 return false;
6194}
6195
Eric Laurent8340e672019-11-06 11:01:08 -08006196bool AudioPolicyManager::isCallScreenModeSupported()
6197{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006198 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006199}
6200
6201
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006202status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006203{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006204 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006205 if (!sourceDesc->isConnected()) {
6206 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6207 return NO_ERROR;
6208 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006209 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6210 if (swOutput != 0) {
6211 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006212 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006213 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006214 }
jiabinbce0c1d2020-10-05 11:20:18 -07006215 if (releaseOutput(sourceDesc->portId())) {
6216 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6217 // no need to release audio patch here but just return NO_ERROR.
6218 return NO_ERROR;
6219 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006220 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006221 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006222 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006223 // close Hwoutput and remove from mHwOutputs
6224 } else {
6225 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6226 }
6227 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006228 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006229 sourceDesc->disconnect();
6230 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006231}
6232
François Gaffiec005e562018-11-06 15:04:49 +01006233sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6234 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006235{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006236 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006237 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006238 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006239 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006240 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6241 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006242 source = sourceDesc;
6243 break;
6244 }
6245 }
6246 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006247}
6248
Eric Laurentb4f42a92022-01-17 17:37:31 +01006249bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006250 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006251 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006252{
6253 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6254 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006255 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006256 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006257 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6258 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6259 return false;
6260 }
6261 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6262 return false;
6263 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006264 }
6265
Eric Laurentd332bc82023-08-04 11:45:23 +02006266 // The caller can have the audio config criteria ignored by either passing a null ptr or
6267 // the AUDIO_CONFIG_INITIALIZER value.
6268 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006269 // some positional channel masks and PCM format and for stereo if low latency performance
6270 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006271
6272 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006273 static const bool stereo_spatialization_enabled =
6274 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006275 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006276 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006277 ? audio_channel_mask_contains_stereo(config->channel_mask)
6278 : audio_is_channel_mask_spatialized(config->channel_mask);
6279 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006280 return false;
6281 }
6282 if (!audio_is_linear_pcm(config->format)) {
6283 return false;
6284 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006285 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6286 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6287 return false;
6288 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006289 }
6290
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006291 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006292 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006293 if (profile == nullptr) {
6294 return false;
6295 }
6296
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006297 return true;
6298}
6299
Shunkai Yao4c3af932024-04-26 04:12:21 +00006300// The Spatializer output is compatible with Haptic use cases if:
6301// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6302// with client if client haptic channel bits were set, or
6303// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6304// including the haptic bits or creating the HapticGenerator effect for same session.
6305bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6306 const audio_config_t* config, audio_session_t sessionId) const {
6307 const auto clientHapticChannel =
6308 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6309 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6310 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6311
6312 if (threadOutputHapticChannel) {
6313 // check format and sampleRate match if client haptic channel mask exist
6314 if (clientHapticChannel) {
6315 return mSpatializerOutput->getFormat() == config->format &&
6316 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6317 }
6318 return true;
6319 } else {
6320 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6321 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6322 // HapticGenerator effect for this session) are not supported.
6323 return clientHapticChannel == 0 &&
6324 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6325 }
6326}
6327
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006328void AudioPolicyManager::checkVirtualizerClientRoutes() {
6329 std::set<audio_stream_type_t> streamsToInvalidate;
6330 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006331 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6332 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006333 audio_attributes_t attr = client->attributes();
6334 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6335 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6336 audio_config_base_t clientConfig = client->config();
6337 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006338 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006339 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006340 streamsToInvalidate.insert(client->stream());
6341 }
6342 }
6343 }
6344
jiabinc44b3462022-12-08 12:52:31 -08006345 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006346}
6347
Eric Laurente191d1b2022-04-15 11:59:25 +02006348
6349bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6350 const sp<SwAudioOutputDescriptor>& outputDesc) {
6351 if (outputDesc->isDuplicated()) {
6352 return false;
6353 }
6354 DeviceVector devices = outputDesc->supportedDevices();
6355 for (size_t i = 0; i < mOutputs.size(); i++) {
6356 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6357 if (desc == outputDesc || desc->isDuplicated()) {
6358 continue;
6359 }
6360 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6361 if (!sharedDevices.isEmpty()
6362 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6363 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6364 return false;
6365 }
6366 }
6367 return true;
6368}
6369
6370
Eric Laurentfa0f6742021-08-17 18:39:44 +02006371status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006372 const audio_attributes_t *attr,
6373 audio_io_handle_t *output) {
6374 *output = AUDIO_IO_HANDLE_NONE;
6375
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006376 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6377 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6378 audio_config_t *configPtr = nullptr;
6379 audio_config_t config;
6380 if (mixerConfig != nullptr) {
6381 config = audio_config_initializer(mixerConfig);
6382 configPtr = &config;
6383 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006384 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006385 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006386 return BAD_VALUE;
6387 }
6388
6389 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006390 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006391 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006392 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006393 return BAD_VALUE;
6394 }
6395
Eric Laurente191d1b2022-04-15 11:59:25 +02006396 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006397 for (size_t i = 0; i < mOutputs.size(); i++) {
6398 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006399 if (!desc->isDuplicated()
6400 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6401 spatializerOutputs.push_back(desc);
6402 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006403 }
6404 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006405 mSpatializerOutput.clear();
6406 bool outputsChanged = false;
6407 for (const auto& desc : spatializerOutputs) {
6408 if (desc->mProfile == profile
6409 && (configPtr == nullptr
6410 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6411 mSpatializerOutput = desc;
6412 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6413 } else {
6414 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6415 " and devices %s", __func__, desc->mIoHandle,
6416 configPtr != nullptr ? configPtr->channel_mask : 0,
6417 devices.toString().c_str());
6418 closeOutput(desc->mIoHandle);
6419 outputsChanged = true;
6420 }
Eric Laurent39095982021-08-24 18:29:27 +02006421 }
6422
Eric Laurente191d1b2022-04-15 11:59:25 +02006423 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006424 sp<SwAudioOutputDescriptor> desc =
6425 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006426 if (desc != nullptr) {
6427 mSpatializerOutput = desc;
6428 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006429 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006430 }
6431
6432 checkVirtualizerClientRoutes();
6433
Eric Laurente191d1b2022-04-15 11:59:25 +02006434 if (outputsChanged) {
6435 mPreviousOutputs = mOutputs;
6436 mpClientInterface->onAudioPortListUpdate();
6437 }
6438
6439 if (mSpatializerOutput == nullptr) {
6440 ALOGV("%s could not open spatializer output with requested config", __func__);
6441 return BAD_VALUE;
6442 }
Eric Laurent39095982021-08-24 18:29:27 +02006443 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006444 ALOGV("%s returning new spatializer output %d", __func__, *output);
6445 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006446}
6447
Eric Laurentfa0f6742021-08-17 18:39:44 +02006448status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6449 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006450 return INVALID_OPERATION;
6451 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006452 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006453 return BAD_VALUE;
6454 }
Eric Laurent39095982021-08-24 18:29:27 +02006455
Eric Laurente191d1b2022-04-15 11:59:25 +02006456 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6457 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6458 closeOutput(mSpatializerOutput->mIoHandle);
6459 //from now on mSpatializerOutput is null
6460 checkVirtualizerClientRoutes();
6461 }
Eric Laurent39095982021-08-24 18:29:27 +02006462
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006463 return NO_ERROR;
6464}
6465
Eric Laurente552edb2014-03-10 17:42:56 -07006466// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006467// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006468// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006469uint32_t AudioPolicyManager::nextAudioPortGeneration()
6470{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006471 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006472}
6473
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006474AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006475 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006476 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006477 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006478 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006479 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006480 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006481 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006482 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006483 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006484 mAudioPortGeneration(1),
6485 mBeaconMuteRefCount(0),
6486 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006487 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006488 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006489 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006490 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006491{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006492}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006493
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006494status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006495 if (mEngine == nullptr) {
6496 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006497 }
6498 mEngine->setObserver(this);
6499 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006500 if (status != NO_ERROR) {
6501 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6502 return status;
6503 }
François Gaffie2110e042015-03-24 08:41:51 +01006504
jiabin29230182023-04-04 21:02:36 +00006505 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6506 // at the end of this function.
6507 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006508 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6509 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6510
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006511 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006512 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006513 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006514
Eric Laurent3a4311c2014-03-17 12:00:47 -07006515 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006516 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6517 defaultOutputDevice == nullptr ||
6518 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6519 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6520 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006521 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006522 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006523 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006524
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006525 // Silence ALOGV statements
6526 property_set("log.tag." LOG_TAG, "D");
6527
Eric Laurente552edb2014-03-10 17:42:56 -07006528 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006529 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006530}
6531
Eric Laurente0720872014-03-11 09:30:41 -07006532AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006533{
Eric Laurente552edb2014-03-10 17:42:56 -07006534 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006535 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006536 }
6537 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006538 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006539 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006540 mAvailableOutputDevices.clear();
6541 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006542 mOutputs.clear();
6543 mInputs.clear();
6544 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006545 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006546 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006547}
6548
Eric Laurente0720872014-03-11 09:30:41 -07006549status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006550{
Eric Laurent87ffa392015-05-22 10:32:38 -07006551 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006552}
6553
Eric Laurente552edb2014-03-10 17:42:56 -07006554// ---
6555
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006556void AudioPolicyManager::onNewAudioModulesAvailable()
6557{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006558 DeviceVector newDevices;
6559 onNewAudioModulesAvailableInt(&newDevices);
6560 if (!newDevices.empty()) {
6561 nextAudioPortGeneration();
6562 mpClientInterface->onAudioPortListUpdate();
6563 }
6564}
6565
6566void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6567{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006568 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006569 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6570 continue;
6571 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006572 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006573 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6574 handle != AUDIO_MODULE_HANDLE_NONE) {
6575 hwModule->setHandle(handle);
6576 } else {
6577 ALOGW("could not load HW module %s", hwModule->getName());
6578 continue;
6579 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006580 }
6581 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006582 // open all output streams needed to access attached devices.
6583 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006584 // This also validates mAvailableOutputDevices list
6585 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6586 if (!outProfile->canOpenNewIo()) {
6587 ALOGE("Invalid Output profile max open count %u for profile %s",
6588 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6589 continue;
6590 }
6591 if (!outProfile->hasSupportedDevices()) {
6592 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6593 continue;
6594 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006595 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6596 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006597 mTtsOutputAvailable = true;
6598 }
6599
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006600 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006601 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006602 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006603 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6604 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006605 } else {
6606 // choose first device present in profile's SupportedDevices also part of
6607 // mAvailableOutputDevices.
6608 if (availProfileDevices.isEmpty()) {
6609 continue;
6610 }
6611 supportedDevice = availProfileDevices.itemAt(0);
6612 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006613 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006614 continue;
6615 }
6616 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6617 mpClientInterface);
6618 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006619 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6620 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006621 AUDIO_STREAM_DEFAULT,
6622 AUDIO_OUTPUT_FLAG_NONE, &output);
6623 if (status != NO_ERROR) {
6624 ALOGW("Cannot open output stream for devices %s on hw module %s",
6625 supportedDevice->toString().c_str(), hwModule->getName());
6626 continue;
6627 }
6628 for (const auto &device : availProfileDevices) {
6629 // give a valid ID to an attached device once confirmed it is reachable
6630 if (!device->isAttached()) {
6631 device->attach(hwModule);
6632 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006633 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006634 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006635 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6636 }
6637 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006638 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006639 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6640 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006641 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006642 }
Eric Laurent39095982021-08-24 18:29:27 +02006643 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006644 outputDesc->close();
6645 } else {
6646 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306647 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006648 DeviceVector(supportedDevice),
6649 true,
6650 0,
6651 NULL);
6652 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006653 }
6654 // open input streams needed to access attached devices to validate
6655 // mAvailableInputDevices list
6656 for (const auto& inProfile : hwModule->getInputProfiles()) {
6657 if (!inProfile->canOpenNewIo()) {
6658 ALOGE("Invalid Input profile max open count %u for profile %s",
6659 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6660 continue;
6661 }
6662 if (!inProfile->hasSupportedDevices()) {
6663 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6664 continue;
6665 }
6666 // chose first device present in profile's SupportedDevices also part of
6667 // available input devices
6668 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006669 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006670 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006671 ALOGV("%s: Input device list is empty! for profile %s",
6672 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006673 continue;
6674 }
6675 sp<AudioInputDescriptor> inputDesc =
6676 new AudioInputDescriptor(inProfile, mpClientInterface);
6677
6678 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6679 status_t status = inputDesc->open(nullptr,
6680 availProfileDevices.itemAt(0),
6681 AUDIO_SOURCE_MIC,
6682 AUDIO_INPUT_FLAG_NONE,
6683 &input);
6684 if (status != NO_ERROR) {
6685 ALOGW("Cannot open input stream for device %s on hw module %s",
6686 availProfileDevices.toString().c_str(),
6687 hwModule->getName());
6688 continue;
6689 }
6690 for (const auto &device : availProfileDevices) {
6691 // give a valid ID to an attached device once confirmed it is reachable
6692 if (!device->isAttached()) {
6693 device->attach(hwModule);
6694 device->importAudioPortAndPickAudioProfile(inProfile, true);
6695 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006696 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006697 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6698 }
6699 }
6700 inputDesc->close();
6701 }
6702 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006703
6704 // Check if spatializer outputs can be closed until used.
6705 // mOutputs vector never contains duplicated outputs at this point.
6706 std::vector<audio_io_handle_t> outputsClosed;
6707 for (size_t i = 0; i < mOutputs.size(); i++) {
6708 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6709 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6710 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6711 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006712 nextAudioPortGeneration();
6713 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6714 if (index >= 0) {
6715 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6716 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6717 patchDesc->getAfHandle(), 0);
6718 mAudioPatches.removeItemsAt(index);
6719 mpClientInterface->onAudioPatchListUpdate();
6720 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006721 desc->close();
6722 }
6723 }
6724 for (auto output : outputsClosed) {
6725 removeOutput(output);
6726 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006727}
6728
Eric Laurent98e38192018-02-15 18:31:53 -08006729void AudioPolicyManager::addOutput(audio_io_handle_t output,
6730 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006731{
Eric Laurent1c333e22014-05-20 10:48:17 -07006732 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006733 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006734 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006735 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006736 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006737}
6738
François Gaffie53615e22015-03-19 09:24:12 +01006739void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6740{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006741 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6742 ALOGV("%s: removing primary output", __func__);
6743 mPrimaryOutput = nullptr;
6744 }
François Gaffie53615e22015-03-19 09:24:12 +01006745 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006746 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006747}
6748
Eric Laurent98e38192018-02-15 18:31:53 -08006749void AudioPolicyManager::addInput(audio_io_handle_t input,
6750 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006751{
Eric Laurent1c333e22014-05-20 10:48:17 -07006752 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006753 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006754}
Eric Laurente552edb2014-03-10 17:42:56 -07006755
François Gaffie11d30102018-11-02 16:09:09 +01006756status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006757 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006758 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006759{
François Gaffie11d30102018-11-02 16:09:09 +01006760 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006761 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006762 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006763
François Gaffie11d30102018-11-02 16:09:09 +01006764 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006765 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006766 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006767 }
Eric Laurente552edb2014-03-10 17:42:56 -07006768
Eric Laurent3b73df72014-03-11 09:06:29 -07006769 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006770 // first call getAudioPort to get the supported attributes from the HAL
6771 struct audio_port_v7 port = {};
6772 device->toAudioPort(&port);
6773 status_t status = mpClientInterface->getAudioPort(&port);
6774 if (status == NO_ERROR) {
6775 device->importAudioPort(port);
6776 }
6777
6778 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006779 for (size_t i = 0; i < mOutputs.size(); i++) {
6780 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006781 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006782 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006783 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6784 mOutputs.keyAt(i), device->toString().c_str());
6785 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006786 }
6787 }
6788 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006789 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006790 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006791 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6792 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006793 if (profile->supportsDevice(device)) {
6794 profiles.add(profile);
6795 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6796 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006797 }
6798 }
6799 }
6800
Eric Laurent7b279bb2015-12-14 10:18:23 -08006801 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006802
Eric Laurente552edb2014-03-10 17:42:56 -07006803 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006804 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006805 return BAD_VALUE;
6806 }
6807
6808 // open outputs for matching profiles if needed. Direct outputs are also opened to
6809 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6810 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006811 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006812
6813 // nothing to do if one output is already opened for this profile
6814 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006815 for (j = 0; j < outputs.size(); j++) {
6816 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006817 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006818 // matching profile: save the sample rates, format and channel masks supported
6819 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006820 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006821 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006822 }
Eric Laurente552edb2014-03-10 17:42:56 -07006823 break;
6824 }
6825 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006826 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006827 continue;
6828 }
6829
Eric Laurent3974e3b2017-12-07 17:58:43 -08006830 if (!profile->canOpenNewIo()) {
6831 ALOGW("Max Output number %u already opened for this profile %s",
6832 profile->maxOpenCount, profile->getTagName().c_str());
6833 continue;
6834 }
6835
Eric Laurent83efe1c2017-07-09 16:51:08 -07006836 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006837 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006838 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6839 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006840 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006841 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006842 profiles.removeAt(profile_index);
6843 profile_index--;
6844 } else {
6845 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006846 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006847 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006848 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6849 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006850 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006851 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006852
François Gaffie11d30102018-11-02 16:09:09 +01006853 if (device_distinguishes_on_address(deviceType)) {
6854 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6855 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306856 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6857 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006858 }
Eric Laurente552edb2014-03-10 17:42:56 -07006859 ALOGV("checkOutputsForDevice(): adding output %d", output);
6860 }
6861 }
6862
6863 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006864 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006865 return BAD_VALUE;
6866 }
Eric Laurentd4692962014-05-05 18:13:44 -07006867 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006868 // check if one opened output is not needed any more after disconnecting one device
6869 for (size_t i = 0; i < mOutputs.size(); i++) {
6870 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006871 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006872 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006873 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006874 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006875 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006876 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006877 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6878 mOutputs.keyAt(i));
6879 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006880 }
Eric Laurente552edb2014-03-10 17:42:56 -07006881 }
6882 }
Eric Laurentd4692962014-05-05 18:13:44 -07006883 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006884 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006885 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6886 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006887 if (!profile->supportsDevice(device)) {
6888 continue;
6889 }
6890 ALOGV("checkOutputsForDevice(): "
6891 "clearing direct output profile %zu on module %s",
6892 j, hwModule->getName());
6893 profile->clearAudioProfiles();
6894 if (!profile->hasDynamicAudioProfile()) {
6895 continue;
6896 }
6897 // When a device is disconnected, if there is an IOProfile that contains dynamic
6898 // profiles and supports the disconnected device, call getAudioPort to repopulate
6899 // the capabilities of the devices that is supported by the IOProfile.
6900 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6901 if (supportedDevice == device ||
6902 !mAvailableOutputDevices.contains(supportedDevice)) {
6903 continue;
6904 }
6905 struct audio_port_v7 port;
6906 supportedDevice->toAudioPort(&port);
6907 status_t status = mpClientInterface->getAudioPort(&port);
6908 if (status == NO_ERROR) {
6909 supportedDevice->importAudioPort(port);
6910 }
Eric Laurente552edb2014-03-10 17:42:56 -07006911 }
6912 }
6913 }
6914 }
6915 return NO_ERROR;
6916}
6917
François Gaffie11d30102018-11-02 16:09:09 +01006918status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006919 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006920{
François Gaffie11d30102018-11-02 16:09:09 +01006921 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006922 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006923 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006924 }
6925
Eric Laurentd4692962014-05-05 18:13:44 -07006926 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006927 sp<AudioInputDescriptor> desc;
6928
jiabinbf5f4262023-04-12 21:48:34 +00006929 // first call getAudioPort to get the supported attributes from the HAL
6930 struct audio_port_v7 port = {};
6931 device->toAudioPort(&port);
6932 status_t status = mpClientInterface->getAudioPort(&port);
6933 if (status == NO_ERROR) {
6934 device->importAudioPort(port);
6935 }
6936
Eric Laurent0dd51852019-04-19 18:18:58 -07006937 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006938 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006939 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006940 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006941 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006942 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006943 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006944
François Gaffie11d30102018-11-02 16:09:09 +01006945 if (profile->supportsDevice(device)) {
6946 profiles.add(profile);
6947 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6948 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006949 }
6950 }
6951 }
6952
Eric Laurent0dd51852019-04-19 18:18:58 -07006953 if (profiles.isEmpty()) {
6954 ALOGW("%s: No input profile available for device %s",
6955 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006956 return BAD_VALUE;
6957 }
6958
6959 // open inputs for matching profiles if needed. Direct inputs are also opened to
6960 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6961 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6962
Eric Laurent1c333e22014-05-20 10:48:17 -07006963 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006964
Eric Laurentd4692962014-05-05 18:13:44 -07006965 // nothing to do if one input is already opened for this profile
6966 size_t input_index;
6967 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6968 desc = mInputs.valueAt(input_index);
6969 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006970 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006971 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006972 }
Eric Laurentd4692962014-05-05 18:13:44 -07006973 break;
6974 }
6975 }
6976 if (input_index != mInputs.size()) {
6977 continue;
6978 }
6979
Eric Laurent3974e3b2017-12-07 17:58:43 -08006980 if (!profile->canOpenNewIo()) {
6981 ALOGW("Max Input number %u already opened for this profile %s",
6982 profile->maxOpenCount, profile->getTagName().c_str());
6983 continue;
6984 }
6985
Eric Laurentfe231122017-11-17 17:48:06 -08006986 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006987 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006988 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006989
Eric Laurentcf2c0212014-07-25 16:20:43 -07006990 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006991 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006992 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006993 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006994 mpClientInterface->setParameters(input, String8(param));
6995 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006996 }
jiabin12537fc2023-10-12 17:56:08 +00006997 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006998 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006999 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08007000 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007001 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007002 }
7003
Eric Laurent0dd51852019-04-19 18:18:58 -07007004 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007005 addInput(input, desc);
7006 }
7007 } // endif input != 0
7008
Eric Laurentcf2c0212014-07-25 16:20:43 -07007009 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08007010 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01007011 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007012 profiles.removeAt(profile_index);
7013 profile_index--;
7014 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007015 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007016 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007017 }
Eric Laurentd4692962014-05-05 18:13:44 -07007018 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007019
7020 if (checkCloseInput(desc)) {
7021 ALOGV("%s closing input %d", __func__, input);
7022 closeInput(input);
7023 }
Eric Laurentd4692962014-05-05 18:13:44 -07007024 }
7025 } // end scan profiles
7026
7027 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007028 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007029 return BAD_VALUE;
7030 }
7031 } else {
7032 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007033 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007034 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007035 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007036 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007037 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007038 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007039 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08007040 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
7041 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007042 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007043 }
7044 }
7045 }
7046 } // end disconnect
7047
7048 return NO_ERROR;
7049}
7050
7051
Eric Laurente0720872014-03-11 09:30:41 -07007052void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007053{
7054 ALOGV("closeOutput(%d)", output);
7055
François Gaffie1c878552018-11-22 16:53:21 +01007056 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7057 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007058 ALOGW("closeOutput() unknown output %d", output);
7059 return;
7060 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007061 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007062 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007063
Eric Laurente552edb2014-03-10 17:42:56 -07007064 // look for duplicated outputs connected to the output being removed.
7065 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007066 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7067 if (dupOutput->isDuplicated() &&
7068 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7069 sp<SwAudioOutputDescriptor> remainingOutput =
7070 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007071 // As all active tracks on duplicated output will be deleted,
7072 // and as they were also referenced on the other output, the reference
7073 // count for their stream type must be adjusted accordingly on
7074 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007075 const bool wasActive = remainingOutput->isActive();
7076 // Note: no-op on the closing output where all clients has already been set inactive
7077 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007078 // stop() will be a no op if the output is still active but is needed in case all
7079 // active streams refcounts where cleared above
7080 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007081 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007082 }
Eric Laurente552edb2014-03-10 17:42:56 -07007083 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7084 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7085
7086 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007087 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007088 }
7089 }
7090
Eric Laurent05b90f82014-08-27 15:32:29 -07007091 nextAudioPortGeneration();
7092
François Gaffie1c878552018-11-22 16:53:21 +01007093 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007094 if (index >= 0) {
7095 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007096 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7097 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007098 mAudioPatches.removeItemsAt(index);
7099 mpClientInterface->onAudioPatchListUpdate();
7100 }
7101
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007102 if (closingOutputWasActive) {
7103 closingOutput->stop();
7104 }
François Gaffie1c878552018-11-22 16:53:21 +01007105 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007106 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007107 for (const auto device : closingOutput->devices()) {
7108 device->setPreferredConfig(nullptr);
7109 }
7110 }
Eric Laurente552edb2014-03-10 17:42:56 -07007111
François Gaffie53615e22015-03-19 09:24:12 +01007112 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007113 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007114 if (closingOutput == mSpatializerOutput) {
7115 mSpatializerOutput.clear();
7116 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007117
7118 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7119 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007120 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007121 bool directOutputOpen = false;
7122 for (size_t i = 0; i < mOutputs.size(); i++) {
7123 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7124 directOutputOpen = true;
7125 break;
7126 }
7127 }
7128 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007129 ALOGV("no direct outputs open, reset MSD patches");
7130 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7131 // how output devices for patching are resolved. Avoid by caching and reusing the
7132 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7133 // devices to patch to. This may be complicated by the fact that devices may become
7134 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007135 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007136 }
7137 }
jiabin220eea12024-05-17 17:55:20 +00007138
7139 if (closingOutput->mPreferredAttrInfo != nullptr) {
7140 closingOutput->mPreferredAttrInfo->resetActiveClient();
7141 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007142}
7143
7144void AudioPolicyManager::closeInput(audio_io_handle_t input)
7145{
7146 ALOGV("closeInput(%d)", input);
7147
7148 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7149 if (inputDesc == NULL) {
7150 ALOGW("closeInput() unknown input %d", input);
7151 return;
7152 }
7153
Eric Laurent6a94d692014-05-20 11:18:06 -07007154 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007155
François Gaffie11d30102018-11-02 16:09:09 +01007156 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007157 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007158 if (index >= 0) {
7159 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007160 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7161 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007162 mAudioPatches.removeItemsAt(index);
7163 mpClientInterface->onAudioPatchListUpdate();
7164 }
7165
François Gaffie6ebbce02023-07-19 13:27:53 +02007166 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007167 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007168 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007169
François Gaffie11d30102018-11-02 16:09:09 +01007170 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7171 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007172 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007173 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007174 }
Eric Laurente552edb2014-03-10 17:42:56 -07007175}
7176
François Gaffie11d30102018-11-02 16:09:09 +01007177SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7178 const DeviceVector &devices,
7179 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007180{
7181 SortedVector<audio_io_handle_t> outputs;
7182
François Gaffie11d30102018-11-02 16:09:09 +01007183 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007184 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007185 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007186 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007187 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007188 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007189 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007190 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007191 outputs.add(openOutputs.keyAt(i));
7192 }
7193 }
7194 return outputs;
7195}
7196
Mikhail Naganov37977152018-07-11 15:54:44 -07007197void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7198{
7199 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7200 // output is suspended before any tracks are moved to it
7201 checkA2dpSuspend();
7202 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007203 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007204 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007205 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007206 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007207 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7208 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7209 // configuration changes will ultimately be rerouted correctly. We can still avoid
7210 // unnecessary rerouting by caching and reusing the arguments to
7211 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7212 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007213 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007214 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007215 // an event that changed routing likely occurred, inform upper layers
7216 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007217}
7218
François Gaffiec005e562018-11-06 15:04:49 +01007219bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7220 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007221{
François Gaffiec005e562018-11-06 15:04:49 +01007222 return mEngine->getProductStrategyForAttributes(lAttr) ==
7223 mEngine->getProductStrategyForAttributes(rAttr);
7224}
7225
Francois Gaffieff1eb522020-05-06 18:37:04 +02007226void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7227{
7228 for (size_t i = 0; i < mAudioSources.size(); i++) {
7229 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7230 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007231 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007232 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007233 connectAudioSource(sourceDesc);
7234 }
7235 }
7236}
7237
7238void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7239{
7240 for (size_t i = 0; i < mAudioSources.size(); i++) {
7241 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7242 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7243 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7244 disconnectAudioSource(sourceDesc);
7245 }
7246 }
7247}
7248
François Gaffiec005e562018-11-06 15:04:49 +01007249void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7250{
7251 auto psId = mEngine->getProductStrategyForAttributes(attr);
7252
7253 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7254 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007255
François Gaffie11d30102018-11-02 16:09:09 +01007256 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7257 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007258
Eric Laurentc209fe42020-06-05 18:11:23 -07007259 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007260 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007261 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007262 // take into account dynamic audio policies related changes: if a client is now associated
7263 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007264 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007265 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7266 if (desc->isDuplicated()) {
7267 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007268 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007269 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7270 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7271 continue;
7272 }
7273 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007274 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007275 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7276 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7277 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007278 if (status != OK) {
7279 continue;
7280 }
yucliuf4de36d2020-09-14 14:57:56 -07007281 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007282 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007283 maxLatency = desc->latency();
7284 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007285 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007286 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007287 }
7288 }
7289
Eric Laurent56ed8842022-11-15 16:04:41 +01007290 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007291 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7292 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007293 for (audio_io_handle_t srcOut : srcOutputs) {
7294 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007295 if (desc == nullptr) continue;
7296
7297 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007298 maxLatency = desc->latency();
7299 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007300
Eric Laurent56ed8842022-11-15 16:04:41 +01007301 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007302 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007303 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007304 // a client on a non direct outputs has necessarily a linear PCM format
7305 // so we can call selectOutput() safely
7306 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7307 client->flags(),
7308 client->config().format,
7309 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007310 client->config().sample_rate,
7311 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007312 if (newOutput != srcOut) {
7313 invalidate = true;
7314 break;
7315 }
7316 } else {
7317 sp<IOProfile> profile = getProfileForOutput(newDevices,
7318 client->config().sample_rate,
7319 client->config().format,
7320 client->config().channel_mask,
7321 client->flags(),
7322 true /* directOnly */);
7323 if (profile != desc->mProfile) {
7324 invalidate = true;
7325 break;
7326 }
7327 }
7328 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007329 // mute strategy while moving tracks from one output to another
7330 if (invalidate) {
7331 invalidatedOutputs.push_back(desc);
7332 if (desc->isStrategyActive(psId)) {
7333 setStrategyMute(psId, true, desc);
7334 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7335 newDevices.types());
7336 }
Eric Laurente552edb2014-03-10 17:42:56 -07007337 }
François Gaffiec005e562018-11-06 15:04:49 +01007338 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007339 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007340 connectAudioSource(source);
7341 }
Eric Laurente552edb2014-03-10 17:42:56 -07007342 }
7343
Eric Laurent56ed8842022-11-15 16:04:41 +01007344 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7345 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7346 std::to_string(srcOutputs[0]).c_str(),
7347 std::to_string(dstOutputs[0]).c_str());
7348
François Gaffiec005e562018-11-06 15:04:49 +01007349 // Move effects associated to this stream from previous output to new output
7350 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007351 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007352 }
François Gaffiec005e562018-11-06 15:04:49 +01007353 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007354 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007355 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007356 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007357 desc->setTracksInvalidatedStatusByStrategy(psId);
7358 }
Eric Laurente552edb2014-03-10 17:42:56 -07007359 }
7360 }
7361}
7362
Eric Laurente0720872014-03-11 09:30:41 -07007363void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007364{
François Gaffiec005e562018-11-06 15:04:49 +01007365 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7366 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7367 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007368 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007369 }
Eric Laurente552edb2014-03-10 17:42:56 -07007370}
7371
Kevin Rocard153f92d2018-12-18 18:33:28 -08007372void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007373 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007374 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007375 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007376 for (size_t i = 0; i < mOutputs.size(); i++) {
7377 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7378 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007379 sp<AudioPolicyMix> primaryMix;
7380 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007381 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007382 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7383 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7384 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007385 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7386 for (auto &secondaryMix : secondaryMixes) {
7387 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7388 if (outputDesc != nullptr &&
7389 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7390 secondaryDescs.push_back(outputDesc);
7391 }
7392 }
7393
jiabinc44b3462022-12-08 12:52:31 -08007394 if (status != OK &&
7395 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7396 // When it failed to query secondary output, only invalidate the client that is not
7397 // MMAP. The reason is that MMAP stream will not support secondary output.
7398 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007399 } else if (!std::equal(
7400 client->getSecondaryOutputs().begin(),
7401 client->getSecondaryOutputs().end(),
7402 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007403 if (!audio_is_linear_pcm(client->config().format)) {
7404 // If the format is not PCM, the tracks should be invalidated to get correct
7405 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007406 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007407 } else {
7408 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7409 std::vector<audio_io_handle_t> secondaryOutputIds;
7410 for (const auto &secondaryDesc: secondaryDescs) {
7411 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7412 weakSecondaryDescs.push_back(secondaryDesc);
7413 }
7414 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7415 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007416 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007417 }
7418 }
7419 }
jiabin10a03f12021-05-07 23:46:28 +00007420 if (!trackSecondaryOutputs.empty()) {
7421 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7422 }
jiabinc44b3462022-12-08 12:52:31 -08007423 if (!clientsToInvalidate.empty()) {
7424 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7425 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007426 }
7427}
7428
Eric Laurent2517af32020-11-25 15:31:27 +01007429bool AudioPolicyManager::isScoRequestedForComm() const {
7430 AudioDeviceTypeAddrVector devices;
7431 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7432 for (const auto &device : devices) {
7433 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7434 return true;
7435 }
7436 }
7437 return false;
7438}
7439
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007440bool AudioPolicyManager::isHearingAidUsedForComm() const {
7441 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7442 true /*fromCache*/);
7443 for (const auto &device : devices) {
7444 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7445 return true;
7446 }
7447 }
7448 return false;
7449}
7450
7451
Eric Laurente0720872014-03-11 09:30:41 -07007452void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007453{
François Gaffie53615e22015-03-19 09:24:12 +01007454 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007455 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007456 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007457 return;
7458 }
7459
Eric Laurent3a4311c2014-03-17 12:00:47 -07007460 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007461 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7462 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007463 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007464
7465 // if suspended, restore A2DP output if:
7466 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007467 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007468 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007469 //
Eric Laurentf732e072016-08-03 19:30:28 -07007470 // if not suspended, suspend A2DP output if:
7471 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007472 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007473 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007474 //
7475 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007476 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007477 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007478 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007479 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007480
7481 mpClientInterface->restoreOutput(a2dpOutput);
7482 mA2dpSuspended = false;
7483 }
7484 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007485 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007486 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007487 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007488 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007489
7490 mpClientInterface->suspendOutput(a2dpOutput);
7491 mA2dpSuspended = true;
7492 }
7493 }
7494}
7495
François Gaffie11d30102018-11-02 16:09:09 +01007496DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7497 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007498{
François Gaffiedb1755b2023-09-01 11:50:35 +02007499 if (outputDesc == nullptr) {
7500 return DeviceVector{};
7501 }
François Gaffie11d30102018-11-02 16:09:09 +01007502
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007503 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007504 if (index >= 0) {
7505 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007506 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007507 ALOGV("%s device %s forced by patch %d", __func__,
7508 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7509 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007510 }
7511 }
7512
Dean Wheatley514b4312020-06-17 21:45:00 +10007513 // Do not retrieve engine device for outputs through MSD
7514 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7515 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7516 return outputDesc->devices();
7517 }
7518
Eric Laurent97ac8712018-07-27 18:59:02 -07007519 // Honor explicit routing requests only if no client using default routing is active on this
7520 // input: a specific app can not force routing for other apps by setting a preferred device.
7521 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007522 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007523 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007524 if (device != nullptr) {
7525 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007526 }
7527
François Gaffiea807ef92018-11-05 10:44:33 +01007528 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7529 // of setForceUse / Default Bus device here
7530 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7531 if (device != nullptr) {
7532 return DeviceVector(device);
7533 }
7534
François Gaffiedb1755b2023-09-01 11:50:35 +02007535 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007536 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7537 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307538 auto hasStreamActive = [&](auto stream) {
7539 return hasStream(streams, stream) && isStreamActive(stream, 0);
7540 };
Eric Laurent484e9272018-06-07 17:29:23 -07007541
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307542 auto doGetOutputDevicesForVoice = [&]() {
7543 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007544 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307545 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007546 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7547 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307548 };
7549
7550 // With low-latency playing on speaker, music on WFD, when the first low-latency
7551 // output is stopped, getNewOutputDevices checks for a product strategy
7552 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007553 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307554 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7555 // stream is associated to the output descriptor.
7556 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7557 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7558 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7559 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007560 // Retrieval of devices for voice DL is done on primary output profile, cannot
7561 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007562 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007563 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7564 break;
7565 }
Eric Laurente552edb2014-03-10 17:42:56 -07007566 }
François Gaffiec005e562018-11-06 15:04:49 +01007567 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007568 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007569}
7570
François Gaffie11d30102018-11-02 16:09:09 +01007571sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7572 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007573{
François Gaffie11d30102018-11-02 16:09:09 +01007574 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007575
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007576 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007577 if (index >= 0) {
7578 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007579 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007580 ALOGV("getNewInputDevice() device %s forced by patch %d",
7581 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7582 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007583 }
7584 }
7585
Eric Laurent97ac8712018-07-27 18:59:02 -07007586 // Honor explicit routing requests only if no client using default routing is active on this
7587 // input: a specific app can not force routing for other apps by setting a preferred device.
7588 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007589 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7590 if (device != nullptr) {
7591 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007592 }
7593
Eric Laurentdc95a252018-04-12 12:46:56 -07007594 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007595 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007596 audio_attributes_t attributes;
7597 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007598 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007599 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7600 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007601 attributes = topClient->attributes();
7602 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007603 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007604 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007605 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7606 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007607 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007608 }
7609
Francois Gaffie716e1432019-01-14 16:58:59 +01007610 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7611 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007612 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007613 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007614 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007615 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007616
Eric Laurente552edb2014-03-10 17:42:56 -07007617 return device;
7618}
7619
Eric Laurent794fde22016-03-11 09:50:45 -08007620bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7621 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007622 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007623}
7624
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007625status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007626 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007627 if (devices == nullptr) {
7628 return BAD_VALUE;
7629 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007630
Andy Hung6d23c0f2022-02-16 09:37:15 -08007631 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007632 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7633 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007634 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007635 for (const auto& device : curDevices) {
7636 devices->push_back(device->getDeviceTypeAddr());
7637 }
7638 return NO_ERROR;
7639}
7640
Eric Laurente0720872014-03-11 09:30:41 -07007641void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007642 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007643 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007644 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007645 updateDevicesAndOutputs();
7646 break;
7647 default:
7648 break;
7649 }
7650}
7651
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007652uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007653
7654 // skip beacon mute management if a dedicated TTS output is available
7655 if (mTtsOutputAvailable) {
7656 return 0;
7657 }
7658
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007659 switch(event) {
7660 case STARTING_OUTPUT:
7661 mBeaconMuteRefCount++;
7662 break;
7663 case STOPPING_OUTPUT:
7664 if (mBeaconMuteRefCount > 0) {
7665 mBeaconMuteRefCount--;
7666 }
7667 break;
7668 case STARTING_BEACON:
7669 mBeaconPlayingRefCount++;
7670 break;
7671 case STOPPING_BEACON:
7672 if (mBeaconPlayingRefCount > 0) {
7673 mBeaconPlayingRefCount--;
7674 }
7675 break;
7676 }
7677
7678 if (mBeaconMuteRefCount > 0) {
7679 // any playback causes beacon to be muted
7680 return setBeaconMute(true);
7681 } else {
7682 // no other playback: unmute when beacon starts playing, mute when it stops
7683 return setBeaconMute(mBeaconPlayingRefCount == 0);
7684 }
7685}
7686
7687uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7688 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7689 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7690 // keep track of muted state to avoid repeating mute/unmute operations
7691 if (mBeaconMuted != mute) {
7692 // mute/unmute AUDIO_STREAM_TTS on all outputs
7693 ALOGV("\t muting %d", mute);
7694 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007695 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7696 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7697 ALOGV("\t no tts volume source available");
7698 return 0;
7699 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007700 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007701 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007702 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007703 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007704 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007705 maxLatency = latency;
7706 }
7707 }
7708 mBeaconMuted = mute;
7709 return maxLatency;
7710 }
7711 return 0;
7712}
7713
Eric Laurente0720872014-03-11 09:30:41 -07007714void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007715{
François Gaffiec005e562018-11-06 15:04:49 +01007716 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007717 mPreviousOutputs = mOutputs;
7718}
7719
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007720uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007721 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007722 uint32_t delayMs)
7723{
7724 // mute/unmute strategies using an incompatible device combination
7725 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7726 // if unmuting, unmute only after the specified delay
7727 if (outputDesc->isDuplicated()) {
7728 return 0;
7729 }
7730
7731 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007732 DeviceVector devices = outputDesc->devices();
7733 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007734
François Gaffiec005e562018-11-06 15:04:49 +01007735 auto productStrategies = mEngine->getOrderedProductStrategies();
7736 for (const auto &productStrategy : productStrategies) {
7737 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7738 DeviceVector curDevices =
7739 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7740 curDevices = curDevices.filter(outputDesc->supportedDevices());
7741 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007742 bool doMute = false;
7743
François Gaffiec005e562018-11-06 15:04:49 +01007744 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007745 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007746 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7747 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007748 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007749 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007750 }
Eric Laurent99401132014-05-07 19:48:15 -07007751 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007752 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007753 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007754 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007755 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007756 continue;
7757 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307758 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007759 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7760 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7761 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007762 if (mute) {
7763 // FIXME: should not need to double latency if volume could be applied
7764 // immediately by the audioflinger mixer. We must account for the delay
7765 // between now and the next time the audioflinger thread for this output
7766 // will process a buffer (which corresponds to one buffer size,
7767 // usually 1/2 or 1/4 of the latency).
7768 if (muteWaitMs < desc->latency() * 2) {
7769 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007770 }
7771 }
7772 }
7773 }
7774 }
7775 }
7776
Eric Laurent99401132014-05-07 19:48:15 -07007777 // temporary mute output if device selection changes to avoid volume bursts due to
7778 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007779 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007780 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007781
Eric Laurentdc462862016-07-19 12:29:53 -07007782 if (muteWaitMs < tempMuteWaitMs) {
7783 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007784 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007785
7786 // If recommended duration is defined, replace temporary mute duration to avoid
7787 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7788 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7789 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7790 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7791 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7792
François Gaffieaaac0fd2018-11-22 17:56:39 +01007793 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7794 // make sure that we do not start the temporary mute period too early in case of
7795 // delayed device change
7796 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7797 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007798 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007799 }
7800 }
7801
Eric Laurente552edb2014-03-10 17:42:56 -07007802 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7803 if (muteWaitMs > delayMs) {
7804 muteWaitMs -= delayMs;
7805 usleep(muteWaitMs * 1000);
7806 return muteWaitMs;
7807 }
7808 return 0;
7809}
7810
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307811uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7812 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007813 const DeviceVector &devices,
7814 bool force,
7815 int delayMs,
7816 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007817 bool requiresMuteCheck, bool requiresVolumeCheck,
7818 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007819{
jiabin3ff8d7d2022-12-13 06:27:44 +00007820 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307821 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7822 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7823 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007824 uint32_t muteWaitMs;
7825
7826 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307827 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007828 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307829 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007830 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007831 return muteWaitMs;
7832 }
Eric Laurente552edb2014-03-10 17:42:56 -07007833
7834 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007835 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007836 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007837 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007838
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307839 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7840 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007841
7842 if (!filteredDevices.isEmpty()) {
7843 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007844 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007845
7846 // if the outputs are not materially active, there is no need to mute.
7847 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007848 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007849 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307850 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7851 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007852 muteWaitMs = 0;
7853 }
Eric Laurente552edb2014-03-10 17:42:56 -07007854
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007855 bool outputRouted = outputDesc->isRouted();
7856
Eric Laurent79ea9582020-06-11 18:49:24 -07007857 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7858 // output profile or if new device is not supported AND previous device(s) is(are) still
7859 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007860 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307861 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7862 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007863 // restore previous device after evaluating strategy mute state
7864 outputDesc->setDevices(prevDevices);
7865 return muteWaitMs;
7866 }
7867
Eric Laurente552edb2014-03-10 17:42:56 -07007868 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007869 // the requested device is AUDIO_DEVICE_NONE
7870 // OR the requested device is the same as current device
7871 // AND force is not specified
7872 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007873 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007874 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307875 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7876 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7877 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007878 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307879 ALOGV("%s %s setting same device on routed output, force apply volumes",
7880 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007881 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7882 }
Eric Laurente552edb2014-03-10 17:42:56 -07007883 return muteWaitMs;
7884 }
7885
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307886 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7887 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007888
Eric Laurente552edb2014-03-10 17:42:56 -07007889 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007890 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007891 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007892 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007893 PatchBuilder patchBuilder;
7894 patchBuilder.addSource(outputDesc);
7895 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7896 for (const auto &filteredDevice : filteredDevices) {
7897 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007898 }
7899
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007900 // Add half reported latency to delayMs when muteWaitMs is null in order
7901 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007902 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7903 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7904 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007905 }
Eric Laurente552edb2014-03-10 17:42:56 -07007906
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007907 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7908 if (!skipMuteDelay) {
7909 // update stream volumes according to new device
7910 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7911 }
Eric Laurente552edb2014-03-10 17:42:56 -07007912
7913 return muteWaitMs;
7914}
7915
Eric Laurentc75307b2015-03-17 15:29:32 -07007916status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007917 int delayMs,
7918 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007919{
Eric Laurent6a94d692014-05-20 11:18:06 -07007920 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007921 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7922 return INVALID_OPERATION;
7923 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007924 if (patchHandle) {
7925 index = mAudioPatches.indexOfKey(*patchHandle);
7926 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007927 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007928 }
7929 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007930 return INVALID_OPERATION;
7931 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007932 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007933 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007934 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007935 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007936 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007937 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007938 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007939 return status;
7940}
7941
7942status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007943 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007944 bool force,
7945 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007946{
7947 status_t status = NO_ERROR;
7948
Eric Laurent1f2f2232014-06-02 12:01:23 -07007949 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007950 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7951 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007952
François Gaffie11d30102018-11-02 16:09:09 +01007953 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007954 PatchBuilder patchBuilder;
7955 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007956 // AUDIO_SOURCE_HOTWORD is for internal use only:
7957 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007958 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7959 auto result = usecase;
7960 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7961 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7962 }
7963 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007964 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007965 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007966 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007967 }
7968 }
7969 return status;
7970}
7971
Eric Laurent6a94d692014-05-20 11:18:06 -07007972status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7973 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007974{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007975 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007976 ssize_t index;
7977 if (patchHandle) {
7978 index = mAudioPatches.indexOfKey(*patchHandle);
7979 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007980 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007981 }
7982 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007983 return INVALID_OPERATION;
7984 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007985 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007986 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007987 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007988 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007989 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007990 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007991 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007992 return status;
7993}
7994
François Gaffie11d30102018-11-02 16:09:09 +01007995sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007996 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007997 audio_format_t& format,
7998 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007999 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008000{
8001 // Choose an input profile based on the requested capture parameters: select the first available
8002 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008003 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008004
Atneya Nair0f0a8032022-12-12 16:20:12 -08008005 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8006 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8007 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8008
8009 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008010
jiabin2fd710d2022-05-02 23:20:22 +00008011 for (;;) {
8012 sp<IOProfile> firstInexact = nullptr;
8013 uint32_t updatedSamplingRate = 0;
8014 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8015 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8016 for (const auto& hwModule : mHwModules) {
8017 for (const auto& profile : hwModule->getInputProfiles()) {
8018 // profile->log();
8019 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008020 if (profile->getCompatibilityScore(
8021 DeviceVector(device),
8022 samplingRate,
8023 &updatedSamplingRate,
8024 format,
8025 &updatedFormat,
8026 channelMask,
8027 &updatedChannelMask,
8028 // FIXME ugly cast
8029 (audio_output_flags_t) flags,
8030 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8031 samplingRate = updatedSamplingRate;
8032 format = updatedFormat;
8033 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008034 return profile;
8035 }
jiabin66acc432024-02-06 00:57:36 +00008036 if (firstInexact == nullptr
8037 && profile->getCompatibilityScore(
8038 DeviceVector(device),
8039 samplingRate,
8040 &updatedSamplingRate,
8041 format,
8042 &updatedFormat,
8043 channelMask,
8044 &updatedChannelMask,
8045 // FIXME ugly cast
8046 (audio_output_flags_t) flags,
8047 false /*exactMatchRequiredForInputFlags*/)
8048 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008049 firstInexact = profile;
8050 }
8051 }
8052 }
8053
8054 if (firstInexact != nullptr) {
8055 samplingRate = updatedSamplingRate;
8056 format = updatedFormat;
8057 channelMask = updatedChannelMask;
8058 return firstInexact;
8059 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8060 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8061 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8062 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8063 flags = AUDIO_INPUT_FLAG_NONE;
8064 } else { // fail
8065 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8066 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8067 samplingRate, format, channelMask, oriFlags);
8068 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008069 }
8070 }
jiabin2fd710d2022-05-02 23:20:22 +00008071
8072 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008073}
8074
Vlad Popa87e0e582024-05-20 18:49:20 -07008075float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8076 VolumeSource volumeSource,
8077 int index,
8078 const DeviceTypeSet &deviceTypes)
8079{
8080 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8081 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8082 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8083
8084 if (com_android_media_audio_abs_volume_index_fix()) {
8085 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8086 mAbsoluteVolumeDrivingStreams.end()) {
8087 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8088 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8089 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8090 ALOGD("%s: no group matching with %s", __FUNCTION__,
8091 toString(attributesToDriveAbs).c_str());
8092 return volumeDb;
8093 }
8094
8095 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8096 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8097 if (vsToDriveAbs == volumeSource) {
8098 // attenuation is applied by the abs volume controller
8099 return volumeDbMax;
8100 } else {
8101 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8102 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8103 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8104 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8105 curvesAbs.getVolumeIndexMax());
8106 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8107 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8108 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8109 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8110 return newVolumeDb;
8111 }
8112 }
8113 return volumeDb;
8114 } else {
8115 return volumeDb;
8116 }
8117}
8118
François Gaffieaaac0fd2018-11-22 17:56:39 +01008119float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8120 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008121 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008122 const DeviceTypeSet& deviceTypes,
8123 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008124{
Vlad Popa87e0e582024-05-20 18:49:20 -07008125 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008126 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8127 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8128
8129 if (!computeInternalInteraction) {
8130 return volumeDb;
8131 }
8132
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008133 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8134 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8135 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8136 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008137 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8138 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8139 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8140 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8141 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008142 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008143 mOutputs.isActive(ringVolumeSrc, 0)) {
8144 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008145 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8146 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008147 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008148 }
8149
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008150 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008151 if ((volumeSource != callVolumeSrc && (isInCall() ||
8152 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008153 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008154 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8155 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008156 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8157 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8158 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008159 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008160 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008161 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008162 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008163 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8164 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008165 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008166 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8167 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8168 // programmatically muted.
8169 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8170 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8171 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008172 bool exemptFromCapping =
8173 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8174 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008175 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8176 volumeSource, volumeDb);
8177 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008178 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8179 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8180 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008181 }
8182 }
Eric Laurente552edb2014-03-10 17:42:56 -07008183 // if a headset is connected, apply the following rules to ring tones and notifications
8184 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008185 // - always attenuate notifications volume by 6dB
8186 // - attenuate ring tones volume by 6dB unless music is not playing and
8187 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008188 // - if music is playing, always limit the volume to current music volume,
8189 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008190 if (!Intersection(deviceTypes,
8191 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8192 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008193 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8194 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008195 ((volumeSource == alarmVolumeSrc ||
8196 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008197 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8198 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8199 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008200 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8201 curves.canBeMuted()) {
8202
Eric Laurente552edb2014-03-10 17:42:56 -07008203 // when the phone is ringing we must consider that music could have been paused just before
8204 // by the music application and behave as if music was active if the last music track was
8205 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008206 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8207 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008208 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008209 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008210 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8211 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008212 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008213 float musicVolDb = computeVolume(musicCurves,
8214 musicVolumeSrc,
8215 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008216 musicDevice,
8217 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008218 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8219 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8220 if (volumeDb > minVolDb) {
8221 volumeDb = minVolDb;
8222 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008223 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008224 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8225 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008226 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8227 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8228 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8229 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008230 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008231 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008232 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8233 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008234 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8235 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008236 }
8237 }
jiabin9a3361e2019-10-01 09:38:30 -07008238 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008239 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008240 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008241 }
8242 }
8243
François Gaffie43c73442018-11-08 08:21:55 +01008244 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008245}
8246
Eric Laurent3839bc02018-07-10 18:33:34 -07008247int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008248 VolumeSource fromVolumeSource,
8249 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008250{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008251 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008252 return srcIndex;
8253 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008254 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8255 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008256 float minSrc = (float)srcCurves.getVolumeIndexMin();
8257 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8258 float minDst = (float)dstCurves.getVolumeIndexMin();
8259 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008260
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008261 // preserve mute request or correct range
8262 if (srcIndex < minSrc) {
8263 if (srcIndex == 0) {
8264 return 0;
8265 }
8266 srcIndex = minSrc;
8267 } else if (srcIndex > maxSrc) {
8268 srcIndex = maxSrc;
8269 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008270 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8271}
8272
François Gaffieaaac0fd2018-11-22 17:56:39 +01008273status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8274 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008275 int index,
8276 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008277 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008278 int delayMs,
8279 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008280{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008281 // do not change actual attributes volume if the attributes is muted
8282 if (outputDesc->isMuted(volumeSource)) {
8283 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8284 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008285 return NO_ERROR;
8286 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008287
Eric Laurentae6e88c2024-01-10 14:42:57 +01008288 bool isVoiceVolSrc;
8289 bool isBtScoVolSrc;
8290 if (!isVolumeConsistentForCalls(
8291 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008292 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008293 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008294 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008295 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008296
jiabin9a3361e2019-10-01 09:38:30 -07008297 if (deviceTypes.empty()) {
8298 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008299 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008300 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008301 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008302 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008303
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008304 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8305 ALOGE("invalid volume index range");
8306 return BAD_VALUE;
8307 }
8308
jiabin9a3361e2019-10-01 09:38:30 -07008309 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8310 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008311 // Force VoIP volume to max for bluetooth SCO device except if muted
8312 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008313 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008314 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008315 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008316 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008317 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8318 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008319
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008320 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008321 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008322 }
Eric Laurente552edb2014-03-10 17:42:56 -07008323 return NO_ERROR;
8324}
8325
Eric Laurentae6e88c2024-01-10 14:42:57 +01008326void AudioPolicyManager::setVoiceVolume(
8327 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8328 float voiceVolume;
8329 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8330 // by the headset
8331 if (isVoiceVolSrc) {
8332 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8333 } else {
8334 voiceVolume = index == 0 ? 0.0 : 1.0;
8335 }
8336 if (voiceVolume != mLastVoiceVolume) {
8337 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8338 mLastVoiceVolume = voiceVolume;
8339 }
8340}
8341
8342bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8343 const DeviceTypeSet& deviceTypes,
8344 bool& isVoiceVolSrc,
8345 bool& isBtScoVolSrc,
8346 const char* caller) {
8347 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8348 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8349 const bool isScoRequested = isScoRequestedForComm();
8350 const bool isHAUsed = isHearingAidUsedForComm();
8351
8352 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8353 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8354
8355 if ((callVolSrc != btScoVolSrc) &&
8356 ((isVoiceVolSrc && isScoRequested) ||
8357 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8358 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8359 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8360 volumeSource, isScoRequested ? " " : " not ");
8361 return false;
8362 }
8363 return true;
8364}
8365
Eric Laurentc75307b2015-03-17 15:29:32 -07008366void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008367 const DeviceTypeSet& deviceTypes,
8368 int delayMs,
8369 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008370{
jiabincd510522020-01-22 09:40:55 -08008371 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008372 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8373 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8374 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008375 curves.getVolumeIndex(deviceTypes),
8376 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008377 }
8378}
8379
François Gaffiec005e562018-11-06 15:04:49 +01008380void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8381 bool on,
8382 const sp<AudioOutputDescriptor>& outputDesc,
8383 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008384 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008385{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008386 std::vector<VolumeSource> sourcesToMute;
8387 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8388 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8389 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008390 VolumeSource source = toVolumeSource(attributes, false);
8391 if ((source != VOLUME_SOURCE_NONE) &&
8392 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8393 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008394 sourcesToMute.push_back(source);
8395 }
Eric Laurente552edb2014-03-10 17:42:56 -07008396 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008397 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008398 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008399 }
8400
Eric Laurente552edb2014-03-10 17:42:56 -07008401}
8402
François Gaffieaaac0fd2018-11-22 17:56:39 +01008403void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8404 bool on,
8405 const sp<AudioOutputDescriptor>& outputDesc,
8406 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008407 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008408{
jiabin9a3361e2019-10-01 09:38:30 -07008409 if (deviceTypes.empty()) {
8410 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008411 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008412 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008413 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008414 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008415 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008416 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008417 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8418 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008419 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008420 }
8421 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008422 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8423 // ignored
8424 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008425 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008426 if (!outputDesc->isMuted(volumeSource)) {
8427 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008428 return;
8429 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008430 if (outputDesc->decMuteCount(volumeSource) == 0) {
8431 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008432 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008433 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008434 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008435 delayMs);
8436 }
8437 }
8438}
8439
François Gaffie53615e22015-03-19 09:24:12 +01008440bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8441{
François Gaffiec005e562018-11-06 15:04:49 +01008442 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008443 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8444 return true;
8445 }
8446
8447 // has known usage?
8448 switch (paa->usage) {
8449 case AUDIO_USAGE_UNKNOWN:
8450 case AUDIO_USAGE_MEDIA:
8451 case AUDIO_USAGE_VOICE_COMMUNICATION:
8452 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8453 case AUDIO_USAGE_ALARM:
8454 case AUDIO_USAGE_NOTIFICATION:
8455 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8456 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8457 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8458 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8459 case AUDIO_USAGE_NOTIFICATION_EVENT:
8460 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8461 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8462 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8463 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008464 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008465 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008466 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008467 case AUDIO_USAGE_EMERGENCY:
8468 case AUDIO_USAGE_SAFETY:
8469 case AUDIO_USAGE_VEHICLE_STATUS:
8470 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008471 break;
8472 default:
8473 return false;
8474 }
8475 return true;
8476}
8477
François Gaffie2110e042015-03-24 08:41:51 +01008478audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8479{
8480 return mEngine->getForceUse(usage);
8481}
8482
Eric Laurent96d1dda2022-03-14 17:14:19 +01008483bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008484 return isStateInCall(mEngine->getPhoneState());
8485}
8486
Eric Laurent96d1dda2022-03-14 17:14:19 +01008487bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008488 return is_state_in_call(state);
8489}
8490
Eric Laurentf9cccec2022-11-16 19:12:00 +01008491bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008492 audio_mode_t mode = mEngine->getPhoneState();
8493 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008494 || (mode == AUDIO_MODE_CALL_SCREEN)
8495 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008496}
8497
Eric Laurentf9cccec2022-11-16 19:12:00 +01008498bool AudioPolicyManager::isInCallOrScreening() const {
8499 audio_mode_t mode = mEngine->getPhoneState();
8500 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8501}
8502
Eric Laurentd60560a2015-04-10 11:31:20 -07008503void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8504{
8505 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008506 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008507 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008508 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008509 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008510 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008511 }
8512 }
8513
8514 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8515 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8516 bool release = false;
8517 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8518 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8519 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8520 source->ext.device.type == deviceDesc->type()) {
8521 release = true;
8522 }
8523 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008524 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008525 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8526 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8527 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008528 sink->ext.device.type == deviceDesc->type() &&
8529 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8530 || strncmp(sink->ext.device.address, address,
8531 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008532 release = true;
8533 }
8534 }
8535 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008536 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8537 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008538 }
8539 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008540
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008541 mInputs.clearSessionRoutesForDevice(deviceDesc);
8542
Francois Gaffie716e1432019-01-14 16:58:59 +01008543 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008544}
8545
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008546void AudioPolicyManager::modifySurroundFormats(
8547 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008548 std::unordered_set<audio_format_t> enforcedSurround(
8549 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008550 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008551 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008552 allSurround.insert(pair.first);
8553 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8554 }
Phil Burk09bc4612016-02-24 15:58:15 -08008555
8556 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8557 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008558 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008559 // This is the resulting set of formats depending on the surround mode:
8560 // 'all surround' = allSurround
8561 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8562 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8563 // 'manual surround' = mManualSurroundFormats
8564 // AUTO: formats v 'enforced surround'
8565 // ALWAYS: formats v 'all surround' v 'enforced surround'
8566 // NEVER: formats ^ 'non-surround'
8567 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008568
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008569 std::unordered_set<audio_format_t> formatSet;
8570 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8571 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008572 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008573 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008574 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008575 formatSet.insert(*formatIter);
8576 }
8577 }
8578 } else {
8579 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8580 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008581 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008582
jiabin81772902018-04-02 17:52:27 -07008583 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008584 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008585 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8586 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8587 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008588 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008589 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8590 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8591 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008592 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008593 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008594 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008595 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008596 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008597 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008598}
8599
jiabin06e4bab2019-07-29 10:13:34 -07008600void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8601 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008602 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8603 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8604
8605 // If NEVER, then remove support for channelMasks > stereo.
8606 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008607 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8608 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008609 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008610 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008611 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008612 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008613 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008614 }
8615 }
jiabin81772902018-04-02 17:52:27 -07008616 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8617 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8618 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008619 bool supports5dot1 = false;
8620 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008621 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008622 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8623 supports5dot1 = true;
8624 break;
8625 }
8626 }
8627 // If not then add 5.1 support.
8628 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008629 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008630 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008631 }
Phil Burk09bc4612016-02-24 15:58:15 -08008632 }
8633}
8634
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008635void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008636 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008637 const sp<IOProfile>& profile) {
8638 if (!profile->hasDynamicAudioProfile()) {
8639 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008640 }
François Gaffie112b0af2015-11-19 16:13:25 +01008641
jiabin12537fc2023-10-12 17:56:08 +00008642 audio_port_v7 devicePort;
8643 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008644
jiabin12537fc2023-10-12 17:56:08 +00008645 audio_port_v7 mixPort;
8646 profile->toAudioPort(&mixPort);
8647 mixPort.ext.mix.handle = ioHandle;
8648
8649 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8650 if (status != NO_ERROR) {
8651 ALOGE("%s failed to query the attributes of the mix port", __func__);
8652 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008653 }
jiabin12537fc2023-10-12 17:56:08 +00008654
8655 std::set<audio_format_t> supportedFormats;
8656 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8657 supportedFormats.insert(mixPort.audio_profiles[i].format);
8658 }
8659 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8660 mReportedFormatsMap[devDesc] = formats;
8661
8662 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8663 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8664 modifySurroundFormats(devDesc, &formats);
8665 size_t modifiedNumProfiles = 0;
8666 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8667 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8668 formats.end()) {
8669 // Skip the format that is not present after modifying surround formats.
8670 continue;
8671 }
8672 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8673 sizeof(struct audio_profile));
8674 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8675 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8676 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8677 modifySurroundChannelMasks(&channels);
8678 std::copy(channels.begin(), channels.end(),
8679 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8680 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8681 }
8682 mixPort.num_audio_profiles = modifiedNumProfiles;
8683 }
8684 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008685}
Eric Laurentd60560a2015-04-10 11:31:20 -07008686
Mikhail Naganovdc769682018-05-04 15:34:08 -07008687status_t AudioPolicyManager::installPatch(const char *caller,
8688 audio_patch_handle_t *patchHandle,
8689 AudioIODescriptorInterface *ioDescriptor,
8690 const struct audio_patch *patch,
8691 int delayMs)
8692{
8693 ssize_t index = mAudioPatches.indexOfKey(
8694 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8695 *patchHandle : ioDescriptor->getPatchHandle());
8696 sp<AudioPatch> patchDesc;
8697 status_t status = installPatch(
8698 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8699 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008700 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008701 }
8702 return status;
8703}
8704
8705status_t AudioPolicyManager::installPatch(const char *caller,
8706 ssize_t index,
8707 audio_patch_handle_t *patchHandle,
8708 const struct audio_patch *patch,
8709 int delayMs,
8710 uid_t uid,
8711 sp<AudioPatch> *patchDescPtr)
8712{
8713 sp<AudioPatch> patchDesc;
8714 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8715 if (index >= 0) {
8716 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008717 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008718 }
8719
8720 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8721 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8722 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8723 if (status == NO_ERROR) {
8724 if (index < 0) {
8725 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008726 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008727 } else {
8728 patchDesc->mPatch = *patch;
8729 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008730 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008731 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008732 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008733 }
8734 nextAudioPortGeneration();
8735 mpClientInterface->onAudioPatchListUpdate();
8736 }
8737 if (patchDescPtr) *patchDescPtr = patchDesc;
8738 return status;
8739}
8740
jiabinbce0c1d2020-10-05 11:20:18 -07008741bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8742{
8743 const TrackClientVector activeClients = output->getActiveClients();
8744 if (activeClients.empty()) {
8745 return true;
8746 }
8747 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8748 if (index < 0) {
8749 ALOGE("%s, no audio patch found while there are active clients on output %d",
8750 __func__, output->getId());
8751 return false;
8752 }
8753 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8754 DeviceVector routedDevices;
8755 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8756 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8757 patchDesc->mPatch.sinks[i].id);
8758 if (device == nullptr) {
8759 ALOGE("%s, no audio device found with id(%d)",
8760 __func__, patchDesc->mPatch.sinks[i].id);
8761 return false;
8762 }
8763 routedDevices.add(device);
8764 }
8765 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008766 if (client->isInvalid()) {
8767 // No need to take care about invalidated clients.
8768 continue;
8769 }
jiabinbce0c1d2020-10-05 11:20:18 -07008770 sp<DeviceDescriptor> preferredDevice =
8771 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8772 if (mEngine->getOutputDevicesForAttributes(
8773 client->attributes(), preferredDevice, false) == routedDevices) {
8774 return false;
8775 }
8776 }
8777 return true;
8778}
8779
8780sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008781 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008782 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8783 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008784{
8785 for (const auto& device : devices) {
8786 // TODO: This should be checking if the profile supports the device combo.
8787 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008788 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8789 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008790 return nullptr;
8791 }
8792 }
8793 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8794 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008795 status_t status = desc->open(halConfig, mixerConfig, devices,
8796 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008797 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008798 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008799 return nullptr;
8800 }
jiabin14b50cc2023-12-13 19:01:52 +00008801 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8802 auto portConfig = desc->getConfig();
8803 for (const auto& device : devices) {
8804 device->setPreferredConfig(&portConfig);
8805 }
8806 }
jiabinbce0c1d2020-10-05 11:20:18 -07008807
8808 // Here is where the out_set_parameters() for card & device gets called
8809 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8810 const audio_devices_t deviceType = device->type();
8811 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008812 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008813 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8814 mpClientInterface->setParameters(output, String8(param));
8815 free(param);
8816 }
jiabin12537fc2023-10-12 17:56:08 +00008817 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008818 if (!profile->hasValidAudioProfile()) {
8819 ALOGW("%s() missing param", __func__);
8820 desc->close();
8821 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008822 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8823 // Reopen the output with the best audio profile picked by APM when the profile supports
8824 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008825 desc->close();
8826 output = AUDIO_IO_HANDLE_NONE;
8827 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8828 profile->pickAudioProfile(
8829 config.sample_rate, config.channel_mask, config.format);
8830 config.offload_info.sample_rate = config.sample_rate;
8831 config.offload_info.channel_mask = config.channel_mask;
8832 config.offload_info.format = config.format;
8833
jiabina84c3d32022-12-02 18:59:55 +00008834 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008835 if (status != NO_ERROR) {
8836 return nullptr;
8837 }
8838 }
8839
8840 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008841 setOutputDevices(__func__, desc,
8842 devices,
8843 true,
8844 0,
8845 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008846 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8847 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8848
jiabinbce0c1d2020-10-05 11:20:18 -07008849 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8850 sp<AudioPolicyMix> policyMix;
8851 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8852 policyMix->setOutput(desc);
8853 desc->mPolicyMix = policyMix;
8854 } else {
8855 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008856 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008857 }
8858
baek.kim -61c20122022-07-27 10:05:32 +00008859 } else if (hasPrimaryOutput() && speaker != nullptr
8860 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008861 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8862 // no duplicated output for:
8863 // - direct outputs
8864 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008865 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008866 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8867
8868 //TODO: configure audio effect output stage here
8869
8870 // open a duplicating output thread for the new output and the primary output
8871 sp<SwAudioOutputDescriptor> dupOutputDesc =
8872 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8873 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8874 if (status == NO_ERROR) {
8875 // add duplicated output descriptor
8876 addOutput(duplicatedOutput, dupOutputDesc);
8877 } else {
8878 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8879 mPrimaryOutput->mIoHandle, output);
8880 desc->close();
8881 removeOutput(output);
8882 nextAudioPortGeneration();
8883 return nullptr;
8884 }
8885 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008886 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8887 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8888 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008889 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008890 }
jiabinbce0c1d2020-10-05 11:20:18 -07008891 return desc;
8892}
8893
jiabinf1c73972022-04-14 16:28:52 -07008894status_t AudioPolicyManager::getDevicesForAttributes(
8895 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8896 // Devices are determined in the following precedence:
8897 //
8898 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8899 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8900 //
8901 // If no such dynamic policy then
8902 // 2) Devices containing an active client using setPreferredDevice
8903 // with same strategy as the attributes.
8904 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8905 //
8906 // If no corresponding active client with setPreferredDevice then
8907 // 3) Devices associated with the strategy determined by the attributes
8908 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8909 //
8910 // See related getOutputForAttrInt().
8911
8912 // check dynamic policies but only for primary descriptors (secondary not used for audible
8913 // audio routing, only used for duplication for playback capture)
8914 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008915 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008916 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008917 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8918 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8919 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008920 if (status != OK) {
8921 return status;
8922 }
8923
8924 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8925 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8926 // as they are unaffected by device/stream volume
8927 // (per SwAudioOutputDescriptor::isFixedVolume()).
8928 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8929 ) {
8930 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8931 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8932 devices.add(deviceDesc);
8933 } else {
8934 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8935 // which selects setPreferredDevice if active. This means forVolume call
8936 // will take an active setPreferredDevice, if such exists.
8937
8938 devices = mEngine->getOutputDevicesForAttributes(
8939 attr, nullptr /* preferredDevice */, false /* fromCache */);
8940 }
8941
8942 if (forVolume) {
8943 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8944 // for single volume control in AudioService (such relationship should exist if
8945 // SPEAKER_SAFE is present).
8946 //
8947 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8948 DeviceVector speakerSafeDevices =
8949 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8950 if (!speakerSafeDevices.isEmpty()) {
8951 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8952 devices.remove(speakerSafeDevices);
8953 }
8954 }
8955
8956 return NO_ERROR;
8957}
8958
8959status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8960 AudioProfileVector& audioProfiles,
8961 uint32_t flags,
8962 bool isInput) {
8963 for (const auto& hwModule : mHwModules) {
8964 // the MSD module checks for different conditions
8965 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8966 continue;
8967 }
8968 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8969 : hwModule->getOutputProfiles();
8970 for (const auto& profile : ioProfiles) {
8971 if (!profile->areAllDevicesSupported(devices) ||
8972 !profile->isCompatibleProfileForFlags(
8973 flags, false /*exactMatchRequiredForInputFlags*/)) {
8974 continue;
8975 }
8976 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8977 }
8978 }
8979
8980 if (!isInput) {
8981 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8982 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8983 if (msdModule != nullptr) {
8984 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8985 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8986 for (const auto &profile: msdModule->getOutputProfiles()) {
8987 if (!profile->asAudioPort()->isDirectOutput()) {
8988 continue;
8989 }
8990 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8991 }
8992 } else {
8993 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8994 }
8995 }
8996 }
8997
8998 return NO_ERROR;
8999}
9000
jiabin3ff8d7d2022-12-13 06:27:44 +00009001sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9002 const audio_config_t *config,
9003 audio_output_flags_t flags,
9004 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009005 closeOutput(outputDesc->mIoHandle);
9006 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9007 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9008 if (preferredOutput == nullptr) {
9009 ALOGE("%s failed to reopen output device=%d, caller=%s",
9010 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009011 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009012 return preferredOutput;
9013}
9014
9015void AudioPolicyManager::reopenOutputsWithDevices(
9016 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9017 for (const auto& [output, devices] : outputsToReopen) {
9018 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9019 closeOutput(output);
9020 openOutputWithProfileAndDevice(desc->mProfile, devices);
9021 }
jiabina84c3d32022-12-02 18:59:55 +00009022}
9023
jiabinc44b3462022-12-08 12:52:31 -08009024PortHandleVector AudioPolicyManager::getClientsForStream(
9025 audio_stream_type_t streamType) const {
9026 PortHandleVector clients;
9027 for (size_t i = 0; i < mOutputs.size(); ++i) {
9028 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9029 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9030 }
9031 return clients;
9032}
9033
9034void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9035 PortHandleVector clients;
9036 for (auto stream : streams) {
9037 PortHandleVector clientsForStream = getClientsForStream(stream);
9038 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9039 }
9040 mpClientInterface->invalidateTracks(clients);
9041}
9042
jiabin220eea12024-05-17 17:55:20 +00009043void AudioPolicyManager::updateClientsInternalMute(
9044 const sp<android::SwAudioOutputDescriptor> &desc) {
9045 if (!desc->isBitPerfect() ||
9046 !com::android::media::audioserver::
9047 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9048 // This is only used for bit perfect output now.
9049 return;
9050 }
9051 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9052 bool bitPerfectClientInternalMute = false;
9053 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9054 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9055 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9056 bitPerfectClient = client;
9057 continue;
9058 }
9059 bool muted = false;
9060 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9061 // System sound is muted.
9062 muted = true;
9063 } else {
9064 bitPerfectClientInternalMute = true;
9065 }
9066 if (client->setInternalMute(muted)) {
9067 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9068 if (!result.ok()) {
9069 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9070 continue;
9071 }
9072 media::TrackInternalMuteInfo info;
9073 info.portId = result.value();
9074 info.muted = client->getInternalMute();
9075 clientsInternalMute.push_back(std::move(info));
9076 }
9077 }
9078 if (bitPerfectClient != nullptr &&
9079 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9080 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9081 if (result.ok()) {
9082 media::TrackInternalMuteInfo info;
9083 info.portId = result.value();
9084 info.muted = bitPerfectClient->getInternalMute();
9085 clientsInternalMute.push_back(std::move(info));
9086 } else {
9087 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9088 __func__, bitPerfectClient->portId());
9089 }
9090 }
9091 if (!clientsInternalMute.empty()) {
9092 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9093 status != NO_ERROR) {
9094 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9095 }
9096 }
9097}
9098
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009099} // namespace android