blob: 739e201d6d5d7dbf715e24695def3314d1cc15ed [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();
Jaideep Sharma33173202024-06-18 17:46:45 +0530378 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700379 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } // end if is output device
381
Eric Laurente552edb2014-03-10 17:42:56 -0700382 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700383 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700385 switch (state)
386 {
387 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700388 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700389 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700391 return INVALID_OPERATION;
392 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700393
Jaideep Sharma33173202024-06-18 17:46:45 +0530394 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
395
Eric Laurent0dd51852019-04-19 18:18:58 -0700396 if (mAvailableInputDevices.add(device) < 0) {
397 return NO_MEMORY;
398 }
399
François Gaffie44481e72016-04-20 07:49:57 +0200400 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
401 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000402 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 // Propagate device availability to Engine
404 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700407 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
408
Eric Laurent0dd51852019-04-19 18:18:58 -0700409 mAvailableInputDevices.remove(device);
410
jiabinc0048632023-04-27 22:04:31 +0000411 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100412
413 mHwModules.cleanUpForDevice(device);
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 return INVALID_OPERATION;
416 }
417
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700421 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700424 return INVALID_OPERATION;
425 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700426
François Gaffie11d30102018-11-02 16:09:09 +0100427 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
jiabinc0048632023-04-27 22:04:31 +0000429 // Notify the HAL to prepare to disconnect device
430 broadcastDeviceConnectionState(
431 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700432
François Gaffie11d30102018-11-02 16:09:09 +0100433 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700434
435 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436
jiabinc0048632023-04-27 22:04:31 +0000437 // Set Disconnect to HALs
438 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
439
Kriti Dangef6be8f2020-11-05 11:58:19 +0100440 // remove device from mReportedFormatsMap cache
441 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700442
443 // Propagate device availability to Engine
444 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700446
447 default:
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450 }
451
Eric Laurent0dd51852019-04-19 18:18:58 -0700452 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700453 // As the input device list can impact the output device selection, update
454 // getDeviceForStrategy() cache
455 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700456
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100457 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200458 // Reconnect Audio Source
459 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
460 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
461 checkAudioSourceForAttributes(attributes);
462 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700463 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100464 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700465 }
466
Eric Laurentb52c1522014-05-20 11:27:36 -0700467 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530468 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700470 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700471
François Gaffie11d30102018-11-02 16:09:09 +0100472 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700473 return BAD_VALUE;
474}
475
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100476status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
477 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800478 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700479 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
480 devDescr->setName(device_name);
481 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100482}
483
Eric Laurent736a1022019-03-27 18:28:46 -0700484void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
485 audio_policy_dev_state_t state) {
486
487 // the Engine does not have to know about remote submix devices used by dynamic audio policies
488 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
489 return;
490 }
491 mEngine->setDeviceConnectionState(device, state);
492}
493
494
Eric Laurente0720872014-03-11 09:30:41 -0700495audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100496 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700497{
Eric Laurent634b7142016-04-20 13:48:02 -0700498 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
500 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700501 (strlen(device_address) != 0)/*matchAddress*/);
502
503 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100504 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700505 device, device_address);
506 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
507 }
François Gaffie53615e22015-03-19 09:24:12 +0100508
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 DeviceVector *deviceVector;
510
Eric Laurente552edb2014-03-10 17:42:56 -0700511 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700514 deviceVector = &mAvailableInputDevices;
515 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100516 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700517 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700518 }
Eric Laurent634b7142016-04-20 13:48:02 -0700519
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 return (deviceVector->getDevice(
521 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800523}
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
526 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 const char *device_name,
528 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
531 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800533 // connect/disconnect only 1 device at a time
534 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
535
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800536 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700537 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539 // Nothing to do: device is not connected
540 return NO_ERROR;
541 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700544 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 // configure codecs.
546 // Handle two specific cases by sending a set parameter to
547 // configure A2DP codecs. No need to toggle device state.
548 // Case 1: A2DP active device switches from primary to primary
549 // module
550 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700552 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800553 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
554 if (availablePrimaryOutputDevices().contains(devDesc) &&
555 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 bool isA2dp = audio_is_a2dp_out_device(device);
557 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
558 : String8(AudioParameter::keyReconfigLeSupported);
559 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100561 int isReconfigSupported;
562 repliedParameters.getInt(supportKey, isReconfigSupported);
563 if (isReconfigSupported) {
564 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
565 : String8(AudioParameter::keyReconfigLe);
566 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 param.add(key, String8("true"));
568 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
569 devDesc->setEncodedFormat(encodedFormat);
570 return NO_ERROR;
571 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700572 }
573 }
cnx421bd2dcc42020-07-11 14:58:44 +0800574 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000575 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800576 for (size_t i = 0; i < mOutputs.size(); i++) {
577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000578 // mute media strategies to avoid sending the music tail into
579 // the earpiece or headset.
580 if (desc->isStrategyActive(musicStrategy)) {
581 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
582 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
583 tempRecommendedMuteDuration : desc->latency() * 4;
584 if (muteWaitMs < tempMuteDurationMs) {
585 muteWaitMs = tempMuteDurationMs;
586 }
587 }
cnx421bd2dcc42020-07-11 14:58:44 +0800588 setStrategyMute(musicStrategy, true, desc);
589 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
590 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
591 nullptr, true /*fromCache*/).types());
592 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
594 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
595 // happens after the actual device switch.
596 if (muteWaitMs > 0) {
597 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
598 usleep(muteWaitMs * 1000);
599 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800600 // Toggle the device state: UNAVAILABLE -> AVAILABLE
601 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100602 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800604 device_address, device_name,
605 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
608 status);
609 return status;
610 }
611
612 status = setDeviceConnectionState(device,
613 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800614 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800615 if (status != NO_ERROR) {
616 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
617 status);
618 return status;
619 }
620
621 return NO_ERROR;
622}
623
Pattydd807582021-11-04 21:01:03 +0800624status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
625 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626{
Pattydd807582021-11-04 21:01:03 +0800627 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 std::unordered_set<audio_format_t> formatSet;
630 sp<HwModule> primaryModule =
631 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700632 if (primaryModule == nullptr) {
633 ALOGE("%s() unable to get primary module", __func__);
634 return NO_INIT;
635 }
Pattydd807582021-11-04 21:01:03 +0800636
637 DeviceTypeSet audioDeviceSet;
638
639 switch(device) {
640 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
641 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
642 break;
643 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800644 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
645 break;
646 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
647 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800648 break;
649 default:
650 ALOGE("%s() device type 0x%08x not supported", __func__, device);
651 return BAD_VALUE;
652 }
653
jiabin9a3361e2019-10-01 09:38:30 -0700654 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800655 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800656 for (const auto& device : declaredDevices) {
657 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800658 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800659 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800660 return status;
661}
662
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
664{
665 DeviceVector rxSinkdevices{};
666 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
667 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
668 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
669 auto rxSinkDevice = rxSinkdevices.itemAt(0);
670 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
671 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
672 // retrieve Rx Source device descriptor
673 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
674 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
675
676 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
677 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
678 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
679 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
680 return DeviceVector(rxSinkDevice);
681 }
682 }
683 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
684 // the device returned is not necessarily reachable via this output
685 // (filter later by setOutputDevices())
686 return getNewOutputDevices(mPrimaryOutput, fromCache);
687}
688
689status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
690{
François Gaffiedb1755b2023-09-01 11:50:35 +0200691 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
693 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
694 }
695 return INVALID_OPERATION;
696}
697
698status_t AudioPolicyManager::updateCallRoutingInternal(
699 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700700{
701 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100702 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700703 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200704 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700705 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100706 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 }
François Gaffie11d30102018-11-02 16:09:09 +0100708
Francois Gaffie716e1432019-01-14 16:58:59 +0100709 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100710 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200711
Eric Laurentb2fb4102024-06-21 12:25:26 +0000712 if (!fix_call_audio_patch()) {
713 disconnectTelephonyAudioSource(mCallRxSourceClient);
714 disconnectTelephonyAudioSource(mCallTxSourceClient);
715 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200716
717 if (rxDevices.isEmpty()) {
718 ALOGW("%s() no selected output device", __func__);
719 return INVALID_OPERATION;
720 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000721 if (txSourceDevice == nullptr) {
722 ALOGE("%s() selected input device not available", __func__);
723 return INVALID_OPERATION;
724 }
François Gaffiec005e562018-11-06 15:04:49 +0100725
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100726 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100727 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728
François Gaffie9eb18552018-11-05 10:33:26 +0100729 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700730 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100731 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700732 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100733 // retrieve Rx Source and Tx Sink device descriptors
734 sp<DeviceDescriptor> rxSourceDevice =
735 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738 sp<DeviceDescriptor> txSinkDevice =
739 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
740 String8(),
741 AUDIO_FORMAT_DEFAULT);
742
743 // RX and TX Telephony device are declared by Primary Audio HAL
744 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
745 (telephonyRxModule->getHalVersionMajor() >= 3)) {
746 if (rxSourceDevice == 0 || txSinkDevice == 0) {
747 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100748 ALOGE("%s() no telephony Tx and/or RX device", __func__);
749 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100751 // createAudioPatchInternal now supports both HW / SW bridging
752 createRxPatch = true;
753 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100754 } else {
755 // If the RX device is on the primary HW module, then use legacy routing method for
756 // voice calls via setOutputDevice() on primary output.
757 // Otherwise, create two audio patches for TX and RX path.
758 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
759 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 // If the TX device is also on the primary HW module, setOutputDevice() will take care
761 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100762 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
763 (txSinkDevice != 0);
764 }
765 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
766 // Otherwise, create two audio patches for TX and RX path.
767 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000768 if (fix_call_audio_patch()) {
769 disconnectTelephonyAudioSource(mCallRxSourceClient);
770 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200771 if (!hasPrimaryOutput()) {
772 ALOGW("%s() no primary output available", __func__);
773 return INVALID_OPERATION;
774 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530775 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000777 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800778 // If the TX device is on the primary HW module but RX device is
779 // on other HW module, SinkMetaData of telephony input should handle it
780 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700782 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100783 // terminate active capture if on the same HW module as the call TX source device
784 // FIXME: would be better to refine to only inputs whose profile connects to the
785 // call TX device but this information is not in the audio patch and logic here must be
786 // symmetric to the one in startInput()
787 for (const auto& activeDesc : mInputs.getActiveInputs()) {
788 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
789 closeActiveClients(activeDesc);
790 }
791 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200792 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000793 } else if (fix_call_audio_patch()) {
794 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800795 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100796 if (waitMs != nullptr) {
797 *waitMs = muteWaitMs;
798 }
799 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800800}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700801
Mikhail Naganov100f0122018-11-29 11:22:16 -0800802bool AudioPolicyManager::isDeviceOfModule(
803 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
804 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
805 if (module != 0) {
806 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
807 .indexOf(devDesc) != NAME_NOT_FOUND
808 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
809 .indexOf(devDesc) != NAME_NOT_FOUND;
810 }
811 return false;
812}
813
David Lif85c5e32024-07-01 13:14:10 +0000814void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200815{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000816 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
817
818 if (fix_call_audio_patch()) {
819 if (mCallRxSourceClient != nullptr) {
820 DeviceVector rxDevices =
821 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
822 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
823 "connectTelephonyRxAudioSource(): no device found for call RX source");
824 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
825 if (mCallRxSourceClient->isConnected()
826 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
827 return;
828 }
829 disconnectTelephonyAudioSource(mCallRxSourceClient);
830 }
831 } else {
832 disconnectTelephonyAudioSource(mCallRxSourceClient);
833 }
834
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835 const struct audio_port_config source = {
836 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
837 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
838 };
Eric Laurent541a2002024-01-15 18:11:42 +0100839 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000840
Eric Laurentccbd7872024-06-20 12:34:15 +0000841 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000842 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
844 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000845 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
846 mCallRxSourceClient->srcDevice()->toString().c_str(),
847 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200848 ALOGE_IF(mCallRxSourceClient == nullptr,
849 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200850}
851
Francois Gaffie601801d2021-06-22 13:27:39 +0200852void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853{
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 if (clientDesc == nullptr) {
855 return;
856 }
857 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
858 "%s error stopping audio source", __func__);
859 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200860}
861
862void AudioPolicyManager::connectTelephonyTxAudioSource(
863 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
864 uint32_t delayMs)
865{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200866 if (srcDevice == nullptr || sinkDevice == nullptr) {
867 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
868 return;
869 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000870
871 if (fix_call_audio_patch()) {
872 if (mCallTxSourceClient != nullptr) {
873 if (mCallTxSourceClient->isConnected()
874 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
875 return;
876 }
877 disconnectTelephonyAudioSource(mCallTxSourceClient);
878 }
879 } else {
880 disconnectTelephonyAudioSource(mCallTxSourceClient);
881 }
882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200883 PatchBuilder patchBuilder;
884 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000885
Francois Gaffie601801d2021-06-22 13:27:39 +0200886 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200887 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
888
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200889 struct audio_port_config source = {};
890 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient = new SourceClientDescriptor(
892 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000893 mCommunnicationStrategy, toVolumeSource(aa), true,
894 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100895 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
896
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
898 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
900 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000902 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
903 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200904 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200905 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200906 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200907}
908
Eric Laurente0720872014-03-11 09:30:41 -0700909void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700910{
911 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100912 // store previous phone state for management of sonification strategy below
913 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100914 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100915
916 if (mEngine->setPhoneState(state) != NO_ERROR) {
917 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700918 return;
919 }
François Gaffie2110e042015-03-24 08:41:51 +0100920 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700921 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700922 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700923 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800924 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
926
François Gaffie2110e042015-03-24 08:41:51 +0100927 /**
928 * Switching to or from incall state or switching between telephony and VoIP lead to force
929 * routing command.
930 */
Eric Laurent74b71512019-11-06 17:21:57 -0800931 bool force = ((isStateInCall(oldState) != isStateInCall(state))
932 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700933
934 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700935 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 int delayMs = 0;
938 if (isStateInCall(state)) {
939 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100940 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
941 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700942 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700943 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700944 // mute media and sonification strategies and delay device switch by the largest
945 // latency of any output where either strategy is active.
946 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100947 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
948 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
949 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700950 (delayMs < (int)desc->latency()*2)) {
951 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffiec005e562018-11-06 15:04:49 +0100953 setStrategyMute(musicStrategy, true, desc);
954 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
956 nullptr, true /*fromCache*/).types());
957 setStrategyMute(sonificationStrategy, true, desc);
958 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
959 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
960 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962 }
963
François Gaffiedb1755b2023-09-01 11:50:35 +0200964 if (state == AUDIO_MODE_IN_CALL) {
965 (void)updateCallRouting(false /*fromCache*/, delayMs);
966 } else {
967 if (oldState == AUDIO_MODE_IN_CALL) {
968 disconnectTelephonyAudioSource(mCallRxSourceClient);
969 disconnectTelephonyAudioSource(mCallTxSourceClient);
970 }
971 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100972 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
973 // force routing command to audio hardware when ending call
974 // even if no device change is needed
975 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
976 rxDevices = mPrimaryOutput->devices();
977 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530978 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700979 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700980 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700981
jiabin3ff8d7d2022-12-13 06:27:44 +0000982 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700983 // reevaluate routing on all outputs in case tracks have been started during the call
984 for (size_t i = 0; i < mOutputs.size(); i++) {
985 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100986 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000987 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
988 && desc->mPreferredAttrInfo != nullptr) {
989 // If the output is using preferred mixer attributes and the audio mode is not normal,
990 // the output need to reopen with default configuration.
991 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
992 continue;
993 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200994 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
995 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200997 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700998 }
999 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001
Eric Laurent96d1dda2022-03-14 17:14:19 +01001002 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1003
Eric Laurente552edb2014-03-10 17:42:56 -07001004 if (isStateInCall(state)) {
1005 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001006 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001007 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001008 }
1009
1010 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001011 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1012 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001013}
1014
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001015audio_mode_t AudioPolicyManager::getPhoneState() {
1016 return mEngine->getPhoneState();
1017}
1018
Eric Laurente0720872014-03-11 09:30:41 -07001019void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001020 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001021{
François Gaffie2110e042015-03-24 08:41:51 +01001022 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001023 if (config == mEngine->getForceUse(usage)) {
1024 return;
1025 }
Eric Laurente552edb2014-03-10 17:42:56 -07001026
François Gaffie2110e042015-03-24 08:41:51 +01001027 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1028 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1029 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
François Gaffie2110e042015-03-24 08:41:51 +01001031 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1032 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1033 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001036 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001037
Eric Laurent22fcda22019-05-17 16:28:47 -07001038 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1039 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001040 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001041 }
1042
Eric Laurentdc462862016-07-19 12:29:53 -07001043 //FIXME: workaround for truncated touch sounds
1044 // to be removed when the problem is handled by system UI
1045 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001046 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1047 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1048 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001049
1050 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001051 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001052}
1053
Eric Laurente0720872014-03-11 09:30:41 -07001054void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001055{
1056 ALOGV("setSystemProperty() property %s, value %s", property, value);
1057}
1058
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059// Find an MSD output profile compatible with the parameters passed.
1060// When "directOnly" is set, restrict search to profiles for direct outputs.
1061sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1062 const DeviceVector& devices,
1063 uint32_t samplingRate,
1064 audio_format_t format,
1065 audio_channel_mask_t channelMask,
1066 audio_output_flags_t flags,
1067 bool directOnly)
1068{
1069 flags = getRelevantFlags(flags, directOnly);
1070
1071 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1072 if (msdModule != nullptr) {
1073 // for the msd module check if there are patches to the output devices
1074 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1075 HwModuleCollection modules;
1076 modules.add(msdModule);
1077 return searchCompatibleProfileHwModules(
1078 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1079 flags, directOnly);
1080 }
1081 }
1082 return nullptr;
1083}
1084
Michael Chana94fbb22018-04-24 14:31:19 +10001085// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1086// search to profiles for direct outputs.
1087sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001088 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001089 uint32_t samplingRate,
1090 audio_format_t format,
1091 audio_channel_mask_t channelMask,
1092 audio_output_flags_t flags,
1093 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001094{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001095 flags = getRelevantFlags(flags, directOnly);
1096
1097 return searchCompatibleProfileHwModules(
1098 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1099}
1100
1101audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1102 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001103 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 // only retain flags that will drive the direct output profile selection
1105 // if explicitly requested
1106 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001107 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1109 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001110 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001111 return flags;
1112}
Eric Laurent861a6282015-05-18 15:40:16 -07001113
Dorin Drimusecc9f422022-03-09 17:57:40 +01001114sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1115 const HwModuleCollection& hwModules,
1116 const DeviceVector& devices,
1117 uint32_t samplingRate,
1118 audio_format_t format,
1119 audio_channel_mask_t channelMask,
1120 audio_output_flags_t flags,
1121 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001122 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001123 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001124 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001125 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 samplingRate, NULL /*updatedSamplingRate*/,
1127 format, NULL /*updatedFormat*/,
1128 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001129 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001130 continue;
1131 }
1132 // reject profiles not corresponding to a device currently available
1133 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1134 continue;
1135 }
1136 // reject profiles if connected device does not support codec
1137 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1138 continue;
1139 }
1140 if (!directOnly) {
1141 return curProfile;
1142 }
1143
1144 // when searching for direct outputs, if several profiles are compatible, give priority
1145 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001146 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001147 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001148 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001149 }
1150 profile = curProfile;
1151 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1152 break;
1153 }
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155 }
Eric Laurent861a6282015-05-18 15:40:16 -07001156 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001157}
1158
Eric Laurentfa0f6742021-08-17 18:39:44 +02001159sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001160 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161{
1162 for (const auto& hwModule : mHwModules) {
1163 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001164 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001165 continue;
1166 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001167 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001168 // reject profiles not corresponding to a device currently available
1169 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1170 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1171 continue;
1172 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001173 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1174 != devices.size()) {
1175 continue;
1176 }
1177 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001178 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1179 return curProfile;
1180 }
1181 }
1182 return nullptr;
1183}
1184
Eric Laurentf4e63452017-11-06 19:31:46 +00001185audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
François Gaffiec005e562018-11-06 15:04:49 +01001187 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001188
1189 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1190 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1191 // format, flags, etc. This may result in some discrepancy for functions that utilize
1192 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1193 // and AudioSystem::getOutputSamplingRate().
1194
François Gaffie11d30102018-11-02 16:09:09 +01001195 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001196 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1197 if (stream == AUDIO_STREAM_MUSIC &&
1198 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1199 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1200 }
1201 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001202
François Gaffie11d30102018-11-02 16:09:09 +01001203 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1204 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001205 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001206}
1207
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1209 const audio_attributes_t *srcAttr,
1210 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001211{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001212 if (srcAttr != NULL) {
1213 if (!isValidAttributes(srcAttr)) {
1214 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1215 __func__,
1216 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1217 srcAttr->tags);
1218 return BAD_VALUE;
1219 }
1220 *dstAttr = *srcAttr;
1221 } else {
1222 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1223 ALOGE("%s: invalid stream type", __func__);
1224 return BAD_VALUE;
1225 }
François Gaffiec005e562018-11-06 15:04:49 +01001226 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001228
1229 // Only honor audibility enforced when required. The client will be
1230 // forced to reconnect if the forced usage changes.
1231 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001232 dstAttr->flags = static_cast<audio_flags_mask_t>(
1233 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001234 }
1235
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001236 return NO_ERROR;
1237}
1238
Kevin Rocard153f92d2018-12-18 18:33:28 -08001239status_t AudioPolicyManager::getOutputForAttrInt(
1240 audio_attributes_t *resultAttr,
1241 audio_io_handle_t *output,
1242 audio_session_t session,
1243 const audio_attributes_t *attr,
1244 audio_stream_type_t *stream,
1245 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001246 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001247 audio_output_flags_t *flags,
1248 audio_port_handle_t *selectedDeviceId,
1249 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001251 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001252 bool *isSpatialized,
1253 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001254{
François Gaffiec005e562018-11-06 15:04:49 +01001255 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001256 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001257 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001258 const sp<DeviceDescriptor> requestedDevice =
1259 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1260
Eric Laurent8a1095a2019-11-08 14:44:16 -08001261 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001262 *isSpatialized = false;
1263
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001264 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1265 if (status != NO_ERROR) {
1266 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001267 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001268 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001269 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001270 }
François Gaffiec005e562018-11-06 15:04:49 +01001271 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001272
François Gaffiec005e562018-11-06 15:04:49 +01001273 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1274 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001275
Oscar Azucena873d10f2023-01-12 18:34:42 -08001276 bool usePrimaryOutputFromPolicyMixes = false;
1277
Kevin Rocard153f92d2018-12-18 18:33:28 -08001278 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1279 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1280 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001282 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1283 .channel_mask = config->channel_mask,
1284 .format = config->format,
1285 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001286 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001287 mAvailableOutputDevices, requestedDevice, primaryMix,
1288 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001289 if (status != OK) {
1290 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001291 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001292
Kevin Rocard153f92d2018-12-18 18:33:28 -08001293 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001294 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1295 && !audio_is_linear_pcm(config->format)) {
1296 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001297 return BAD_VALUE;
1298 }
1299 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001300 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001301 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1302 primaryMix->mDeviceAddress,
1303 AUDIO_FORMAT_DEFAULT);
1304 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001305 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001306 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1307 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001308 // if a direct output can be opened to deliver the track's multi-channel content to the
1309 // output rather than being downmixed by the primary output, then use this direct
1310 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1311 // mix.
1312 bool tryDirectForChannelMask = policyDesc != nullptr
1313 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1314 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001315 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001316 audio_io_handle_t newOutput;
1317 status = openDirectOutput(
1318 *stream, session, config,
1319 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001320 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001321 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001322 policyDesc = mOutputs.valueFor(newOutput);
1323 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001324 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001325 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001326 policyDesc = nullptr;
1327 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001328 }
1329 if (policyDesc != nullptr) {
1330 policyDesc->mPolicyMix = primaryMix;
1331 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001332 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1333 : AUDIO_PORT_HANDLE_NONE;
1334 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1335 // Remove direct flag as it is not on a direct output.
1336 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1337 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001338
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001339 ALOGV("getOutputForAttr() returns output %d", *output);
1340 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1341 *outputType = API_OUT_MIX_PLAYBACK;
1342 } else {
1343 *outputType = API_OUTPUT_LEGACY;
1344 }
1345 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001346 } else {
1347 if (policyMixDevice != nullptr) {
1348 ALOGE("%s, try to use primary mix but no output found", __func__);
1349 return INVALID_OPERATION;
1350 }
1351 // Fallback to default engine selection as the selected primary mix device is not
1352 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001353 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001354 }
François Gaffiec005e562018-11-06 15:04:49 +01001355 // Virtual sources must always be dynamicaly or explicitly routed
1356 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1357 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1358 return BAD_VALUE;
1359 }
1360 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1361 // in order to let the choice of the order to future vendor engine
1362 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001363
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001365 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001366 }
1367
Nadav Barb2f18162018-07-18 13:01:53 +03001368 // Set incall music only if device was explicitly set, and fallback to the device which is
1369 // chosen by the engine if not.
1370 // FIXME: provide a more generic approach which is not device specific and move this back
1371 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001372 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001373 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001374 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001375 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001376 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001377 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001378 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001379 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001380 }
1381 }
1382
François Gaffiec005e562018-11-06 15:04:49 +01001383 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1384 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1385 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001386
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001388 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001389 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001390 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001391 ALOGV("%s() Using MSD devices %s instead of devices %s",
1392 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001393 } else {
1394 *output = AUDIO_IO_HANDLE_NONE;
1395 }
1396 }
1397 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001398 sp<PreferredMixerAttributesInfo> info = nullptr;
1399 if (outputDevices.size() == 1) {
1400 info = getPreferredMixerAttributesInfo(
1401 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001402 mEngine->getProductStrategyForAttributes(*resultAttr),
1403 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001404 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1405 // and it is currently active.
1406 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001407 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001408 info = nullptr;
1409 }
jiabin220eea12024-05-17 17:55:20 +00001410 if (com::android::media::audioserver::
1411 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1412 if (info != nullptr && info->getUid() == uid &&
1413 info->configMatches(*config) &&
1414 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1415 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1416 [this, &outputDevices](audio_usage_t usage) {
1417 return mOutputs.isUsageActiveOnDevice(
1418 usage, outputDevices[0]); }))) {
1419 // Bit-perfect request is not allowed when the phone mode is not normal or
1420 // there is any higher priority user case active.
1421 return INVALID_OPERATION;
1422 }
1423 }
jiabina84c3d32022-12-02 18:59:55 +00001424 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001425 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001426 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001427 // The client will be active if the client is currently preferred mixer owner and the
1428 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001429 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001430 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001431 && info->getUid() == uid
1432 && *output != AUDIO_IO_HANDLE_NONE
1433 // When bit-perfect output is selected for the preferred mixer attributes owner,
1434 // only need to consider the config matches.
1435 && mOutputs.valueFor(*output)->isConfigurationMatched(
1436 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001437
1438 if (*isBitPerfect) {
1439 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1440 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001442 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001443 AudioProfileVector profiles;
1444 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1445 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001446 const auto channels = profiles[0]->getChannels();
1447 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1448 config->channel_mask = *channels.begin();
1449 }
1450 const auto sampleRates = profiles[0]->getSampleRates();
1451 if (!sampleRates.empty() &&
1452 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1453 config->sample_rate = *sampleRates.begin();
1454 }
jiabinf1c73972022-04-14 16:28:52 -07001455 config->format = profiles[0]->getFormat();
1456 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001457 return INVALID_OPERATION;
1458 }
Paul McLeanaa981192015-03-21 09:55:15 -07001459
François Gaffiec005e562018-11-06 15:04:49 +01001460 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001461 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001462 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001463 *selectedDeviceId = outputDevice->getId();
1464 break;
1465 }
1466 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001467
Eric Laurent8a1095a2019-11-08 14:44:16 -08001468 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1469 *outputType = API_OUTPUT_TELEPHONY_TX;
1470 } else {
1471 *outputType = API_OUTPUT_LEGACY;
1472 }
1473
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001474 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1475
1476 return NO_ERROR;
1477}
1478
1479status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1480 audio_io_handle_t *output,
1481 audio_session_t session,
1482 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001483 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001484 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001485 audio_output_flags_t *flags,
1486 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001487 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001488 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001489 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001490 bool *isSpatialized,
1491 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001492{
1493 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1494 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1495 return INVALID_OPERATION;
1496 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001497 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001498 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001499 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001500 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001501 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001502 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001503 const sp<DeviceDescriptor> requestedDevice =
1504 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1505
1506 // Prevent from storing invalid requested device id in clients
1507 const audio_port_handle_t sanitizedRequestedPortId =
1508 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1509 *selectedDeviceId = sanitizedRequestedPortId;
1510
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001512 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001513 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1514 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001515 if (status != NO_ERROR) {
1516 return status;
1517 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001518 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001519 if (secondaryOutputs != nullptr) {
1520 for (auto &secondaryMix : secondaryMixes) {
1521 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1522 if (outputDesc != nullptr &&
1523 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1524 secondaryOutputs->push_back(outputDesc->mIoHandle);
1525 weakSecondaryOutputDescs.push_back(outputDesc);
1526 }
1527 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001528 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001529
Eric Laurent8fc147b2018-07-22 19:13:55 -07001530 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001531 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001532 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001533 };
jiabin4ef93452019-09-10 14:29:54 -07001534 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001535
Eric Laurentc209fe42020-06-05 18:11:23 -07001536 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001537 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001538 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001539 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001540 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001541 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001542 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001543 std::move(weakSecondaryOutputDescs),
1544 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001545 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001546
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001547 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1548 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001549
Eric Laurente83b55d2014-11-14 10:06:21 -08001550 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001551}
1552
Eric Laurentc529cf62020-04-17 18:19:10 -07001553status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1554 audio_session_t session,
1555 const audio_config_t *config,
1556 audio_output_flags_t flags,
1557 const DeviceVector &devices,
1558 audio_io_handle_t *output) {
1559
1560 *output = AUDIO_IO_HANDLE_NONE;
1561
1562 // skip direct output selection if the request can obviously be attached to a mixed output
1563 // and not explicitly requested
1564 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1565 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1566 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1567 return NAME_NOT_FOUND;
1568 }
1569
1570 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1571 // This prevents creating an offloaded track and tearing it down immediately after start
1572 // when audioflinger detects there is an active non offloadable effect.
1573 // FIXME: We should check the audio session here but we do not have it in this context.
1574 // This may prevent offloading in rare situations where effects are left active by apps
1575 // in the background.
1576 sp<IOProfile> profile;
1577 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1578 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1579 profile = getProfileForOutput(
1580 devices, config->sample_rate, config->format, config->channel_mask,
1581 flags, true /* directOnly */);
1582 }
1583
1584 if (profile == nullptr) {
1585 return NAME_NOT_FOUND;
1586 }
1587
1588 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1589 for (size_t i = 0; i < mOutputs.size(); i++) {
1590 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1591 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1592 // reuse direct output if currently open by the same client
1593 // and configured with same parameters
1594 if ((config->sample_rate == desc->getSamplingRate()) &&
1595 (config->format == desc->getFormat()) &&
1596 (config->channel_mask == desc->getChannelMask()) &&
1597 (session == desc->mDirectClientSession)) {
1598 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301599 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001600 mOutputs.keyAt(i), session);
1601 *output = mOutputs.keyAt(i);
1602 return NO_ERROR;
1603 }
1604 }
1605 }
1606
1607 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001608 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301609 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1610 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001611 return NAME_NOT_FOUND;
1612 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1613 // MMAP gracefully handles lack of an exclusive track resource by mixing
1614 // above the audio framework. For AAudio to know that the limit is reached,
1615 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301616 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1617 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001618 return NAME_NOT_FOUND;
1619 } else {
1620 // Close outputs on this profile, if available, to free resources for this request
1621 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1622 const auto desc = mOutputs.valueAt(i);
1623 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301624 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1625 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001626 closeOutput(desc->mIoHandle);
1627 }
1628 }
1629 }
1630 }
1631
1632 // Unable to close streams to find free resources for this request
1633 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301634 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1635 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001636 return NAME_NOT_FOUND;
1637 }
1638
Atneya Nairb16666a2023-12-11 20:18:33 -08001639 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001640
Michael Chan6fb34492020-12-08 15:44:49 +11001641 // An MSD patch may be using the only output stream that can service this request. Release
1642 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001643 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001644
Eric Laurentf1f22e72021-07-13 14:04:14 +02001645 status_t status =
1646 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001647
1648 // only accept an output with the requested parameters
1649 if (status != NO_ERROR ||
1650 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1651 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1652 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1653 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1654 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1655 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1656 config->channel_mask, outputDesc->getChannelMask());
1657 if (*output != AUDIO_IO_HANDLE_NONE) {
1658 outputDesc->close();
1659 }
1660 // fall back to mixer output if possible when the direct output could not be open
1661 if (audio_is_linear_pcm(config->format) &&
1662 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1663 return NAME_NOT_FOUND;
1664 }
1665 *output = AUDIO_IO_HANDLE_NONE;
1666 return BAD_VALUE;
1667 }
1668 outputDesc->mDirectOpenCount = 1;
1669 outputDesc->mDirectClientSession = session;
1670
1671 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001672 setOutputDevices(__func__, outputDesc,
1673 devices,
1674 true,
1675 0,
1676 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001677 mPreviousOutputs = mOutputs;
1678 ALOGV("%s returns new direct output %d", __func__, *output);
1679 mpClientInterface->onAudioPortListUpdate();
1680 return NO_ERROR;
1681}
1682
François Gaffie11d30102018-11-02 16:09:09 +01001683audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1684 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001685 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001686 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001687 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001688 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001689 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001690 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001691 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001692{
Andy Hungc88b0642018-04-27 15:42:35 -07001693 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001694
jiabine375d412019-02-26 12:54:53 -08001695 // Discard haptic channel mask when forcing muting haptic channels.
1696 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001697 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1698 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001699
Eric Laurente552edb2014-03-10 17:42:56 -07001700 // open a direct output if required by specified parameters
1701 //force direct flag if offload flag is set: offloading implies a direct output stream
1702 // and all common behaviors are driven by checking only the direct flag
1703 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001704 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1705 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001706 }
Nadav Bar766fb022018-01-07 12:18:03 +02001707 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1708 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001709 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001710
1711 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1712
Eric Laurente83b55d2014-11-14 10:06:21 -08001713 // only allow deep buffering for music stream type
1714 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001715 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001716 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001717 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001718 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1719 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001720 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001721 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001722 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001723 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001724 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001725 audio_is_linear_pcm(config->format) &&
1726 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001727 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001728 AUDIO_OUTPUT_FLAG_DIRECT);
1729 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001730 }
Eric Laurente552edb2014-03-10 17:42:56 -07001731
Carter Hsua3abb402021-10-26 11:11:20 +08001732 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1733 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1734 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1735 }
1736
Eric Laurentf9230d52024-01-26 18:49:09 +01001737 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001738 // was specified and offload or direct playback is not explicitly requested, and there is no
1739 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001740 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001741 if (mSpatializerOutput != nullptr &&
1742 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1743 prefMixerConfigInfo == nullptr &&
1744 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1745 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001746 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001747 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001748 }
1749
Eric Laurentc529cf62020-04-17 18:19:10 -07001750 audio_config_t directConfig = *config;
1751 directConfig.channel_mask = channelMask;
1752 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1753 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001754 return output;
1755 }
1756
Eric Laurent14cbfca2016-03-17 09:42:16 -07001757 // A request for HW A/V sync cannot fallback to a mixed output because time
1758 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001759 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001760 return AUDIO_IO_HANDLE_NONE;
1761 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001762 // A request for Tuner cannot fallback to a mixed output
1763 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1764 return AUDIO_IO_HANDLE_NONE;
1765 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001766
Eric Laurente552edb2014-03-10 17:42:56 -07001767 // ignoring channel mask due to downmix capability in mixer
1768
1769 // open a non direct output
1770
1771 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001772 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001773 // get which output is suitable for the specified stream. The actual
1774 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001775 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001776 if (prefMixerConfigInfo != nullptr) {
1777 for (audio_io_handle_t outputHandle : outputs) {
1778 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1779 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1780 output = outputHandle;
1781 break;
1782 }
1783 }
1784 if (output == AUDIO_IO_HANDLE_NONE) {
1785 // No output open with the preferred profile. Open a new one.
1786 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1787 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1788 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1789 config.format = prefMixerConfigInfo->getConfigBase().format;
1790 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1791 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1792 &config, prefMixerConfigInfo->getFlags());
1793 if (preferredOutput == nullptr) {
1794 ALOGE("%s failed to open output with preferred mixer config", __func__);
1795 } else {
1796 output = preferredOutput->mIoHandle;
1797 }
1798 }
1799 } else {
1800 // at this stage we should ignore the DIRECT flag as no direct output could be
1801 // found earlier
1802 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001803 if (com::android::media::audioserver::
1804 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1805 // If the preferred mixer attributes is null, do not select the bit-perfect output
1806 // unless the bit-perfect output is the only output.
1807 // The bit-perfect output can exist while the passed in preferred mixer attributes
1808 // info is null when it is a high priority client. The high priority clients are
1809 // ringtone or alarm, which is not a bit-perfect use case.
1810 size_t i = 0;
1811 while (i < outputs.size() && outputs.size() > 1) {
1812 auto desc = mOutputs.valueFor(outputs[i]);
1813 // The output descriptor must not be null here.
1814 if (desc->isBitPerfect()) {
1815 outputs.removeItemsAt(i);
1816 } else {
1817 i += 1;
1818 }
1819 }
1820 }
jiabina84c3d32022-12-02 18:59:55 +00001821 output = selectOutput(
1822 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1823 }
Eric Laurente552edb2014-03-10 17:42:56 -07001824 }
François Gaffie11d30102018-11-02 16:09:09 +01001825 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001826 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001827 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001828
Eric Laurente552edb2014-03-10 17:42:56 -07001829 return output;
1830}
1831
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001832sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001833 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1834 mAvailableInputDevices);
1835 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1836}
1837
1838DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1839 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1840 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001841}
1842
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001845 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1846 if (msdModule != 0) {
1847 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1848 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1849 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1850 const struct audio_port_config *source = &patch->mPatch.sources[j];
1851 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1852 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001853 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001854 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 }
1856 }
1857 }
1858 return msdPatches;
1859}
1860
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001861bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1862 ssize_t index = mAudioPatches.indexOfKey(handle);
1863 if (index < 0) {
1864 return false;
1865 }
1866 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1867 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1868 if (msdModule == nullptr) {
1869 return false;
1870 }
1871 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1872 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1873 return true;
1874 }
1875 index = getMsdOutputPatches().indexOfKey(handle);
1876 if (index < 0) {
1877 return false;
1878 }
1879 return true;
1880}
1881
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1883 const InputProfileCollection &inputProfiles,
1884 const OutputProfileCollection &outputProfiles,
1885 const sp<DeviceDescriptor> &sourceDevice,
1886 const sp<DeviceDescriptor> &sinkDevice,
1887 AudioProfileVector& sourceProfiles,
1888 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001891 return NO_INIT;
1892 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001893 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001894 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 return NO_INIT;
1896 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001897 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001898 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1899 inProfile->supportsDevice(sourceDevice)) {
1900 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 }
1902 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001904 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001905 outProfile->supportsDevice(sinkDevice)) {
1906 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 }
1908 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909 return NO_ERROR;
1910}
1911
1912status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1913 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1914 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1915{
Dean Wheatley16809da2022-12-09 14:55:46 +11001916 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1917 static const std::vector<audio_format_t> formatsOrder = {{
1918 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001919 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1920 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001921 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1922 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1923 // preferred).
1924 std::vector<audio_channel_mask_t> masks = {{
1925 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1926 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1927 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1928 // insert index masks (higher counts most preferred) as preferred over position masks
1929 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1930 masks.insert(
1931 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1932 }
1933 return masks;
1934 }();
1935
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001936 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001937 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1938 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001939 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1941 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001942 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 }
1944 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1945 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1946 sinkConfig->format = bestSinkConfig.format;
1947 // For encoded streams force direct flag to prevent downstream mixing.
1948 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1949 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001950 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1951 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001952 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001953 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1954 // raw and IEC61937 framed streams.
1955 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1956 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1957 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001958 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1959 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001960 sourceConfig->channel_mask =
1961 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1962 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1963 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 sourceConfig->format = bestSinkConfig.format;
1965 // Copy input stream directly without any processing (e.g. resampling).
1966 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1967 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1968 if (hwAvSync) {
1969 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1970 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1971 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1972 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1973 }
1974 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1975 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1976 sinkConfig->config_mask |= config_mask;
1977 sourceConfig->config_mask |= config_mask;
1978 return NO_ERROR;
1979}
1980
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001981PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1982 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001983{
1984 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001985 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1986 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1987 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1988 if (deviceModule == nullptr) {
1989 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1990 return patchBuilder;
1991 }
1992 const InputProfileCollection inputProfiles = msdIsSource ?
1993 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1994 const OutputProfileCollection outputProfiles = msdIsSource ?
1995 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1996
1997 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1998 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1999 device : getMsdAudioOutDevices().itemAt(0);
2000 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2001
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002002 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2003 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002004 AudioProfileVector sourceProfiles;
2005 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2007 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002008 for (auto hwAvSync : { true, false }) {
2009 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2010 sourceProfiles, sinkProfiles) != NO_ERROR) {
2011 continue;
2012 }
2013 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2014 &sinkConfig) == NO_ERROR) {
2015 // Found a matching config. Re-create PatchBuilder with this config.
2016 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2017 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002018 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002019 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002020 " supporting PCM format conversion.", __func__);
2021 return patchBuilder;
2022}
2023
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002024status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002025 DeviceVector devices;
2026 if (outputDevices != nullptr && outputDevices->size() > 0) {
2027 devices.add(*outputDevices);
2028 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002029 // Use media strategy for unspecified output device. This should only
2030 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2031 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002032 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002033 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002034 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002035 }
Michael Chan6fb34492020-12-08 15:44:49 +11002036 std::vector<PatchBuilder> patchesToCreate;
2037 for (auto i = 0u; i < devices.size(); ++i) {
2038 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002039 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002040 }
2041 // Retain only the MSD patches associated with outputDevices request.
2042 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002043 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002044 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2045 auto retainedPatch = false;
2046 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2047 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2048 patchesToRemove.removeItemsAt(i);
2049 retainedPatch = true;
2050 break;
2051 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002052 }
Michael Chan6fb34492020-12-08 15:44:49 +11002053 if (retainedPatch) {
2054 it = patchesToCreate.erase(it);
2055 continue;
2056 }
2057 ++it;
2058 }
2059 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2060 return NO_ERROR;
2061 }
2062 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2063 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002064 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002065 }
Michael Chan6fb34492020-12-08 15:44:49 +11002066 status_t status = NO_ERROR;
2067 for (const auto &p : patchesToCreate) {
2068 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2069 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2070 char message[256];
2071 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2072 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2073 currStatus == NO_ERROR ? "Success" : "Error",
2074 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2075 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2076 if (currStatus == NO_ERROR) {
2077 ALOGD("%s", message);
2078 } else {
2079 ALOGE("%s", message);
2080 if (status == NO_ERROR) {
2081 status = currStatus;
2082 }
2083 }
2084 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002085 return status;
2086}
2087
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002088void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2089 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002090 for (size_t i = 0; i < msdPatches.size(); i++) {
2091 const auto& patch = msdPatches[i];
2092 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2093 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2094 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2095 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2096 releaseAudioPatch(patch->getHandle(), mUidCached);
2097 break;
2098 }
2099 }
2100 }
2101}
2102
Dorin Drimus94d94412022-02-02 09:05:02 +01002103bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002104 DeviceVector devicesToCheck =
2105 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002106 AudioPatchCollection msdPatches = getMsdOutputPatches();
2107 for (size_t i = 0; i < msdPatches.size(); i++) {
2108 const auto& patch = msdPatches[i];
2109 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2110 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2111 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2112 const auto& foundDevice = devicesToCheck.getDevice(
2113 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2114 if (foundDevice != nullptr) {
2115 devicesToCheck.remove(foundDevice);
2116 if (devicesToCheck.isEmpty()) {
2117 return true;
2118 }
2119 }
2120 }
2121 }
2122 }
2123 return false;
2124}
2125
Eric Laurente0720872014-03-11 09:30:41 -07002126audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002127 audio_output_flags_t flags,
2128 audio_format_t format,
2129 audio_channel_mask_t channelMask,
2130 uint32_t samplingRate,
2131 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002132{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002133 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2134 "%s called with format %#x", __func__, format);
2135
jiabinebb6af42020-06-09 17:31:17 -07002136 // Return the output that haptic-generating attached to when 1) session id is specified,
2137 // 2) haptic-generating effect exists for given session id and 3) the output that
2138 // haptic-generating effect attached to is in given outputs.
2139 if (sessionId != AUDIO_SESSION_NONE) {
2140 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2141 sessionId, FX_IID_HAPTICGENERATOR);
2142 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2143 return hapticGeneratingOutput;
2144 }
2145 }
2146
Eric Laurent16c66dd2019-05-01 17:54:10 -07002147 // Flags disqualifying an output: the match must happen before calling selectOutput()
2148 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2149 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2150
2151 // Flags expressing a functional request: must be honored in priority over
2152 // other criteria
2153 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2154 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002155 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2156 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002157 // Flags expressing a performance request: have lower priority than serving
2158 // requested sampling rate or channel mask
2159 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2160 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2161 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2162
2163 const audio_output_flags_t functionalFlags =
2164 (audio_output_flags_t)(flags & kFunctionalFlags);
2165 const audio_output_flags_t performanceFlags =
2166 (audio_output_flags_t)(flags & kPerformanceFlags);
2167
2168 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2169
Eric Laurente552edb2014-03-10 17:42:56 -07002170 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002171 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002172 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002173 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002175 // with tiebreak preferring the minimum number of extra functional flags
2176 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002177 // 3: the output supporting the exact channel mask
2178 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002179 // 5: the output with the highest sampling rate if the requested sample rate is
2180 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181 // 6: the output with the highest number of requested performance flags
2182 // 7: the output with the bit depth the closest to the requested one
2183 // 8: the primary output
2184 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002185
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 // matching criteria values in priority order for best matching output so far
2187 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002188
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002189 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2191 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2192 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002193
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002194 for (audio_io_handle_t output : outputs) {
2195 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002196 // matching criteria values in priority order for current output
2197 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002198
Eric Laurent16c66dd2019-05-01 17:54:10 -07002199 if (outputDesc->isDuplicated()) {
2200 continue;
2201 }
2202 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2203 continue;
2204 }
Eric Laurent8838a382014-09-08 16:44:28 -07002205
Eric Laurent16c66dd2019-05-01 17:54:10 -07002206 // If haptic channel is specified, use the haptic output if present.
2207 // When using haptic output, same audio format and sample rate are required.
2208 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002209 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002210 // skip if haptic channel specified but output does not support it, or output support haptic
2211 // but there is no haptic channel requested AND no orphan haptic effect exist
2212 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2213 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002214 continue;
2215 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002216 // In the case of audio-coupled-haptic playback, there is no format conversion and
2217 // resampling in the framework, same format/channel/sampleRate for client and the output
2218 // thread is required. In the case of HapticGenerator effect, do not require format
2219 // matching.
2220 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2221 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002222 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002223 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002224 }
2225
2226 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002227 const int matchingFunctionalFlags =
2228 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2229 const int totalFunctionalFlags =
2230 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2231 // Prefer matching functional flags, but subtract unnecessary functional flags.
2232 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002233
2234 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002235 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2236 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002237 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2238 channelCount <= outputChannelCount) {
2239 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002240 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2241 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002242 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002243 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002244 currentMatchCriteria[3] = outputChannelCount;
2245 }
2246
2247 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002248 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002249 int diff; // avoid unsigned integer overflow.
2250 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2251
2252 // prefer the closest output sampling rate greater than or equal to target
2253 // if none exists, prefer the closest output sampling rate less than target.
2254 //
2255 // criteria is offset to make non-negative.
2256 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002257 }
2258
2259 // performance flags match
2260 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2261
2262 // format match
2263 if (format != AUDIO_FORMAT_INVALID) {
2264 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002265 PolicyAudioPort::kFormatDistanceMax -
2266 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002267 }
2268
2269 // primary output match
2270 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2271
2272 // compare match criteria by priority then value
2273 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2274 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2275 bestMatchCriteria = currentMatchCriteria;
2276 bestOutput = output;
2277
2278 std::stringstream result;
2279 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2280 std::ostream_iterator<int>(result, " "));
2281 ALOGV("%s new bestOutput %d criteria %s",
2282 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002283 }
2284 }
2285
Eric Laurent16c66dd2019-05-01 17:54:10 -07002286 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002287}
2288
Eric Laurent8fc147b2018-07-22 19:13:55 -07002289status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002290{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002291 ALOGV("%s portId %d", __FUNCTION__, portId);
2292
2293 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2294 if (outputDesc == 0) {
2295 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002296 return BAD_VALUE;
2297 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002298 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002299
Eric Laurent8fc147b2018-07-22 19:13:55 -07002300 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002301 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002302
jiabin220eea12024-05-17 17:55:20 +00002303 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2304 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2305 && outputDesc->isBitPerfect()) {
2306 // Usually, APM selects bit-perfect output for high priority use cases only when
2307 // bit-perfect output is the only output that can be routed to the selected device.
2308 // However, here is no need to play high priority use cases such as ringtone and alarm
2309 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2310 // can attach to new output.
2311 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2312 __func__, client->stream());
2313 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2314 return DEAD_OBJECT;
2315 }
2316
Eric Laurent733ce942017-12-07 12:18:25 -08002317 status_t status = outputDesc->start();
2318 if (status != NO_ERROR) {
2319 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002320 }
2321
Eric Laurent97ac8712018-07-27 18:59:02 -07002322 uint32_t delayMs;
2323 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002324
2325 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002326 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002327 if (status == DEAD_OBJECT) {
2328 sp<SwAudioOutputDescriptor> desc =
2329 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2330 if (desc == nullptr) {
2331 // This is not common, it may indicate something wrong with the HAL.
2332 ALOGE("%s unable to open output with default config", __func__);
2333 return status;
2334 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002335 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002336 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002337 }
jiabina84c3d32022-12-02 18:59:55 +00002338
2339 // If the client is the first one active on preferred mixer parameters, reopen the output
2340 // if the current mixer parameters doesn't match the preferred one.
2341 if (outputDesc->devices().size() == 1) {
2342 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2343 outputDesc->devices()[0]->getId(), client->strategy());
2344 if (info != nullptr && info->getUid() == client->uid()) {
2345 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2346 info->getConfigBase(), info->getFlags())) {
2347 stopSource(outputDesc, client);
2348 outputDesc->stop();
2349 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2350 config.channel_mask = info->getConfigBase().channel_mask;
2351 config.sample_rate = info->getConfigBase().sample_rate;
2352 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002353 sp<SwAudioOutputDescriptor> desc =
2354 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2355 if (desc == nullptr) {
2356 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002357 }
jiabin220eea12024-05-17 17:55:20 +00002358 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002359 // Intentionally return error to let the client side resending request for
2360 // creating and starting.
2361 return DEAD_OBJECT;
2362 }
2363 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002364 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002365 // If it is first bit-perfect client, reroute all clients that will be routed to
2366 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2367 PortHandleVector clientsToInvalidate;
2368 for (size_t i = 0; i < mOutputs.size(); i++) {
2369 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002370 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002371 continue;
2372 }
2373 for (const auto& c : mOutputs[i]->getClientIterable()) {
2374 clientsToInvalidate.push_back(c->portId());
2375 }
2376 }
2377 if (!clientsToInvalidate.empty()) {
2378 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2379 __func__);
2380 mpClientInterface->invalidateTracks(clientsToInvalidate);
2381 }
2382 }
jiabina84c3d32022-12-02 18:59:55 +00002383 }
2384 }
2385
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002386 if (client->hasPreferredDevice()) {
2387 // playback activity with preferred device impacts routing occurred, inform upper layers
2388 mpClientInterface->onRoutingUpdated();
2389 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002390 if (delayMs != 0) {
2391 usleep(delayMs * 1000);
2392 }
2393
jiabin220eea12024-05-17 17:55:20 +00002394 if (status == NO_ERROR &&
2395 outputDesc->mPreferredAttrInfo != nullptr &&
2396 outputDesc->isBitPerfect() &&
2397 com::android::media::audioserver::
2398 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2399 // A new client is started on bit-perfect output, update all clients internal mute.
2400 updateClientsInternalMute(outputDesc);
2401 }
2402
Eric Laurentc75307b2015-03-17 15:29:32 -07002403 return status;
2404}
2405
Eric Laurent96d1dda2022-03-14 17:14:19 +01002406bool AudioPolicyManager::isLeUnicastActive() const {
2407 if (isInCall()) {
2408 return true;
2409 }
2410 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2411}
2412
2413bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2414 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2415 return false;
2416 }
2417 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2418 ALOGV("%s active %d", __func__, active);
2419 return active;
2420}
2421
Eric Laurent97ac8712018-07-27 18:59:02 -07002422status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2423 const sp<TrackClientDescriptor>& client,
2424 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002425{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002426 // cannot start playback of STREAM_TTS if any other output is being used
2427 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002428
2429 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002430 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002431 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002432 auto clientStrategy = client->strategy();
2433 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002434 if (stream == AUDIO_STREAM_TTS) {
2435 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002436 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002437 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002438 return INVALID_OPERATION;
2439 } else {
2440 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2441 }
2442 } else {
2443 // some playback other than beacon starts
2444 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2445 }
2446
Eric Laurent77305a62016-07-25 16:39:22 -07002447 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002448 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002449 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002450
François Gaffie11d30102018-11-02 16:09:09 +01002451 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002452 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002453 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002454 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002455 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002456 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002457 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002458 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002459 } else {
2460 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002461 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002462 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2463 AUDIO_FORMAT_DEFAULT);
2464 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2465 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 }
2467
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002468 // requiresMuteCheck is false when we can bypass mute strategy.
2469 // It covers a common case when there is no materially active audio
2470 // and muting would result in unnecessary delay and dropped audio.
2471 const uint32_t outputLatencyMs = outputDesc->latency();
2472 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002473 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002474
Eric Laurente552edb2014-03-10 17:42:56 -07002475 // increment usage count for this stream on the requested output:
2476 // NOTE that the usage count is the same for duplicated output and hardware output which is
2477 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002478 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002479
2480 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002481 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002482 // Preferred device may be exclusive, use only if no other active clients on this output
2483 devices = DeviceVector(
2484 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2485 } else {
2486 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2487 }
François Gaffie11d30102018-11-02 16:09:09 +01002488 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002489 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002490 }
2491 }
Eric Laurente552edb2014-03-10 17:42:56 -07002492
François Gaffiec005e562018-11-06 15:04:49 +01002493 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002494 selectOutputForMusicEffects();
2495 }
2496
François Gaffie1c878552018-11-22 16:53:21 +01002497 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002498 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002499 if (devices.isEmpty()) {
2500 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002501 }
François Gaffiec005e562018-11-06 15:04:49 +01002502 bool shouldWait =
2503 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2504 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2505 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002506 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002507 const bool needToCloseBitPerfectOutput =
2508 (com::android::media::audioserver::
2509 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2510 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2511 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002512 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002513 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002514 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002515 // An output has a shared device if
2516 // - managed by the same hw module
2517 // - supports the currently selected device
2518 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002519 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002520
Eric Laurent77305a62016-07-25 16:39:22 -07002521 // force a device change if any other output is:
2522 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002523 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002524 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002525 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002526 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002527 // change the device currently selected by the other output.
2528 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002529 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002530 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002531 force = true;
2532 }
2533 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002534 // a notification so that audio focus effect can propagate, or that a mute/unmute
2535 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002536 const uint32_t latencyMs = desc->latency();
2537 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2538
2539 if (shouldWait && isActive && (waitMs < latencyMs)) {
2540 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002541 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002542
2543 // Require mute check if another output is on a shared device
2544 // and currently active to have proper drain and avoid pops.
2545 // Note restoring AudioTracks onto this output needs to invoke
2546 // a volume ramp if there is no mute.
2547 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002548
2549 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2550 outputsToReopen.push_back(desc);
2551 }
Eric Laurente552edb2014-03-10 17:42:56 -07002552 }
2553 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002554
jiabin220eea12024-05-17 17:55:20 +00002555 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002556 // If the output is open with preferred mixer attributes, but the routed device is
2557 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2558 // changed.
2559 return DEAD_OBJECT;
2560 }
jiabin220eea12024-05-17 17:55:20 +00002561 for (auto& outputToReopen : outputsToReopen) {
2562 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2563 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002564 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302565 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2566 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002567
Eric Laurente552edb2014-03-10 17:42:56 -07002568 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002569 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002570 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002571 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002572 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002573 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002574 outputDesc->useHwGain() /*force*/)) {
2575 // request AudioService to reinitialize the volume curves asynchronously
2576 ALOGE("checkAndSetVolume failed, requesting volume range init");
2577 mpClientInterface->onVolumeRangeInitRequest();
2578 };
Eric Laurente552edb2014-03-10 17:42:56 -07002579
2580 // update the outputs if starting an output with a stream that can affect notification
2581 // routing
2582 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002583
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002584 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002585 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002586 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002587 }
Eric Laurentdc462862016-07-19 12:29:53 -07002588
2589 if (waitMs > muteWaitMs) {
2590 *delayMs = waitMs - muteWaitMs;
2591 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002592
2593 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2594 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2595 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2596 // change occurs after the MixerThread starts and causes a stream volume
2597 // glitch.
2598 //
2599 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002600 }
Eric Laurentdc462862016-07-19 12:29:53 -07002601
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002602 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002603 mEngine->getForceUse(
2604 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002605 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002606 }
2607
Eric Laurent97ac8712018-07-27 18:59:02 -07002608 // Automatically enable the remote submix input when output is started on a re routing mix
2609 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002610 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2611 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002612 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2613 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2614 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002615 "remote-submix",
2616 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002617 }
2618
Eric Laurent96d1dda2022-03-14 17:14:19 +01002619 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2620
Eric Laurente552edb2014-03-10 17:42:56 -07002621 return NO_ERROR;
2622}
2623
Eric Laurent96d1dda2022-03-14 17:14:19 +01002624void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2625 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2626 bool isUnicastActive = isLeUnicastActive();
2627
2628 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002629 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002630 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2631 for (size_t i = 0; i < mOutputs.size(); i++) {
2632 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2633 if (desc != ignoredOutput && desc->isActive()
2634 && ((isUnicastActive &&
2635 !desc->devices().
2636 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2637 || (wasUnicastActive &&
2638 !desc->devices().getDevicesFromTypes(
2639 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2640 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2641 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002642 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002643 // If the device is using preferred mixer attributes, the output need to reopen
2644 // with default configuration when the new selected devices are different from
2645 // current routing devices.
2646 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2647 continue;
2648 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302649 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002650 // re-apply device specific volume if not done by setOutputDevice()
2651 if (!force) {
2652 applyStreamVolumes(desc, newDevices.types(), delayMs);
2653 }
2654 }
2655 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002656 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002657 }
2658}
2659
Eric Laurent8fc147b2018-07-22 19:13:55 -07002660status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002661{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662 ALOGV("%s portId %d", __FUNCTION__, portId);
2663
2664 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2665 if (outputDesc == 0) {
2666 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002667 return BAD_VALUE;
2668 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002669 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002670
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002671 if (client->hasPreferredDevice(true)) {
2672 // playback activity with preferred device impacts routing occurred, inform upper layers
2673 mpClientInterface->onRoutingUpdated();
2674 }
2675
Eric Laurent97ac8712018-07-27 18:59:02 -07002676 ALOGV("stopOutput() output %d, stream %d, session %d",
2677 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002678
Eric Laurent97ac8712018-07-27 18:59:02 -07002679 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002680
Eric Laurent733ce942017-12-07 12:18:25 -08002681 if (status == NO_ERROR ) {
2682 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002683 } else {
2684 return status;
2685 }
2686
2687 if (outputDesc->devices().size() == 1) {
2688 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2689 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002690 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002691 if (info != nullptr && info->getUid() == client->uid()) {
2692 info->decreaseActiveClient();
2693 if (info->getActiveClientCount() == 0) {
2694 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002695 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002696 }
2697 }
jiabin220eea12024-05-17 17:55:20 +00002698 if (com::android::media::audioserver::
2699 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2700 !outputReopened && outputDesc->isBitPerfect()) {
2701 // Only need to update the clients' internal mute when the output is bit-perfect and it
2702 // is not reopened.
2703 updateClientsInternalMute(outputDesc);
2704 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002705 }
2706 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002707}
2708
Eric Laurent97ac8712018-07-27 18:59:02 -07002709status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2710 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002711{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002712 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002713 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002714 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002715 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002716
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002717 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2718
François Gaffie1c878552018-11-22 16:53:21 +01002719 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2720 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002721 // Automatically disable the remote submix input when output is stopped on a
2722 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002723 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002724 if (isSingleDeviceType(
2725 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002726 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002727 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002728 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2729 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002730 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002731 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002732 }
2733 }
2734 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002735 if (client->hasPreferredDevice(true) &&
2736 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002737 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002738 forceDeviceUpdate = true;
2739 }
2740
Eric Laurente552edb2014-03-10 17:42:56 -07002741 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002742 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002743
Eric Laurente552edb2014-03-10 17:42:56 -07002744 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002745 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002746 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002747 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002748
2749 // If the routing does not change, if an output is routed on a device using HwGain
2750 // (aka setAudioPortConfig) and there are still active clients following different
2751 // volume group(s), force reapply volume
2752 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2753 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2754
Eric Laurente552edb2014-03-10 17:42:56 -07002755 // delay the device switch by twice the latency because stopOutput() is executed when
2756 // the track stop() command is received and at that time the audio track buffer can
2757 // still contain data that needs to be drained. The latency only covers the audio HAL
2758 // and kernel buffers. Also the latency does not always include additional delay in the
2759 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302760 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002761 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002762
2763 // force restoring the device selection on other active outputs if it differs from the
2764 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002765 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002766 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002767 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002768 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002769 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002770 desc->isActive() &&
2771 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002772 (newDevices != desc->devices())) {
2773 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2774 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002775
jiabin220eea12024-05-17 17:55:20 +00002776 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002777 // If the device is using preferred mixer attributes, the output need to
2778 // reopen with default configuration when the new selected devices are
2779 // different from current routing devices.
2780 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2781 continue;
2782 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302783 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002784
Eric Laurent57de36c2016-09-28 16:59:11 -07002785 // re-apply device specific volume if not done by setOutputDevice()
2786 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002787 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002788 }
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
2790 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002791 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002792 // update the outputs if stopping one with a stream that can affect notification routing
2793 handleNotificationRoutingForStream(stream);
2794 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002795
2796 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2797 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002798 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002799 }
2800
François Gaffiec005e562018-11-06 15:04:49 +01002801 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002802 selectOutputForMusicEffects();
2803 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002804
2805 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2806
Eric Laurente552edb2014-03-10 17:42:56 -07002807 return NO_ERROR;
2808 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002809 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002810 return INVALID_OPERATION;
2811 }
2812}
2813
jiabinbce0c1d2020-10-05 11:20:18 -07002814bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002815{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002816 ALOGV("%s portId %d", __FUNCTION__, portId);
2817
2818 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2819 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002820 // If an output descriptor is closed due to a device routing change,
2821 // then there are race conditions with releaseOutput from tracks
2822 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2823 // destroyed shortly thereafter.
2824 //
2825 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002826 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002827 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002828 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002829
2830 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002831
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302832 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2833 if (outputDesc->isClientActive(client)) {
2834 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2835 stopOutput(portId);
2836 }
2837
Eric Laurent8fc147b2018-07-22 19:13:55 -07002838 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2839 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002840 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002841 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002842 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002843 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002844 if (--outputDesc->mDirectOpenCount == 0) {
2845 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002846 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002847 }
2848 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302849
Andy Hung39efb7a2018-09-26 15:39:28 -07002850 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002851 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2852 // The output is pending reopened to query dynamic profiles and
2853 // there is no active clients
2854 closeOutput(outputDesc->mIoHandle);
2855 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2856 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2857 if (newOutputDesc == nullptr) {
2858 ALOGE("%s failed to open output", __func__);
2859 }
2860 return true;
2861 }
2862 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002863}
2864
Eric Laurentcaf7f482014-11-25 17:50:47 -08002865status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2866 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002867 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002868 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002869 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002870 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002871 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002872 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002873 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002874 audio_port_handle_t *portId,
2875 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002876{
François Gaffiec005e562018-11-06 15:04:49 +01002877 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002878 "flags %#x attributes=%s requested device ID %d",
2879 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2880 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002881
Eric Laurentad2e7b92017-09-14 20:06:42 -07002882 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002883 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002884 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002885 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002886 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002887 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002888 sp<RecordClientDescriptor> clientDesc;
2889 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002890 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002892
2893 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2894 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2895 return INVALID_OPERATION;
2896 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002897
Francois Gaffie716e1432019-01-14 16:58:59 +01002898 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2899 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002900 }
2901
Paul McLean466dc8e2015-04-17 13:15:36 -06002902 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002903 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002904 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002905
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2907 // possible
2908 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2909 *input != AUDIO_IO_HANDLE_NONE) {
2910 ssize_t index = mInputs.indexOfKey(*input);
2911 if (index < 0) {
2912 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2913 status = BAD_VALUE;
2914 goto error;
2915 }
2916 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002917 RecordClientVector clients = inputDesc->getClientsForSession(session);
2918 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002919 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2920 status = BAD_VALUE;
2921 goto error;
2922 }
2923 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2924 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002925 // corresponds to a new client and is only permitted from the same UID.
2926 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002927 if (clients.size() > 1) {
2928 for (const auto& client : clients) {
2929 // The client map is ordered by key values (portId) and portIds are allocated
2930 // incrementaly. So the first client in this list is the one opened by audio flinger
2931 // when the mmap stream is created and should be ignored as it does not correspond
2932 // to an actual client
2933 if (client == *clients.cbegin()) {
2934 continue;
2935 }
2936 if (uid != client->uid() && !client->isSilenced()) {
2937 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2938 uid, client->portId(), client->uid());
2939 status = INVALID_OPERATION;
2940 goto error;
2941 }
Eric Laurent331679c2018-04-16 17:03:16 -07002942 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002943 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002944 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002945 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002946
Eric Laurentfecbceb2021-02-09 14:46:43 +01002947 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002948 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002949 }
2950
2951 *input = AUDIO_IO_HANDLE_NONE;
2952 *inputType = API_INPUT_INVALID;
2953
Francois Gaffie716e1432019-01-14 16:58:59 +01002954 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002955 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002956 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002957 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002958 ALOGW("%s could not find input mix for attr %s",
2959 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002960 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002961 }
jiabinc1de2df2019-05-07 14:26:40 -07002962 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2963 String8(attr->tags + strlen("addr=")),
2964 AUDIO_FORMAT_DEFAULT);
2965 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002966 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002967 __func__, attributes.source, attributes.tags);
2968 status = BAD_VALUE;
2969 goto error;
2970 }
2971
Kevin Rocard25f9b052019-02-27 15:08:54 -08002972 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2973 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2974 } else {
2975 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2976 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002977 if (virtualDeviceId) {
2978 *virtualDeviceId = policyMix->mVirtualDeviceId;
2979 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002980 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002981 if (explicitRoutingDevice != nullptr) {
2982 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002983 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002984 // Prevent from storing invalid requested device id in clients
2985 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002986 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002987 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2988 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002989 }
François Gaffie11d30102018-11-02 16:09:09 +01002990 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002991 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002992 status = BAD_VALUE;
2993 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002994 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002995 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2996 *inputType = API_INPUT_MIX_CAPTURE;
2997 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002998 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2999 // there is an external policy, but this input is attached to a mix of recorders,
3000 // meaning it receives audio injected into the framework, so the recorder doesn't
3001 // know about it and is therefore considered "legacy"
3002 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003003
3004 if (virtualDeviceId) {
3005 *virtualDeviceId = policyMix->mVirtualDeviceId;
3006 }
François Gaffie11d30102018-11-02 16:09:09 +01003007 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003008 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003009 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003010 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003011 } else {
3012 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003013 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003014
Eric Laurent599c7582015-12-07 18:05:55 -08003015 }
3016
François Gaffiec005e562018-11-06 15:04:49 +01003017 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003018 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003019 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003020 AudioProfileVector profiles;
3021 status_t ret = getProfilesForDevices(
3022 DeviceVector(device), profiles, flags, true /*isInput*/);
3023 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003024 const auto channels = profiles[0]->getChannels();
3025 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3026 config->channel_mask = *channels.begin();
3027 }
3028 const auto sampleRates = profiles[0]->getSampleRates();
3029 if (!sampleRates.empty() &&
3030 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3031 config->sample_rate = *sampleRates.begin();
3032 }
jiabinf1c73972022-04-14 16:28:52 -07003033 config->format = profiles[0]->getFormat();
3034 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003035 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003036 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003037
Marvin Ramine5a122d2023-12-07 13:57:59 +01003038
3039 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3040 *virtualDeviceId = policyMix->mVirtualDeviceId;
3041 }
3042
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043exit:
3044
François Gaffiec005e562018-11-06 15:04:49 +01003045 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3046 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003047
Francois Gaffie716e1432019-01-14 16:58:59 +01003048 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003049 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003050 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051
Mikhail Naganov2996f672019-04-18 12:29:59 -07003052 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003053 requestedDeviceId, attributes.source, flags,
3054 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003055 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003056 // Move (if found) effect for the client session to its input
3057 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003058 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003059
3060 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3061 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003062
Eric Laurent599c7582015-12-07 18:05:55 -08003063 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003064
3065error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003066 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003067}
3068
3069
François Gaffie11d30102018-11-02 16:09:09 +01003070audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003071 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003072 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003073 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003074 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003075 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003076{
3077 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003078 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003079 bool isSoundTrigger = false;
3080
François Gaffiec005e562018-11-06 15:04:49 +01003081 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003082 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3083 if (index >= 0) {
3084 input = mSoundTriggerSessions.valueFor(session);
3085 isSoundTrigger = true;
3086 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3087 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3088 } else {
3089 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003090 }
François Gaffiec005e562018-11-06 15:04:49 +01003091 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003092 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003093 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003094 }
3095
Carter Hsua3abb402021-10-26 11:11:20 +08003096 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3097 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3098 }
3099
Eric Laurentfe231122017-11-17 17:48:06 -08003100 // sampling rate and flags may be updated by getInputProfile
3101 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3102 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003103 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003104 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003105 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003106 // find a compatible input profile (not necessarily identical in parameters)
3107 sp<IOProfile> profile = getInputProfile(
3108 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3109 if (profile == nullptr) {
3110 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003111 }
jiabin2fd710d2022-05-02 23:20:22 +00003112
Glenn Kasten05ddca52016-02-11 08:17:12 -08003113 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003114 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003115 if (samplingRate == 0) {
3116 samplingRate = profileSamplingRate;
3117 }
Eric Laurente552edb2014-03-10 17:42:56 -07003118
Eric Laurent322b4d22015-04-03 15:57:54 -07003119 if (profile->getModuleHandle() == 0) {
3120 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003121 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003122 }
3123
Eric Laurentec376dc2021-04-08 20:41:22 +02003124 // Reuse an already opened input if a client with the same session ID already exists
3125 // on that input
3126 for (size_t i = 0; i < mInputs.size(); i++) {
3127 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3128 if (desc->mProfile != profile) {
3129 continue;
3130 }
3131 RecordClientVector clients = desc->clientsList();
3132 for (const auto &client : clients) {
3133 if (session == client->session()) {
3134 return desc->mIoHandle;
3135 }
3136 }
3137 }
3138
Eric Laurentc71b11b2024-06-03 12:54:53 +00003139 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003140 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003141 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3142 // First pick best candidate for preemption (there may not be any):
3143 // - Preempt and input if:
3144 // - It has only strictly lower priority use cases than the new client
3145 // - It has equal priority use cases than the new client, was not
3146 // opened thanks to preemption or has been active since opened.
3147 // - Order the preemption candidates by inactive first and priority second
3148 sp<AudioInputDescriptor> closeCandidate;
3149 int leastCloseRank = INT_MAX;
3150 static const int sCloseActive = 0x100;
3151
3152 for (size_t i = 0; i < mInputs.size(); i++) {
3153 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3154 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003155 continue;
3156 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003157 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3158 if (topPrioClient == nullptr) {
3159 continue;
3160 }
3161 int topPrio = source_priority(topPrioClient->source());
3162 if (topPrio < source_priority(attributes.source)
3163 || (topPrio == source_priority(attributes.source)
3164 && !desc->isPreemptor())) {
3165 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3166 if (closeRank < leastCloseRank) {
3167 leastCloseRank = closeRank;
3168 closeCandidate = desc;
3169 }
3170 }
3171 }
3172
3173 if (closeCandidate != nullptr) {
3174 closeInput(closeCandidate->mIoHandle);
3175 // Mark the new input as being issued from a preemption
3176 // so that is will not be preempted later
3177 isPreemptor = true;
3178 } else {
3179 // Then pick the best reusable input (There is always one)
3180 // The order of preference is:
3181 // 1) active inputs with same use case as the new client
3182 // 2) inactive inputs with same use case
3183 // 3) active inputs with different use cases
3184 // 4) inactive inputs with different use cases
3185 sp<AudioInputDescriptor> reuseCandidate;
3186 int leastReuseRank = INT_MAX;
3187 static const int sReuseDifferentUseCase = 0x100;
3188
3189 for (size_t i = 0; i < mInputs.size(); i++) {
3190 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3191 if (desc->mProfile != profile) {
3192 continue;
3193 }
3194 int reuseRank = sReuseDifferentUseCase;
3195 for (const auto& client: desc->getClientIterable()) {
3196 if (client->source() == attributes.source) {
3197 reuseRank = 0;
3198 break;
3199 }
3200 }
3201 reuseRank += desc->isActive() ? 0 : 1;
3202 if (reuseRank < leastReuseRank) {
3203 leastReuseRank = reuseRank;
3204 reuseCandidate = desc;
3205 }
3206 }
3207 return reuseCandidate->mIoHandle;
3208 }
3209 } else { // fix_input_sharing_logic()
3210 for (size_t i = 0; i < mInputs.size(); ) {
3211 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3212 if (desc->mProfile != profile) {
3213 i++;
3214 continue;
3215 }
3216 // if sound trigger, reuse input if used by other sound trigger on same session
3217 // else
3218 // reuse input if active client app is not in IDLE state
3219 //
3220 RecordClientVector clients = desc->clientsList();
3221 bool doClose = false;
3222 for (const auto& client : clients) {
3223 if (isSoundTrigger != client->isSoundTrigger()) {
3224 continue;
3225 }
3226 if (client->isSoundTrigger()) {
3227 if (session == client->session()) {
3228 return desc->mIoHandle;
3229 }
3230 continue;
3231 }
3232 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003233 return desc->mIoHandle;
3234 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003235 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003236 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003237 if (doClose) {
3238 closeInput(desc->mIoHandle);
3239 } else {
3240 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003241 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003242 }
3243 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003244 }
3245
Eric Laurentc71b11b2024-06-03 12:54:53 +00003246 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3247 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003248
Eric Laurentfe231122017-11-17 17:48:06 -08003249 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3250 lConfig.sample_rate = profileSamplingRate;
3251 lConfig.channel_mask = profileChannelMask;
3252 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003253
François Gaffie11d30102018-11-02 16:09:09 +01003254 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003255
3256 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003257 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003258 (profileSamplingRate != lConfig.sample_rate) ||
3259 !audio_formats_match(profileFormat, lConfig.format) ||
3260 (profileChannelMask != lConfig.channel_mask)) {
3261 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003262 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003263 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003264 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003265 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003266 }
Eric Laurent599c7582015-12-07 18:05:55 -08003267 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003268 }
3269
Eric Laurentc722f302014-12-10 11:21:49 -08003270 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003271
Eric Laurent599c7582015-12-07 18:05:55 -08003272 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003273 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003274
Eric Laurent599c7582015-12-07 18:05:55 -08003275 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003276}
3277
Eric Laurent4eb58f12018-12-07 16:41:02 -08003278status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003280 ALOGV("%s portId %d", __FUNCTION__, portId);
3281
3282 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3283 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003285 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003286 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003287 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003288 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 if (client->active()) {
3290 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3291 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003292 }
3293
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 audio_session_t session = client->session();
3295
Eric Laurent4eb58f12018-12-07 16:41:02 -08003296 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003297
Eric Laurent4eb58f12018-12-07 16:41:02 -08003298 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003299
Eric Laurent4eb58f12018-12-07 16:41:02 -08003300 status_t status = inputDesc->start();
3301 if (status != NO_ERROR) {
3302 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003303 }
Eric Laurente552edb2014-03-10 17:42:56 -07003304
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003305 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003306 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003307 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003308
Eric Laurent8f42ea12018-08-08 09:08:25 -07003309 // indicate active capture to sound trigger service if starting capture from a mic on
3310 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003311 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003312 if (device != nullptr) {
3313 status = setInputDevice(input, device, true /* force */);
3314 } else {
3315 ALOGW("%s no new input device can be found for descriptor %d",
3316 __FUNCTION__, inputDesc->getId());
3317 status = BAD_VALUE;
3318 }
Eric Laurente552edb2014-03-10 17:42:56 -07003319
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003320 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003321 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003322 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003323 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003324 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3325 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003327 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003328
François Gaffie11d30102018-11-02 16:09:09 +01003329 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3330 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003332 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003334
Eric Laurent8f42ea12018-08-08 09:08:25 -07003335 // automatically enable the remote submix output when input is started if not
3336 // used by a policy mix of type MIX_TYPE_RECORDERS
3337 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003338 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003339 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003340 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003341 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003342 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3343 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003344 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003345 if (address != "") {
3346 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3347 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003348 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003349 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003350 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003351 } else if (status != NO_ERROR) {
3352 // Restore client activity state.
3353 inputDesc->setClientActive(client, false);
3354 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003355 }
3356
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003357 ALOGV("%s input %d source = %d status = %d exit",
3358 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003359
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003360 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003361}
3362
Eric Laurent8fc147b2018-07-22 19:13:55 -07003363status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003364{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003365 ALOGV("%s portId %d", __FUNCTION__, portId);
3366
3367 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3368 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003369 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003370 return BAD_VALUE;
3371 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003372 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003373 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003374 if (!client->active()) {
3375 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003376 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003377 }
Carter Hsue6139d52021-07-08 10:30:20 +08003378 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003380
Eric Laurent8f42ea12018-08-08 09:08:25 -07003381 inputDesc->stop();
3382 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003383 auto current_source = inputDesc->source();
3384 setInputDevice(input, getNewInputDevice(inputDesc),
3385 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003386 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003387 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003388 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003389 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003390 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3391 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003392 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003393 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394
3395 // automatically disable the remote submix output when input is stopped if not
3396 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003397 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003398 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003399 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003400 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003401 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3402 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003403 }
3404 if (address != "") {
3405 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3406 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003407 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 }
3409 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003410 resetInputDevice(input);
3411
3412 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3413 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003414 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3415 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003416 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003417 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003418 }
3419 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003420 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003421 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003422}
3423
Eric Laurent8fc147b2018-07-22 19:13:55 -07003424void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003425{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003426 ALOGV("%s portId %d", __FUNCTION__, portId);
3427
3428 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3429 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003430 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003431 return;
3432 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003433 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003434 audio_io_handle_t input = inputDesc->mIoHandle;
3435
Eric Laurent8f42ea12018-08-08 09:08:25 -07003436 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003437
Andy Hung39efb7a2018-09-26 15:39:28 -07003438 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003439
3440 // If no more clients are present in this session, park effects to an orphan chain
3441 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3442 if (clientsOnSession.size() == 0) {
3443 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3444 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003445 if (inputDesc->getClientCount() > 0) {
3446 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003447 return;
3448 }
3449
Eric Laurent05b90f82014-08-27 15:32:29 -07003450 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003451 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003452 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003453}
3454
Eric Laurent8f42ea12018-08-08 09:08:25 -07003455void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003456{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003458
3459 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003460 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003461 }
3462}
3463
Eric Laurent8f42ea12018-08-08 09:08:25 -07003464void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3465{
3466 stopInput(portId);
3467 releaseInput(portId);
3468}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003469
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003470bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3471 if (input->clientsList().size() == 0
3472 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3473 return true;
3474 }
3475 for (const auto& client : input->clientsList()) {
3476 sp<DeviceDescriptor> device =
3477 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3478 client->session());
3479 if (!input->supportedDevices().contains(device)) {
3480 return true;
3481 }
3482 }
3483 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3484 return false;
3485}
3486
Eric Laurent0dd51852019-04-19 18:18:58 -07003487void AudioPolicyManager::checkCloseInputs() {
3488 // After connecting or disconnecting an input device, close input if:
3489 // - it has no client (was just opened to check profile) OR
3490 // - none of its supported devices are connected anymore OR
3491 // - one of its clients cannot be routed to one of its supported
3492 // devices anymore. Otherwise update device selection
3493 std::vector<audio_io_handle_t> inputsToClose;
3494 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003495 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003496 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003497 }
3498 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003499 for (const audio_io_handle_t handle : inputsToClose) {
3500 ALOGV("%s closing input %d", __func__, handle);
3501 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003502 }
Eric Laurentd4692962014-05-05 18:13:44 -07003503}
3504
Vlad Popa87e0e582024-05-20 18:49:20 -07003505status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3506 const char *address __unused,
3507 bool enabled,
3508 audio_stream_type_t streamToDriveAbs)
3509{
Vlad Popaa536eb32024-07-18 16:00:35 -07003510 if (!enabled) {
3511 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3512 return NO_ERROR;
3513 }
3514
Vlad Popa87e0e582024-05-20 18:49:20 -07003515 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3516 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3517 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3518 toString(streamToDriveAbs).c_str());
3519 return BAD_VALUE;
3520 }
3521
Vlad Popaa536eb32024-07-18 16:00:35 -07003522 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003523 return NO_ERROR;
3524}
3525
François Gaffie251c7f02018-11-07 10:41:08 +01003526void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003527{
3528 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003529 if (indexMin < 0 || indexMax < 0) {
3530 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3531 return;
3532 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003533 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003534
3535 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003536 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3537 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003538 continue;
3539 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003540 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003541 }
Eric Laurente552edb2014-03-10 17:42:56 -07003542}
3543
Eric Laurente0720872014-03-11 09:30:41 -07003544status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003545 int index,
3546 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003547{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003548 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003549 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3550 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3551 return NO_ERROR;
3552 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303553 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3554 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003555 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003556}
3557
Eric Laurente0720872014-03-11 09:30:41 -07003558status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003559 int *index,
3560 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003561{
François Gaffiec005e562018-11-06 15:04:49 +01003562 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3563 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003564 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003565 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003566 deviceTypes = mEngine->getOutputDevicesForStream(
3567 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003568 }
jiabin9a3361e2019-10-01 09:38:30 -07003569 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003570}
3571
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003572status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003573 int index,
3574 audio_devices_t device)
3575{
3576 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003577 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3578 if (group == VOLUME_GROUP_NONE) {
3579 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003580 return BAD_VALUE;
3581 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003582 ALOGV("%s: group %d matching with %s index %d",
3583 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003584 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003585 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003586 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003587 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3588 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3589 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3590 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003591 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3592
3593 status = setVolumeCurveIndex(index, device, curves);
3594 if (status != NO_ERROR) {
3595 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3596 return status;
3597 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003598
jiabin9a3361e2019-10-01 09:38:30 -07003599 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003600 auto curCurvAttrs = curves.getAttributes();
3601 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3602 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003603 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003604 } else if (!curves.getStreamTypes().empty()) {
3605 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003606 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003607 } else {
3608 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3609 return BAD_VALUE;
3610 }
jiabin9a3361e2019-10-01 09:38:30 -07003611 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3612 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003613
François Gaffiecfe17322018-11-07 13:41:29 +01003614 // update volume on all outputs and streams matching the following:
3615 // - The requested stream (or a stream matching for volume control) is active on the output
3616 // - The device (or devices) selected by the engine for this stream includes
3617 // the requested device
3618 // - For non default requested device, currently selected device on the output is either the
3619 // requested device or one of the devices selected by the engine for this stream
3620 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3621 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003622 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003623 for (size_t i = 0; i < mOutputs.size(); i++) {
3624 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003625 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003626
jiabin9a3361e2019-10-01 09:38:30 -07003627 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3628 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003629 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003630
3631 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003632 continue;
3633 }
3634 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3635 curDevices.find(device) == curDevices.end()) {
3636 continue;
3637 }
3638 bool applyVolume = false;
3639 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3640 curSrcDevices.insert(device);
3641 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003642 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3643 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003644 } else {
3645 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3646 }
3647 if (!applyVolume) {
3648 continue; // next output
3649 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003650 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3651 // If a higher priority strategy is active, and the output is routed to a device with a
3652 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003653 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003654 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003655 // If the volume source is active with higher priority source, ensure at least Sw Muted
3656 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003657 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3658 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3659 false /*preferredDevice*/);
3660 if (activeClients.empty()) {
3661 continue;
3662 }
3663 bool isPreempted = false;
3664 bool isHigherPriority = productStrategy < strategy;
3665 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003666 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003667 ALOGV("%s: Strategy=%d (\nrequester:\n"
3668 " group %d, volumeGroup=%d attributes=%s)\n"
3669 " higher priority source active:\n"
3670 " volumeGroup=%d attributes=%s) \n"
3671 " on output %zu, bailing out", __func__, productStrategy,
3672 group, group, toString(attributes).c_str(),
3673 client->volumeSource(), toString(client->attributes()).c_str(), i);
3674 applyVolume = false;
3675 isPreempted = true;
3676 break;
3677 }
3678 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003679 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003680 applyVolume = true;
3681 }
3682 }
3683 if (isPreempted || applyVolume) {
3684 break;
3685 }
3686 }
3687 if (!applyVolume) {
3688 continue; // next output
3689 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003690 }
François Gaffieed91f582020-01-31 10:35:37 +01003691 //FIXME: workaround for truncated touch sounds
3692 // delayed volume change for system stream to be removed when the problem is
3693 // handled by system UI
3694 status_t volStatus = checkAndSetVolume(
3695 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003696 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003697 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3698 if (volStatus != NO_ERROR) {
3699 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003700 }
3701 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003702
3703 // update voice volume if the an active call route exists
3704 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3705 && (curSrcDevices.find(
3706 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3707 != curSrcDevices.end())) {
3708 bool isVoiceVolSrc;
3709 bool isBtScoVolSrc;
3710 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3711 isVoiceVolSrc, isBtScoVolSrc, __func__)
3712 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003713 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3714 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3715 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003716 }
3717 }
3718
François Gaffiecfe17322018-11-07 13:41:29 +01003719 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3720 return status;
3721}
3722
François Gaffieaaac0fd2018-11-22 17:56:39 +01003723status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003724 audio_devices_t device,
3725 IVolumeCurves &volumeCurves)
3726{
3727 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3728 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003729 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3730 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003731 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303732 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3733 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003734 return BAD_VALUE;
3735 }
3736 if (!audio_is_output_device(device)) {
3737 return BAD_VALUE;
3738 }
3739
3740 // Force max volume if stream cannot be muted
3741 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3742
François Gaffieaaac0fd2018-11-22 17:56:39 +01003743 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003744 volumeCurves.addCurrentVolumeIndex(device, index);
3745 return NO_ERROR;
3746}
3747
3748status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3749 int &index,
3750 audio_devices_t device)
3751{
3752 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3753 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003754 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003755 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003756 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003757 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003758 }
jiabin9a3361e2019-10-01 09:38:30 -07003759 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003760}
3761
3762status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3763 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003764 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003765{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003766 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003767 return BAD_VALUE;
3768 }
jiabin9a3361e2019-10-01 09:38:30 -07003769 index = curves.getVolumeIndex(deviceTypes);
3770 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003771 return NO_ERROR;
3772}
3773
3774status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3775 int &index)
3776{
3777 index = getVolumeCurves(attr).getVolumeIndexMin();
3778 return NO_ERROR;
3779}
3780
3781status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3782 int &index)
3783{
3784 index = getVolumeCurves(attr).getVolumeIndexMax();
3785 return NO_ERROR;
3786}
3787
Eric Laurent36829f92017-04-07 19:04:42 -07003788audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003789{
3790 // select one output among several suitable for global effects.
3791 // The priority is as follows:
3792 // 1: An offloaded output. If the effect ends up not being offloadable,
3793 // AudioFlinger will invalidate the track and the offloaded output
3794 // will be closed causing the effect to be moved to a PCM output.
3795 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003796 // 3: The primary output
3797 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003798
François Gaffiec005e562018-11-06 15:04:49 +01003799 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3800 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003801 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003802
Eric Laurent36829f92017-04-07 19:04:42 -07003803 if (outputs.size() == 0) {
3804 return AUDIO_IO_HANDLE_NONE;
3805 }
Eric Laurente552edb2014-03-10 17:42:56 -07003806
Eric Laurent36829f92017-04-07 19:04:42 -07003807 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3808 bool activeOnly = true;
3809
3810 while (output == AUDIO_IO_HANDLE_NONE) {
3811 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3812 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3813 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3814
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003815 for (audio_io_handle_t output : outputs) {
3816 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003817 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003818 continue;
3819 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003820 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3821 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003822 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003823 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003824 }
3825 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003826 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003827 }
3828 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003829 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003830 }
3831 }
3832 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3833 output = outputOffloaded;
3834 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3835 output = outputDeepBuffer;
3836 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3837 output = outputPrimary;
3838 } else {
3839 output = outputs[0];
3840 }
3841 activeOnly = false;
3842 }
3843
3844 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003845 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3846 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003847 mMusicEffectOutput = output;
3848 }
3849
3850 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003851 return output;
3852}
3853
Eric Laurent36829f92017-04-07 19:04:42 -07003854audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3855{
3856 return selectOutputForMusicEffects();
3857}
3858
Eric Laurente0720872014-03-11 09:30:41 -07003859status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003860 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003861 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003862 int session,
3863 int id)
3864{
Shunkai Yao29d10572024-03-19 04:31:47 +00003865 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003866 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003867 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003868 index = mInputs.indexOfKey(io);
3869 if (index < 0) {
3870 ALOGW("registerEffect() unknown io %d", io);
3871 return INVALID_OPERATION;
3872 }
Eric Laurente552edb2014-03-10 17:42:56 -07003873 }
3874 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003875 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3876 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3877 || strategy == PRODUCT_STRATEGY_NONE));
3878 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003879}
3880
Eric Laurentc241b0d2018-11-28 09:08:49 -08003881status_t AudioPolicyManager::unregisterEffect(int id)
3882{
3883 if (mEffects.getEffect(id) == nullptr) {
3884 return INVALID_OPERATION;
3885 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003886 if (mEffects.isEffectEnabled(id)) {
3887 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3888 setEffectEnabled(id, false);
3889 }
3890 return mEffects.unregisterEffect(id);
3891}
3892
3893status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3894{
3895 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3896 if (effect == nullptr) {
3897 return INVALID_OPERATION;
3898 }
3899
3900 status_t status = mEffects.setEffectEnabled(id, enabled);
3901 if (status == NO_ERROR) {
3902 mInputs.trackEffectEnabled(effect, enabled);
3903 }
3904 return status;
3905}
3906
Eric Laurent6c796322019-04-09 14:13:17 -07003907
3908status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3909{
3910 mEffects.moveEffects(ids, io);
3911 return NO_ERROR;
3912}
3913
Eric Laurentc75307b2015-03-17 15:29:32 -07003914bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3915{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003916 auto vs = toVolumeSource(stream, false);
3917 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003918}
3919
3920bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3921{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003922 auto vs = toVolumeSource(stream, false);
3923 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003924}
3925
Eric Laurente0720872014-03-11 09:30:41 -07003926bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003927{
3928 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003929 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003930 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003931 return true;
3932 }
3933 }
3934 return false;
3935}
3936
Eric Laurent275e8e92014-11-30 15:14:47 -08003937// Register a list of custom mixes with their attributes and format.
3938// When a mix is registered, corresponding input and output profiles are
3939// added to the remote submix hw module. The profile contains only the
3940// parameters (sampling rate, format...) specified by the mix.
3941// The corresponding input remote submix device is also connected.
3942//
3943// When a remote submix device is connected, the address is checked to select the
3944// appropriate profile and the corresponding input or output stream is opened.
3945//
3946// When capture starts, getInputForAttr() will:
3947// - 1 look for a mix matching the address passed in attribtutes tags if any
3948// - 2 if none found, getDeviceForInputSource() will:
3949// - 2.1 look for a mix matching the attributes source
3950// - 2.2 if none found, default to device selection by policy rules
3951// At this time, the corresponding output remote submix device is also connected
3952// and active playback use cases can be transferred to this mix if needed when reconnecting
3953// after AudioTracks are invalidated
3954//
3955// When playback starts, getOutputForAttr() will:
3956// - 1 look for a mix matching the address passed in attribtutes tags if any
3957// - 2 if none found, look for a mix matching the attributes usage
3958// - 3 if none found, default to device and output selection by policy rules.
3959
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003960status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003961{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003962 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3963 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003964 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003965 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003966 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003967 // examine each mix's route type
3968 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003969 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003970 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3971 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3972 ALOGE("Unsupported Policy Mix %zu of %zu: "
3973 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3974 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003975 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003976 break;
3977 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003978 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3979 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003980 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003981 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3982 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003983 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003984 rSubmixModule = mHwModules.getModuleFromName(
3985 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3986 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003987 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003988 i);
3989 res = INVALID_OPERATION;
3990 break;
3991 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003992 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003993
Eric Laurent97ac8712018-07-27 18:59:02 -07003994 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003995 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003996 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003997 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003998 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3999 } else {
4000 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4001 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004002 }
François Gaffie036e1e92015-03-19 10:16:24 +01004003
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004004 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004005 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 res = INVALID_OPERATION;
4007 break;
4008 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004009 audio_config_t outputConfig = mix.mFormat;
4010 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004011 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4012 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004013 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4014 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004015 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004016 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4017 audio_is_linear_pcm(outputConfig.format)
4018 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004019 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004020 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4021 audio_is_linear_pcm(inputConfig.format)
4022 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004023
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004024 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004025 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004026 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004027 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004028 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004029 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004031 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4032 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004033 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004034 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004035 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004036
4037 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4038 mix.mDeviceType, mix.mDeviceAddress,
4039 String8(), AUDIO_FORMAT_DEFAULT);
4040 if (device == nullptr) {
4041 res = INVALID_OPERATION;
4042 break;
4043 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004044
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004045 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004046 // First try to find an already opened output supporting the device
4047 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004048 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004049
Eric Laurentc529cf62020-04-17 18:19:10 -07004050 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004051 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004052 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004053 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004054 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004055 } else {
4056 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004057 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004058 }
4059 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004060 // If no output found, try to find a direct output profile supporting the device
4061 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4062 sp<HwModule> module = mHwModules[i];
4063 for (size_t j = 0;
4064 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4065 j++) {
4066 sp<IOProfile> profile = module->getOutputProfiles()[j];
4067 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4068 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4069 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004070 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004071 res = INVALID_OPERATION;
4072 } else {
4073 foundOutput = true;
4074 }
4075 }
4076 }
4077 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004078 if (res != NO_ERROR) {
4079 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004080 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004081 res = INVALID_OPERATION;
4082 break;
4083 } else if (!foundOutput) {
4084 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004085 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004086 res = INVALID_OPERATION;
4087 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004088 } else {
4089 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004090 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004091 }
Eric Laurentc722f302014-12-10 11:21:49 -08004092 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004093 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004094 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004095 if (audio_flags::audio_mix_ownership()) {
4096 // Only unregister mixes that were actually registered to not accidentally unregister
4097 // mixes that already existed previously.
4098 unregisterPolicyMixes(registeredMixes);
4099 registeredMixes.clear();
4100 } else {
4101 unregisterPolicyMixes(mixes);
4102 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004103 } else if (checkOutputs) {
4104 checkForDeviceAndOutputChanges();
4105 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004106 }
4107 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004108}
4109
4110status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4111{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004112 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004113 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004114 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004115 sp<HwModule> rSubmixModule;
4116 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004117 for (const auto& mix : mixes) {
4118 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004119
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004120 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004121 rSubmixModule = mHwModules.getModuleFromName(
4122 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4123 if (rSubmixModule == 0) {
4124 res = INVALID_OPERATION;
4125 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004126 }
4127 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004128
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004129 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004130
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004131 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004132 res = INVALID_OPERATION;
4133 continue;
4134 }
4135
Marvin Ramin0783e202024-03-05 12:45:50 +01004136 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004137 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004138 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4139 status_t currentRes =
4140 setDeviceConnectionStateInt(device,
4141 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4142 address.c_str(),
4143 "remote-submix",
4144 AUDIO_FORMAT_DEFAULT);
4145 if (!audio_flags::audio_mix_ownership()) {
4146 res = currentRes;
4147 }
4148 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004149 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004150 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004151 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004152 }
4153 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004154 }
jiabin5740f082019-08-19 15:08:30 -07004155 rSubmixModule->removeOutputProfile(address.c_str());
4156 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004157
Kevin Rocard153f92d2018-12-18 18:33:28 -08004158 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004159 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004160 res = INVALID_OPERATION;
4161 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004162 } else {
4163 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004164 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004165 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004166 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004167
4168 if (res == NO_ERROR && checkOutputs) {
4169 checkForDeviceAndOutputChanges();
4170 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004171 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004172 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004173}
4174
Marvin Raminbdefaf02023-11-01 09:10:32 +01004175status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4176 if (!audio_flags::audio_mix_test_api()) {
4177 return INVALID_OPERATION;
4178 }
4179
4180 _aidl_return.clear();
4181 _aidl_return.reserve(mPolicyMixes.size());
4182 for (const auto &policyMix: mPolicyMixes) {
4183 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4184 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4185 policyMix->mCbFlags);
4186 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004187 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004188 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004189 }
4190
Vlad Popaa5d73f32024-03-08 16:05:38 -08004191 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004192 return OK;
4193}
4194
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004195status_t AudioPolicyManager::updatePolicyMix(
4196 const AudioMix& mix,
4197 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4198 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4199 if (res == NO_ERROR) {
4200 checkForDeviceAndOutputChanges();
4201 updateCallAndOutputRouting();
4202 }
4203 return res;
4204}
4205
Mikhail Naganov100f0122018-11-29 11:22:16 -08004206void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4207{
4208 size_t i = 0;
4209 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4210 for (const auto& fmt : mManualSurroundFormats) {
4211 if (i++ != 0) dst->append(", ");
4212 std::string sfmt;
4213 FormatConverter::toString(fmt, sfmt);
4214 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4215 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4216 }
4217}
4218
Eric Laurentc529cf62020-04-17 18:19:10 -07004219// Returns true if all devices types match the predicate and are supported by one HW module
4220bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004221 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004222 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004223 const char *context,
4224 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004225 for (size_t i = 0; i < devices.size(); i++) {
4226 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004227 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004228 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004229 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004230 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004231 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004232 return false;
4233 }
4234 }
4235 return true;
4236}
4237
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004238void AudioPolicyManager::changeOutputDevicesMuteState(
4239 const AudioDeviceTypeAddrVector& devices) {
4240 ALOGVV("%s() num devices %zu", __func__, devices.size());
4241
4242 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4243 getSoftwareOutputsForDevices(devices);
4244
4245 for (size_t i = 0; i < outputs.size(); i++) {
4246 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4247 DeviceVector prevDevices = outputDesc->devices();
4248 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4249 }
4250}
4251
4252std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4253 const AudioDeviceTypeAddrVector& devices) const
4254{
4255 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4256 DeviceVector deviceDescriptors;
4257 for (size_t j = 0; j < devices.size(); j++) {
4258 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4259 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4260 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4261 ALOGE("%s: device type %#x address %s not supported or not an output device",
4262 __func__, devices[j].mType, devices[j].getAddress());
4263 continue;
4264 }
4265 deviceDescriptors.add(desc);
4266 }
4267 for (size_t i = 0; i < mOutputs.size(); i++) {
4268 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4269 continue;
4270 }
4271 outputs.push_back(mOutputs.valueAt(i));
4272 }
4273 return outputs;
4274}
4275
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004276status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004277 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004278 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004279 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4280 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004281 }
4282 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004283 if (res != NO_ERROR) {
4284 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4285 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004286 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004287
4288 checkForDeviceAndOutputChanges();
4289 updateCallAndOutputRouting();
4290
4291 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004292}
4293
4294status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4295 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004296 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4297 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004298 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004299 __FUNCTION__, uid);
4300 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004301 }
4302
Eric Laurentc529cf62020-04-17 18:19:10 -07004303 checkForDeviceAndOutputChanges();
4304 updateCallAndOutputRouting();
4305
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004306 return res;
4307}
4308
Eric Laurent2517af32020-11-25 15:31:27 +01004309
jiabin0a488932020-08-07 17:32:40 -07004310status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4311 device_role_t role,
4312 const AudioDeviceTypeAddrVector &devices) {
4313 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4314 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004315
Eric Laurentc529cf62020-04-17 18:19:10 -07004316 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004317 return BAD_VALUE;
4318 }
jiabin0a488932020-08-07 17:32:40 -07004319 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004320 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004321 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4322 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004323 return status;
4324 }
4325
4326 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004327
4328 bool forceVolumeReeval = false;
4329 // FIXME: workaround for truncated touch sounds
4330 // to be removed when the problem is handled by system UI
4331 uint32_t delayMs = 0;
4332 if (strategy == mCommunnicationStrategy) {
4333 forceVolumeReeval = true;
4334 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4335 updateInputRouting();
4336 }
4337 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004338
4339 return NO_ERROR;
4340}
4341
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004342void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4343 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004344{
4345 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004346 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004347 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004348 // Only apply special touch sound delay once
4349 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004350 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004351 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004352 for (size_t i = 0; i < mOutputs.size(); i++) {
4353 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4354 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004355 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4356 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004357 // As done in setDeviceConnectionState, we could also fix default device issue by
4358 // preventing the force re-routing in case of default dev that distinguishes on address.
4359 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004360 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004361 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004362 // If the device is using preferred mixer attributes, the output need to reopen
4363 // with default configuration when the new selected devices are different from
4364 // current routing devices.
4365 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4366 continue;
4367 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304368
4369 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4370 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004371 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004372 // Only apply special touch sound delay once
4373 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004374 }
4375 if (forceVolumeReeval && !newDevices.isEmpty()) {
4376 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4377 }
4378 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004379 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004380 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004381}
4382
Eric Laurent2517af32020-11-25 15:31:27 +01004383void AudioPolicyManager::updateInputRouting() {
4384 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304385 // Skip for hotword recording as the input device switch
4386 // is handled within sound trigger HAL
4387 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4388 continue;
4389 }
Eric Laurent2517af32020-11-25 15:31:27 +01004390 auto newDevice = getNewInputDevice(activeDesc);
4391 // Force new input selection if the new device can not be reached via current input
4392 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4393 setInputDevice(activeDesc->mIoHandle, newDevice);
4394 } else {
4395 closeInput(activeDesc->mIoHandle);
4396 }
4397 }
4398}
4399
Paul Wang5d7cdb52022-11-22 09:45:06 +00004400status_t
4401AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4402 device_role_t role,
4403 const AudioDeviceTypeAddrVector &devices) {
4404 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4405 dumpAudioDeviceTypeAddrVector(devices).c_str());
4406
Eric Laurent78fedbf2023-03-09 14:40:44 +01004407 if (!areAllDevicesSupported(
4408 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004409 return BAD_VALUE;
4410 }
4411 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4412 if (status != NO_ERROR) {
4413 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4414 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4415 return status;
4416 }
4417
4418 checkForDeviceAndOutputChanges();
4419
4420 bool forceVolumeReeval = false;
4421 // TODO(b/263479999): workaround for truncated touch sounds
4422 // to be removed when the problem is handled by system UI
4423 uint32_t delayMs = 0;
4424 if (strategy == mCommunnicationStrategy) {
4425 forceVolumeReeval = true;
4426 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4427 updateInputRouting();
4428 }
4429 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4430
4431 return NO_ERROR;
4432}
4433
4434status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4435 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004436{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004437 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004438
Paul Wang5d7cdb52022-11-22 09:45:06 +00004439 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004440 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004441 ALOGW_IF(status != NAME_NOT_FOUND,
4442 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004443 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004444 return status;
4445 }
4446
4447 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004448
4449 bool forceVolumeReeval = false;
4450 // FIXME: workaround for truncated touch sounds
4451 // to be removed when the problem is handled by system UI
4452 uint32_t delayMs = 0;
4453 if (strategy == mCommunnicationStrategy) {
4454 forceVolumeReeval = true;
4455 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4456 updateInputRouting();
4457 }
4458 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004459
4460 return NO_ERROR;
4461}
4462
jiabin0a488932020-08-07 17:32:40 -07004463status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4464 device_role_t role,
4465 AudioDeviceTypeAddrVector &devices) {
4466 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004467}
4468
Jiabin Huang3b98d322020-09-03 17:54:16 +00004469status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4470 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4471 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4472 dumpAudioDeviceTypeAddrVector(devices).c_str());
4473
Mikhail Naganov55773032020-10-01 15:08:13 -07004474 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004475 return BAD_VALUE;
4476 }
4477 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4478 ALOGW_IF(status != NO_ERROR,
4479 "Engine could not set preferred devices %s for audio source %d role %d",
4480 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4481
4482 return status;
4483}
4484
4485status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4486 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4487 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4488 dumpAudioDeviceTypeAddrVector(devices).c_str());
4489
Mikhail Naganov55773032020-10-01 15:08:13 -07004490 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004491 return BAD_VALUE;
4492 }
4493 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4494 ALOGW_IF(status != NO_ERROR,
4495 "Engine could not add preferred devices %s for audio source %d role %d",
4496 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4497
Eric Laurent2517af32020-11-25 15:31:27 +01004498 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004499 return status;
4500}
4501
4502status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4503 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4504{
4505 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4506 dumpAudioDeviceTypeAddrVector(devices).c_str());
4507
Eric Laurent78fedbf2023-03-09 14:40:44 +01004508 if (!areAllDevicesSupported(
4509 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004510 return BAD_VALUE;
4511 }
4512
4513 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4514 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004515 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004516 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004517 if (status == NO_ERROR) {
4518 updateInputRouting();
4519 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004520 return status;
4521}
4522
4523status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4524 device_role_t role) {
4525 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4526
4527 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004528 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004529 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004530 if (status == NO_ERROR) {
4531 updateInputRouting();
4532 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004533 return status;
4534}
4535
4536status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4537 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4538 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4539}
4540
Oscar Azucena90e77632019-11-27 17:12:28 -08004541status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004542 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004543 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004544 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4545 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004546 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004547 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4548 if (status != NO_ERROR) {
4549 ALOGE("%s() could not set device affinity for userId %d",
4550 __FUNCTION__, userId);
4551 return status;
4552 }
4553
4554 // reevaluate outputs for all devices
4555 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004556 changeOutputDevicesMuteState(devices);
4557 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4558 true /* skipDelays */);
4559 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004560
4561 return NO_ERROR;
4562}
4563
4564status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004565 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004566 AudioDeviceTypeAddrVector devices;
4567 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004568 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4569 if (status != NO_ERROR) {
4570 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4571 __FUNCTION__, userId);
4572 return status;
4573 }
4574
4575 // reevaluate outputs for all devices
4576 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004577 changeOutputDevicesMuteState(devices);
4578 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4579 true /* skipDelays */);
4580 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004581
4582 return NO_ERROR;
4583}
4584
Andy Hungc29d82b2018-10-05 12:23:17 -07004585void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004586{
Andy Hungc29d82b2018-10-05 12:23:17 -07004587 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004588 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004589 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004590 std::string stateLiteral;
4591 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004592 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004593 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4594 "communications", "media", "record", "dock", "system",
4595 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4596 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4597 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004598 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4599 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4600 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4601 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4602 dst->append(" (MANUAL: ");
4603 dumpManualSurroundFormats(dst);
4604 dst->append(")");
4605 }
4606 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004607 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004608 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4609 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004610 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004611 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004612
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004613 dst->append("\n");
4614 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4615 dst->append("\n");
4616 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004617 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004618 mOutputs.dump(dst);
4619 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004620 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004621 mAudioPatches.dump(dst);
4622 mPolicyMixes.dump(dst);
4623 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004624
Kevin Rocardb99cc752019-03-21 20:52:24 -07004625 dst->appendFormat(" AllowedCapturePolicies:\n");
4626 for (auto& policy : mAllowedCapturePolicies) {
4627 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4628 }
4629
jiabina84c3d32022-12-02 18:59:55 +00004630 dst->appendFormat(" Preferred mixer audio configuration:\n");
4631 for (const auto it : mPreferredMixerAttrInfos) {
4632 dst->appendFormat(" - device port id: %d\n", it.first);
4633 for (const auto preferredMixerInfoIt : it.second) {
4634 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4635 preferredMixerInfoIt.second->dump(dst);
4636 }
4637 }
4638
François Gaffiec005e562018-11-06 15:04:49 +01004639 dst->appendFormat("\nPolicy Engine dump:\n");
4640 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004641
4642 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4643 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4644 dst->appendFormat(" - device type: %s, driving stream %d\n",
4645 dumpDeviceTypes({it.first}).c_str(),
4646 mEngine->getVolumeGroupForAttributes(it.second));
4647 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004648}
4649
4650status_t AudioPolicyManager::dump(int fd)
4651{
4652 String8 result;
4653 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004654 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004655 return NO_ERROR;
4656}
4657
Kevin Rocardb99cc752019-03-21 20:52:24 -07004658status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4659{
4660 mAllowedCapturePolicies[uid] = capturePolicy;
4661 return NO_ERROR;
4662}
4663
Eric Laurente552edb2014-03-10 17:42:56 -07004664// This function checks for the parameters which can be offloaded.
4665// This can be enhanced depending on the capability of the DSP and policy
4666// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004667audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004668{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004669 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004670 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004671 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004672 offloadInfo.format,
4673 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4674 offloadInfo.has_video);
4675
jiabin2b9d5a12021-12-10 01:06:29 +00004676 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004677 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004678 }
4679
4680 // See if there is a profile to support this.
4681 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004682 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004683 offloadInfo.sample_rate,
4684 offloadInfo.format,
4685 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004686 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4687 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004688 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4689 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4690 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004691 if (profile == nullptr) {
4692 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4693 }
4694 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4695 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4696 }
4697 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004698}
4699
Michael Chana94fbb22018-04-24 14:31:19 +10004700bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4701 const audio_attributes_t& attributes) {
4702 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004703 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004704 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4705 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004706 config.sample_rate,
4707 config.format,
4708 config.channel_mask,
4709 output_flags,
4710 true /* directOnly */);
4711 ALOGV("%s() profile %sfound with name: %s, "
4712 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4713 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004714 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004715 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004716
4717 // also try the MSD module if compatible profile not found
4718 if (profile == nullptr) {
4719 profile = getMsdProfileForOutput(outputDevices,
4720 config.sample_rate,
4721 config.format,
4722 config.channel_mask,
4723 output_flags,
4724 true /* directOnly */);
4725 ALOGV("%s() MSD profile %sfound with name: %s, "
4726 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4727 __FUNCTION__, profile != 0 ? "" : "NOT ",
4728 (profile != 0 ? profile->getTagName().c_str() : "null"),
4729 config.sample_rate, config.format, config.channel_mask, output_flags);
4730 }
4731 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004732}
4733
jiabin2b9d5a12021-12-10 01:06:29 +00004734bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4735 bool durationIgnored) {
4736 if (mMasterMono) {
4737 return false; // no offloading if mono is set.
4738 }
4739
4740 // Check if offload has been disabled
4741 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4742 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4743 return false;
4744 }
4745
4746 // Check if stream type is music, then only allow offload as of now.
4747 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4748 {
4749 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4750 return false;
4751 }
4752
4753 //TODO: enable audio offloading with video when ready
4754 const bool allowOffloadWithVideo =
4755 property_get_bool("audio.offload.video", false /* default_value */);
4756 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4757 ALOGV("%s: has_video == true, returning false", __func__);
4758 return false;
4759 }
4760
4761 //If duration is less than minimum value defined in property, return false
4762 const int min_duration_secs = property_get_int32(
4763 "audio.offload.min.duration.secs", -1 /* default_value */);
4764 if (!durationIgnored) {
4765 if (min_duration_secs >= 0) {
4766 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4767 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4768 __func__, min_duration_secs);
4769 return false;
4770 }
4771 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4772 ALOGV("%s: Offload denied by duration < default min(=%u)",
4773 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4774 return false;
4775 }
4776 }
4777
4778 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4779 // creating an offloaded track and tearing it down immediately after start when audioflinger
4780 // detects there is an active non offloadable effect.
4781 // FIXME: We should check the audio session here but we do not have it in this context.
4782 // This may prevent offloading in rare situations where effects are left active by apps
4783 // in the background.
4784 if (mEffects.isNonOffloadableEffectEnabled()) {
4785 return false;
4786 }
4787
4788 return true;
4789}
4790
4791audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4792 const audio_config_t *config) {
4793 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4794 offloadInfo.format = config->format;
4795 offloadInfo.sample_rate = config->sample_rate;
4796 offloadInfo.channel_mask = config->channel_mask;
4797 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4798 offloadInfo.has_video = false;
4799 offloadInfo.is_streaming = false;
4800 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4801
4802 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4803 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4804 audio_flags_to_audio_output_flags(attr->flags, &flags);
4805 // only retain flags that will drive compressed offload or passthrough
4806 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4807 if (offloadPossible) {
4808 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4809 }
4810 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4811
Dorin Drimusfae3c642022-03-17 18:36:30 +01004812 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004813 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004814 DeviceVector outputDevices = engineOutputDevices;
4815 // the MSD module checks for different conditions and output devices
4816 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4817 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4818 continue;
4819 }
4820 outputDevices = getMsdAudioOutDevices();
4821 }
jiabin2b9d5a12021-12-10 01:06:29 +00004822 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004823 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004824 config->sample_rate, nullptr /*updatedSamplingRate*/,
4825 config->format, nullptr /*updatedFormat*/,
4826 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004827 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004828 continue;
4829 }
4830 // reject profiles not corresponding to a device currently available
4831 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4832 continue;
4833 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004834 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4835 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004836 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004837 != AUDIO_DIRECT_NOT_SUPPORTED) {
4838 // Already reports offload gapless supported. No need to report offload support.
4839 continue;
4840 }
4841 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4842 != AUDIO_OUTPUT_FLAG_NONE) {
4843 // If offload gapless is reported, no need to report offload support.
4844 directMode = (audio_direct_mode_t) ((directMode &
4845 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4846 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4847 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004848 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004849 }
4850 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004851 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004852 }
4853 }
4854 }
4855 return directMode;
4856}
4857
Dorin Drimusf2196d82022-01-03 12:11:18 +01004858status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4859 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004860 if (mEffects.isNonOffloadableEffectEnabled()) {
4861 return OK;
4862 }
jiabinf1c73972022-04-14 16:28:52 -07004863 DeviceVector devices;
4864 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004865 if (status != OK) {
4866 return status;
4867 }
4868 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4869 if (devices.empty()) {
4870 return OK; // no output devices for the attributes
4871 }
jiabinf1c73972022-04-14 16:28:52 -07004872 return getProfilesForDevices(devices, audioProfilesVector,
4873 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004874}
4875
jiabina84c3d32022-12-02 18:59:55 +00004876status_t AudioPolicyManager::getSupportedMixerAttributes(
4877 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4878 ALOGV("%s, portId=%d", __func__, portId);
4879 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4880 if (deviceDescriptor == nullptr) {
4881 ALOGE("%s the requested device is currently unavailable", __func__);
4882 return BAD_VALUE;
4883 }
jiabin96daffc2023-05-11 17:51:55 +00004884 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4885 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4886 deviceDescriptor->type());
4887 return BAD_VALUE;
4888 }
jiabina84c3d32022-12-02 18:59:55 +00004889 for (const auto& hwModule : mHwModules) {
4890 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4891 if (curProfile->supportsDevice(deviceDescriptor)) {
4892 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4893 }
4894 }
4895 }
4896 return NO_ERROR;
4897}
4898
4899status_t AudioPolicyManager::setPreferredMixerAttributes(
4900 const audio_attributes_t *attr,
4901 audio_port_handle_t portId,
4902 uid_t uid,
4903 const audio_mixer_attributes_t *mixerAttributes) {
4904 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4905 "mixerBehavior=%d}, uid=%d, portId=%u",
4906 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4907 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4908 mixerAttributes->mixer_behavior, uid, portId);
4909 if (attr->usage != AUDIO_USAGE_MEDIA) {
4910 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4911 return BAD_VALUE;
4912 }
4913 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4914 if (deviceDescriptor == nullptr) {
4915 ALOGE("%s the requested device is currently unavailable", __func__);
4916 return BAD_VALUE;
4917 }
4918 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4919 ALOGE("%s(%d), type=%d, is not a usb output device",
4920 __func__, portId, deviceDescriptor->type());
4921 return BAD_VALUE;
4922 }
4923
4924 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4925 audio_flags_to_audio_output_flags(attr->flags, &flags);
4926 flags = (audio_output_flags_t) (flags |
4927 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4928 sp<IOProfile> profile = nullptr;
4929 DeviceVector devices(deviceDescriptor);
4930 for (const auto& hwModule : mHwModules) {
4931 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4932 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004933 && curProfile->getCompatibilityScore(
4934 devices,
4935 mixerAttributes->config.sample_rate,
4936 nullptr /*updatedSamplingRate*/,
4937 mixerAttributes->config.format,
4938 nullptr /*updatedFormat*/,
4939 mixerAttributes->config.channel_mask,
4940 nullptr /*updatedChannelMask*/,
4941 flags,
4942 false /*exactMatchRequiredForInputFlags*/)
4943 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004944 profile = curProfile;
4945 break;
4946 }
4947 }
4948 }
4949 if (profile == nullptr) {
4950 ALOGE("%s, there is no compatible profile found", __func__);
4951 return BAD_VALUE;
4952 }
4953
4954 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4955 sp<PreferredMixerAttributesInfo>::make(
4956 uid, portId, profile, flags, *mixerAttributes);
4957 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4958 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4959
4960 // If 1) there is any client from the preferred mixer configuration owner that is currently
4961 // active and matches the strategy and 2) current output is on the preferred device and the
4962 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4963 // configuration.
4964 std::vector<audio_io_handle_t> outputsToReopen;
4965 for (size_t i = 0; i < mOutputs.size(); i++) {
4966 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004967 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4968 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004969 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004970 } else {
4971 for (const auto &client: output->getActiveClients()) {
4972 if (client->uid() == uid && client->strategy() == strategy) {
4973 client->setIsInvalid();
4974 outputsToReopen.push_back(output->mIoHandle);
4975 }
jiabina84c3d32022-12-02 18:59:55 +00004976 }
4977 }
4978 }
4979 }
4980 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4981 config.sample_rate = mixerAttributes->config.sample_rate;
4982 config.channel_mask = mixerAttributes->config.channel_mask;
4983 config.format = mixerAttributes->config.format;
4984 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004985 sp<SwAudioOutputDescriptor> desc =
4986 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4987 if (desc == nullptr) {
4988 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4989 continue;
4990 }
jiabin220eea12024-05-17 17:55:20 +00004991 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004992 }
4993
4994 return NO_ERROR;
4995}
4996
4997sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004998 audio_port_handle_t devicePortId,
4999 product_strategy_t strategy,
5000 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005001 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5002 if (it == mPreferredMixerAttrInfos.end()) {
5003 return nullptr;
5004 }
jiabind9a58d32023-06-01 17:57:30 +00005005 if (activeBitPerfectPreferred) {
5006 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005007 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005008 return info;
5009 }
5010 }
jiabina84c3d32022-12-02 18:59:55 +00005011 }
jiabind9a58d32023-06-01 17:57:30 +00005012 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5013 return strategyMatchedMixerAttrInfoIt == it->second.end()
5014 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005015}
5016
5017status_t AudioPolicyManager::getPreferredMixerAttributes(
5018 const audio_attributes_t *attr,
5019 audio_port_handle_t portId,
5020 audio_mixer_attributes_t* mixerAttributes) {
5021 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5022 portId, mEngine->getProductStrategyForAttributes(*attr));
5023 if (info == nullptr) {
5024 return NAME_NOT_FOUND;
5025 }
5026 *mixerAttributes = info->getMixerAttributes();
5027 return NO_ERROR;
5028}
5029
5030status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5031 audio_port_handle_t portId,
5032 uid_t uid) {
5033 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5034 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5035 if (preferredMixerAttrInfo == nullptr) {
5036 return NAME_NOT_FOUND;
5037 }
5038 if (preferredMixerAttrInfo->getUid() != uid) {
5039 ALOGE("%s, requested uid=%d, owned uid=%d",
5040 __func__, uid, preferredMixerAttrInfo->getUid());
5041 return PERMISSION_DENIED;
5042 }
5043 mPreferredMixerAttrInfos[portId].erase(strategy);
5044 if (mPreferredMixerAttrInfos[portId].empty()) {
5045 mPreferredMixerAttrInfos.erase(portId);
5046 }
5047
5048 // Reconfig existing output
5049 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5050 for (size_t i = 0; i < mOutputs.size(); i++) {
5051 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5052 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5053 }
5054 }
5055 for (const auto output : potentialOutputsToReopen) {
5056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5057 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5058 preferredMixerAttrInfo->getFlags())) {
5059 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5060 }
5061 }
5062 return NO_ERROR;
5063}
5064
Eric Laurent6a94d692014-05-20 11:18:06 -07005065status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5066 audio_port_type_t type,
5067 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005068 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 unsigned int *generation)
5070{
jiabin19cdba52020-11-24 11:28:58 -08005071 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5072 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 return BAD_VALUE;
5074 }
5075 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005076 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005077 *num_ports = 0;
5078 }
5079
5080 size_t portsWritten = 0;
5081 size_t portsMax = *num_ports;
5082 *num_ports = 0;
5083 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005084 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5085 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005087 for (const auto& dev : mAvailableOutputDevices) {
5088 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005089 continue;
5090 }
5091 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005092 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005093 }
5094 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005095 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 }
5097 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005098 for (const auto& dev : mAvailableInputDevices) {
5099 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005100 continue;
5101 }
5102 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005103 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005104 }
5105 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005106 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 }
5108 }
5109 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5110 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5111 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5112 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5113 }
5114 *num_ports += mInputs.size();
5115 }
5116 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005117 size_t numOutputs = 0;
5118 for (size_t i = 0; i < mOutputs.size(); i++) {
5119 if (!mOutputs[i]->isDuplicated()) {
5120 numOutputs++;
5121 if (portsWritten < portsMax) {
5122 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5123 }
5124 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 }
Eric Laurent84c70242014-06-23 08:46:27 -07005126 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 }
5128 }
jiabina84c3d32022-12-02 18:59:55 +00005129
Eric Laurent6a94d692014-05-20 11:18:06 -07005130 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005131 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 return NO_ERROR;
5133}
5134
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005135status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5136 std::vector<media::AudioPortFw>* _aidl_return) {
5137 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5138 audio_port_v7 port;
5139 dev->toAudioPort(&port);
5140 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5141 _aidl_return->push_back(std::move(aidlPort));
5142 return OK;
5143 };
5144
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005145 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005146 for (const auto& dev : module->getDeclaredDevices()) {
5147 if (role == media::AudioPortRole::NONE ||
5148 ((role == media::AudioPortRole::SOURCE)
5149 == audio_is_input_device(dev->type()))) {
5150 RETURN_STATUS_IF_ERROR(pushPort(dev));
5151 }
5152 }
5153 }
5154 return OK;
5155}
5156
jiabin19cdba52020-11-24 11:28:58 -08005157status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005158{
Eric Laurent99fcae42018-05-17 16:59:18 -07005159 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5160 return BAD_VALUE;
5161 }
5162 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5163 if (dev != 0) {
5164 dev->toAudioPort(port);
5165 return NO_ERROR;
5166 }
5167 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5168 if (dev != 0) {
5169 dev->toAudioPort(port);
5170 return NO_ERROR;
5171 }
5172 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5173 if (out != 0) {
5174 out->toAudioPort(port);
5175 return NO_ERROR;
5176 }
5177 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5178 if (in != 0) {
5179 in->toAudioPort(port);
5180 return NO_ERROR;
5181 }
5182 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005183}
5184
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005185status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5186 audio_patch_handle_t *handle,
5187 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005188{
François Gaffieafd4cea2019-11-18 15:50:22 +01005189 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 if (handle == NULL || patch == NULL) {
5191 return BAD_VALUE;
5192 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005193 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005194 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005195 return BAD_VALUE;
5196 }
5197 // only one source per audio patch supported for now
5198 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 return INVALID_OPERATION;
5200 }
Eric Laurent874c42872014-08-08 15:13:39 -07005201 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 return INVALID_OPERATION;
5203 }
Eric Laurent874c42872014-08-08 15:13:39 -07005204 for (size_t i = 0; i < patch->num_sinks; i++) {
5205 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5206 return INVALID_OPERATION;
5207 }
5208 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005209
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005210 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5211 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5212 if (srcDevice == nullptr || sinkDevice == nullptr) {
5213 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5214 return BAD_VALUE;
5215 }
5216 ALOGV("%s between source %s and sink %s", __func__,
5217 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5218 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5219 // Default attributes, default volume priority, not to infer with non raw audio patches.
5220 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5221 const struct audio_port_config *source = &patch->sources[0];
5222 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005223 new SourceClientDescriptor(
5224 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5225 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005226 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005227 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005228
5229 status_t status =
5230 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5231
5232 if (status != NO_ERROR) {
5233 return INVALID_OPERATION;
5234 }
5235 mAudioSources.add(portId, sourceDesc);
5236 return NO_ERROR;
5237}
5238
5239status_t AudioPolicyManager::connectAudioSourceToSink(
5240 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5241 const struct audio_patch *patch,
5242 audio_patch_handle_t &handle,
5243 uid_t uid, uint32_t delayMs)
5244{
5245 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5246 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5247 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5248 return INVALID_OPERATION;
5249 }
5250 sourceDesc->connect(handle, sinkDevice);
5251 if (isMsdPatch(handle)) {
5252 return NO_ERROR;
5253 }
5254 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5255 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5256 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5257 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5258 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5259 goto FailurePatchAdded;
5260 }
5261 status = swOutput->start();
5262 if (status != NO_ERROR) {
5263 goto FailureSourceAdded;
5264 }
5265 swOutput->addClient(sourceDesc);
5266 status = startSource(swOutput, sourceDesc, &delayMs);
5267 if (status != NO_ERROR) {
5268 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5269 goto FailureSourceActive;
5270 }
5271 if (delayMs != 0) {
5272 usleep(delayMs * 1000);
5273 }
5274 return NO_ERROR;
5275
5276FailureSourceActive:
5277 swOutput->stop();
5278 releaseOutput(sourceDesc->portId());
5279FailureSourceAdded:
5280 sourceDesc->setSwOutput(nullptr);
5281FailurePatchAdded:
5282 releaseAudioPatchInternal(handle);
5283 return INVALID_OPERATION;
5284}
5285
5286status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5287 audio_patch_handle_t *handle,
5288 uid_t uid, uint32_t delayMs,
5289 const sp<SourceClientDescriptor>& sourceDesc)
5290{
5291 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 sp<AudioPatch> patchDesc;
5293 ssize_t index = mAudioPatches.indexOfKey(*handle);
5294
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5296 patch->sources[0].role,
5297 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005298#if LOG_NDEBUG == 0
5299 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5301 patch->sinks[i].role,
5302 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005303 }
5304#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005305
5306 if (index >= 0) {
5307 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005308 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5309 __func__, mUidCached, patchDesc->getUid(), uid);
5310 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 return INVALID_OPERATION;
5312 }
5313 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005314 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 }
5316
5317 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005318 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005320 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 return BAD_VALUE;
5322 }
Eric Laurent84c70242014-06-23 08:46:27 -07005323 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5324 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005325 if (patchDesc != 0) {
5326 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005327 ALOGV("%s source id differs for patch current id %d new id %d",
5328 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 return BAD_VALUE;
5330 }
5331 }
Eric Laurent874c42872014-08-08 15:13:39 -07005332 DeviceVector devices;
5333 for (size_t i = 0; i < patch->num_sinks; i++) {
5334 // Only support mix to devices connection
5335 // TODO add support for mix to mix connection
5336 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005337 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005338 return INVALID_OPERATION;
5339 }
5340 sp<DeviceDescriptor> devDesc =
5341 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5342 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005343 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005344 return BAD_VALUE;
5345 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005346
jiabin66acc432024-02-06 00:57:36 +00005347 if (outputDesc->mProfile->getCompatibilityScore(
5348 DeviceVector(devDesc),
5349 patch->sources[0].sample_rate,
5350 nullptr, // updatedSamplingRate
5351 patch->sources[0].format,
5352 nullptr, // updatedFormat
5353 patch->sources[0].channel_mask,
5354 nullptr, // updatedChannelMask
5355 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005356 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005357 return INVALID_OPERATION;
5358 }
5359 devices.add(devDesc);
5360 }
5361 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 return INVALID_OPERATION;
5363 }
Eric Laurent874c42872014-08-08 15:13:39 -07005364
Eric Laurent6a94d692014-05-20 11:18:06 -07005365 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005366 ALOGV("%s setting device %s on output %d",
5367 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305368 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 index = mAudioPatches.indexOfKey(*handle);
5370 if (index >= 0) {
5371 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005372 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 }
5374 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005375 patchDesc->setUid(uid);
5376 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005377 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005378 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005379 return INVALID_OPERATION;
5380 }
5381 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5382 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5383 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005384 // only one sink supported when connecting an input device to a mix
5385 if (patch->num_sinks > 1) {
5386 return INVALID_OPERATION;
5387 }
François Gaffie53615e22015-03-19 09:24:12 +01005388 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 if (inputDesc == NULL) {
5390 return BAD_VALUE;
5391 }
5392 if (patchDesc != 0) {
5393 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5394 return BAD_VALUE;
5395 }
5396 }
François Gaffie11d30102018-11-02 16:09:09 +01005397 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005398 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005399 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005400 return BAD_VALUE;
5401 }
5402
jiabin66acc432024-02-06 00:57:36 +00005403 if (inputDesc->mProfile->getCompatibilityScore(
5404 DeviceVector(device),
5405 patch->sinks[0].sample_rate,
5406 nullptr, /*updatedSampleRate*/
5407 patch->sinks[0].format,
5408 nullptr, /*updatedFormat*/
5409 patch->sinks[0].channel_mask,
5410 nullptr, /*updatedChannelMask*/
5411 // FIXME for the parameter type,
5412 // and the NONE
5413 (audio_output_flags_t)
5414 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005415 return INVALID_OPERATION;
5416 }
5417 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005418 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005419 device->toString().c_str(), inputDesc->mIoHandle);
5420 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 index = mAudioPatches.indexOfKey(*handle);
5422 if (index >= 0) {
5423 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005424 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005425 }
5426 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005427 patchDesc->setUid(uid);
5428 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005429 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005430 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005431 return INVALID_OPERATION;
5432 }
5433 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5434 // device to device connection
5435 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005436 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005437 return BAD_VALUE;
5438 }
5439 }
François Gaffie11d30102018-11-02 16:09:09 +01005440 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005441 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005442 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005443 return BAD_VALUE;
5444 }
Eric Laurent874c42872014-08-08 15:13:39 -07005445
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 //update source and sink with our own data as the data passed in the patch may
5447 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005448 PatchBuilder patchBuilder;
5449 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005450
5451 // if first sink is to MSD, establish single MSD patch
5452 if (getMsdAudioOutDevices().contains(
5453 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5454 ALOGV("%s patching to MSD", __FUNCTION__);
5455 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5456 goto installPatch;
5457 }
5458
François Gaffieafd4cea2019-11-18 15:50:22 +01005459 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5460 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005461
Eric Laurent874c42872014-08-08 15:13:39 -07005462 for (size_t i = 0; i < patch->num_sinks; i++) {
5463 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005465 return INVALID_OPERATION;
5466 }
François Gaffie11d30102018-11-02 16:09:09 +01005467 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005468 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005469 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005470 return BAD_VALUE;
5471 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005472 audio_port_config sinkPortConfig = {};
5473 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5474 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005475
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005476 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5477 // volume management purpose (tracking activity)
5478 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5479 // in config XML to reach the sink so that is can be declared as available.
5480 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005481 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005482 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005483 // take care of dynamic routing for SwOutput selection,
5484 audio_attributes_t attributes = sourceDesc->attributes();
5485 audio_stream_type_t stream = sourceDesc->stream();
5486 audio_attributes_t resultAttr;
5487 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5488 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005489 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5490 config.channel_mask =
5491 (audio_channel_mask_get_representation(sourceMask)
5492 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5493 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005494 config.format = sourceDesc->config().format;
5495 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5496 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5497 bool isRequestedDeviceForExclusiveUse = false;
5498 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005499 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005500 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005501 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5502 &stream, sourceDesc->uid(), &config, &flags,
5503 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005504 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005505 if (output == AUDIO_IO_HANDLE_NONE) {
5506 ALOGV("%s no output for device %s",
5507 __FUNCTION__, sinkDevice->toString().c_str());
5508 return INVALID_OPERATION;
5509 }
5510 outputDesc = mOutputs.valueFor(output);
5511 if (outputDesc->isDuplicated()) {
5512 ALOGE("%s output is duplicated", __func__);
5513 return INVALID_OPERATION;
5514 }
François Gaffie7e39df22022-04-26 12:48:49 +02005515 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5516 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005517 } else {
5518 // Same for "raw patches" aka created from createAudioPatch API
5519 SortedVector<audio_io_handle_t> outputs =
5520 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5521 // if the sink device is reachable via an opened output stream, request to
5522 // go via this output stream by adding a second source to the patch
5523 // description
5524 output = selectOutput(outputs);
5525 if (output == AUDIO_IO_HANDLE_NONE) {
5526 ALOGE("%s no output available for internal patch sink", __func__);
5527 return INVALID_OPERATION;
5528 }
5529 outputDesc = mOutputs.valueFor(output);
5530 if (outputDesc->isDuplicated()) {
5531 ALOGV("%s output for device %s is duplicated",
5532 __func__, sinkDevice->toString().c_str());
5533 return INVALID_OPERATION;
5534 }
François Gaffie7e39df22022-04-26 12:48:49 +02005535 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005536 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005537 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005538 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005539 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005540 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005541 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5542 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005543 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5544 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005545 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005546 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005547 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005548 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005549 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005550 return INVALID_OPERATION;
5551 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005552 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005553 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005554 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005555 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005556 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005557 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005558 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005559 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5560 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005561 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005562 }
Eric Laurent83b88082014-06-20 18:31:16 -07005563 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005564 }
5565 // TODO: check from routing capabilities in config file and other conflicting patches
5566
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005567installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005568 status_t status = installPatch(
5569 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005570 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005571 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005572 return INVALID_OPERATION;
5573 }
5574 } else {
5575 return BAD_VALUE;
5576 }
5577 } else {
5578 return BAD_VALUE;
5579 }
5580 return NO_ERROR;
5581}
5582
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005583status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005584{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005585 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005586 ssize_t index = mAudioPatches.indexOfKey(handle);
5587
5588 if (index < 0) {
5589 return BAD_VALUE;
5590 }
5591 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005592 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5593 __func__, mUidCached, patchDesc->getUid(), uid);
5594 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005595 return INVALID_OPERATION;
5596 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005597 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5598 for (size_t i = 0; i < mAudioSources.size(); i++) {
5599 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5600 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5601 portId = sourceDesc->portId();
5602 break;
5603 }
5604 }
5605 return portId != AUDIO_PORT_HANDLE_NONE ?
5606 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005607}
Eric Laurent6a94d692014-05-20 11:18:06 -07005608
François Gaffieafd4cea2019-11-18 15:50:22 +01005609status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005610 uint32_t delayMs,
5611 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005612{
5613 ALOGV("%s patch %d", __func__, handle);
5614 if (mAudioPatches.indexOfKey(handle) < 0) {
5615 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5616 return BAD_VALUE;
5617 }
5618 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005619 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005620 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005621 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005622 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005623 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005624 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005625 return BAD_VALUE;
5626 }
5627
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305628 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005629 getNewOutputDevices(outputDesc, true /*fromCache*/),
5630 true,
5631 0,
5632 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005633 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5634 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005635 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005636 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005637 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005638 return BAD_VALUE;
5639 }
5640 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005641 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005642 true,
5643 NULL);
5644 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005645 status_t status =
5646 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5647 ALOGV("%s patch panel returned %d patchHandle %d",
5648 __func__, status, patchDesc->getAfHandle());
5649 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005650 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005651 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005652 // SW or HW Bridge
5653 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5654 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005655 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005656 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5657 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5658 outputDesc = sourceDesc->swOutput().promote();
5659 }
5660 if (outputDesc == nullptr) {
5661 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5662 // releaseOutput has already called closeOutput in case of direct output
5663 return NO_ERROR;
5664 }
François Gaffie7e39df22022-04-26 12:48:49 +02005665 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005666 // While using a HwBridge, force reconsidering device only if not reusing an existing
5667 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005668 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005669 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5670 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5671 // Reconsider device only for cases:
5672 // 1 / Active Output
5673 // 2 / Inactive Output previously hosting HwBridge
5674 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5675 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5676 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305677 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005678 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5679 outputDesc->devices(),
5680 force,
5681 0,
5682 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005683 } else {
5684 return BAD_VALUE;
5685 }
5686 } else {
5687 return BAD_VALUE;
5688 }
5689 return NO_ERROR;
5690}
5691
5692status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5693 struct audio_patch *patches,
5694 unsigned int *generation)
5695{
François Gaffie53615e22015-03-19 09:24:12 +01005696 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005697 return BAD_VALUE;
5698 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005699 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005700 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005701}
5702
Eric Laurente1715a42014-05-20 11:30:42 -07005703status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005704{
Eric Laurente1715a42014-05-20 11:30:42 -07005705 ALOGV("setAudioPortConfig()");
5706
5707 if (config == NULL) {
5708 return BAD_VALUE;
5709 }
5710 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5711 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005712 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5713 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005714 }
5715
Eric Laurenta121f902014-06-03 13:32:54 -07005716 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005717 if (config->type == AUDIO_PORT_TYPE_MIX) {
5718 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005719 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005720 if (outputDesc == NULL) {
5721 return BAD_VALUE;
5722 }
Eric Laurent84c70242014-06-23 08:46:27 -07005723 ALOG_ASSERT(!outputDesc->isDuplicated(),
5724 "setAudioPortConfig() called on duplicated output %d",
5725 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005726 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005727 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005728 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005729 if (inputDesc == NULL) {
5730 return BAD_VALUE;
5731 }
Eric Laurenta121f902014-06-03 13:32:54 -07005732 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005733 } else {
5734 return BAD_VALUE;
5735 }
5736 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5737 sp<DeviceDescriptor> deviceDesc;
5738 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5739 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5740 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5741 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5742 } else {
5743 return BAD_VALUE;
5744 }
5745 if (deviceDesc == NULL) {
5746 return BAD_VALUE;
5747 }
Eric Laurenta121f902014-06-03 13:32:54 -07005748 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005749 } else {
5750 return BAD_VALUE;
5751 }
5752
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005753 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005754 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5755 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005756 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005757 audioPortConfig->toAudioPortConfig(&newConfig, config);
5758 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005759 }
Eric Laurenta121f902014-06-03 13:32:54 -07005760 if (status != NO_ERROR) {
5761 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005762 }
Eric Laurente1715a42014-05-20 11:30:42 -07005763
5764 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005765}
5766
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005767void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5768{
Eric Laurentd60560a2015-04-10 11:31:20 -07005769 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005770 clearAudioPatches(uid);
5771 clearSessionRoutes(uid);
5772}
5773
Eric Laurent6a94d692014-05-20 11:18:06 -07005774void AudioPolicyManager::clearAudioPatches(uid_t uid)
5775{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005776 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005777 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005778 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005779 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005780 }
5781 }
5782}
5783
François Gaffiec005e562018-11-06 15:04:49 +01005784void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005785{
François Gaffiec005e562018-11-06 15:04:49 +01005786 // Take the first attributes following the product strategy as it is used to retrieve the routed
5787 // device. All attributes wihin a strategy follows the same "routing strategy"
5788 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5789 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005790 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005791 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005792 for (size_t j = 0; j < mOutputs.size(); j++) {
5793 if (mOutputs.keyAt(j) == ouptutToSkip) {
5794 continue;
5795 }
5796 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005797 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005798 continue;
5799 }
5800 // If the default device for this strategy is on another output mix,
5801 // invalidate all tracks in this strategy to force re connection.
5802 // Otherwise select new device on the output mix.
5803 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005804 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005805 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005806 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005807 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005808 // If the device is using preferred mixer attributes, the output need to reopen
5809 // with default configuration when the new selected devices are different from
5810 // current routing devices.
5811 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5812 continue;
5813 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305814 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005815 }
5816 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005817 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005818}
5819
5820void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5821{
5822 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005823 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005824 for (size_t i = 0; i < mOutputs.size(); i++) {
5825 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005826 for (const auto& client : outputDesc->getClientIterable()) {
5827 if (client->hasPreferredDevice() && client->uid() == uid) {
5828 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005829 auto clientStrategy = client->strategy();
5830 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5831 end(affectedStrategies)) {
5832 continue;
5833 }
5834 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005835 }
5836 }
5837 }
5838 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005839 for (const auto& strategy : affectedStrategies) {
5840 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005841 }
5842
5843 // remove input routes associated with this uid
5844 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005845 for (size_t i = 0; i < mInputs.size(); i++) {
5846 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005847 for (const auto& client : inputDesc->getClientIterable()) {
5848 if (client->hasPreferredDevice() && client->uid() == uid) {
5849 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5850 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005851 }
5852 }
5853 }
5854 // reroute inputs if necessary
5855 SortedVector<audio_io_handle_t> inputsToClose;
5856 for (size_t i = 0; i < mInputs.size(); i++) {
5857 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005858 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005859 inputsToClose.add(inputDesc->mIoHandle);
5860 }
5861 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005862 for (const auto& input : inputsToClose) {
5863 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005864 }
5865}
5866
Eric Laurentd60560a2015-04-10 11:31:20 -07005867void AudioPolicyManager::clearAudioSources(uid_t uid)
5868{
5869 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005870 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5871 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005872 stopAudioSource(mAudioSources.keyAt(i));
5873 }
5874 }
5875}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005876
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005877status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5878 audio_io_handle_t *ioHandle,
5879 audio_devices_t *device)
5880{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005881 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5882 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005883 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005884 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5885 if (deviceDesc == nullptr) {
5886 return INVALID_OPERATION;
5887 }
5888 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005889
François Gaffiedf372692015-03-19 10:43:27 +01005890 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005891}
5892
Eric Laurentd60560a2015-04-10 11:31:20 -07005893status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005894 const audio_attributes_t *attributes,
5895 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005896 uid_t uid) {
5897 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005898 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005899}
5900
5901status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5902 const audio_attributes_t *attributes,
5903 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005904 uid_t uid, bool internal, bool isCallRx,
5905 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005906{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005907 ALOGV("%s", __FUNCTION__);
5908 *portId = AUDIO_PORT_HANDLE_NONE;
5909
5910 if (source == NULL || attributes == NULL || portId == NULL) {
5911 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5912 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005913 return BAD_VALUE;
5914 }
5915
Eric Laurentd60560a2015-04-10 11:31:20 -07005916 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5917 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005918 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5919 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005920 return INVALID_OPERATION;
5921 }
5922
François Gaffie11d30102018-11-02 16:09:09 +01005923 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005924 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005925 String8(source->ext.device.address),
5926 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005927 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005928 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005929 return BAD_VALUE;
5930 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005931
jiabin4ef93452019-09-10 14:29:54 -07005932 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005933
François Gaffieaaac0fd2018-11-22 17:56:39 +01005934 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005935 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005936 mEngine->getStreamTypeForAttributes(*attributes),
5937 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005938 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005939
David Lif85c5e32024-07-01 13:14:10 +00005940 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005941 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005942 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005943 }
5944 return status;
5945}
5946
David Lif85c5e32024-07-01 13:14:10 +00005947status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5948 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005949{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005950 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005951
5952 // make sure we only have one patch per source.
5953 disconnectAudioSource(sourceDesc);
5954
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005955 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005956 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5957 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5958 sourceDesc->srcDevice()->type(),
5959 String8(sourceDesc->srcDevice()->address().c_str()),
5960 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005961 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005962 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005963 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005964 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005965 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5966 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5967 return INVALID_OPERATION;
5968 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005969 PatchBuilder patchBuilder;
5970 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5971 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005972
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005973 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00005974 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005975}
5976
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005977status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005978{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005979 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5980 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005981 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005982 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005983 return BAD_VALUE;
5984 }
5985 status_t status = disconnectAudioSource(sourceDesc);
5986
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005987 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005988 return status;
5989}
5990
Andy Hung2ddee192015-12-18 17:34:44 -08005991status_t AudioPolicyManager::setMasterMono(bool mono)
5992{
5993 if (mMasterMono == mono) {
5994 return NO_ERROR;
5995 }
5996 mMasterMono = mono;
5997 // if enabling mono we close all offloaded devices, which will invalidate the
5998 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5999 // for recreating the new AudioTrack as non-offloaded PCM.
6000 //
6001 // If disabling mono, we leave all tracks as is: we don't know which clients
6002 // and tracks are able to be recreated as offloaded. The next "song" should
6003 // play back offloaded.
6004 if (mMasterMono) {
6005 Vector<audio_io_handle_t> offloaded;
6006 for (size_t i = 0; i < mOutputs.size(); ++i) {
6007 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6008 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6009 offloaded.push(desc->mIoHandle);
6010 }
6011 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006012 for (const auto& handle : offloaded) {
6013 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006014 }
6015 }
6016 // update master mono for all remaining outputs
6017 for (size_t i = 0; i < mOutputs.size(); ++i) {
6018 updateMono(mOutputs.keyAt(i));
6019 }
6020 return NO_ERROR;
6021}
6022
6023status_t AudioPolicyManager::getMasterMono(bool *mono)
6024{
6025 *mono = mMasterMono;
6026 return NO_ERROR;
6027}
6028
Eric Laurentac9cef52017-06-09 15:46:26 -07006029float AudioPolicyManager::getStreamVolumeDB(
6030 audio_stream_type_t stream, int index, audio_devices_t device)
6031{
Vlad Popa9d482762024-06-21 16:40:23 -07006032 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6033 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006034}
6035
jiabin81772902018-04-02 17:52:27 -07006036status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6037 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006038 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006039{
Kriti Dang6537def2021-03-02 13:46:59 +01006040 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6041 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006042 return BAD_VALUE;
6043 }
Kriti Dang6537def2021-03-02 13:46:59 +01006044 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6045 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006046
6047 size_t formatsWritten = 0;
6048 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006049
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006050 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006051 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6052 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006053 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006054 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006055 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006056 bool formatEnabled = true;
6057 switch (forceUse) {
6058 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006059 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006060 break;
6061 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6062 formatEnabled = false;
6063 break;
6064 default: // AUTO or ALWAYS => true
6065 break;
jiabin81772902018-04-02 17:52:27 -07006066 }
6067 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6068 }
jiabin81772902018-04-02 17:52:27 -07006069 }
6070 return NO_ERROR;
6071}
6072
Kriti Dang6537def2021-03-02 13:46:59 +01006073status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6074 audio_format_t *surroundFormats) {
6075 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6076 return BAD_VALUE;
6077 }
6078 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6079 __func__, *numSurroundFormats, surroundFormats);
6080
6081 size_t formatsWritten = 0;
6082 size_t formatsMax = *numSurroundFormats;
6083 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6084
6085 // Return formats from all device profiles that have already been resolved by
6086 // checkOutputsForDevice().
6087 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6088 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6089 audio_devices_t deviceType = device->type();
6090 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6091 // returns formats reported by HDMI devices.
6092 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6093 continue;
6094 }
6095 // Formats reported by sink devices
6096 std::unordered_set<audio_format_t> formatset;
6097 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6098 formatset.insert(it->second.begin(), it->second.end());
6099 }
6100
6101 // Formats hard-coded in the in policy configuration file (if any).
6102 FormatVector encodedFormats = device->encodedFormats();
6103 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6104 // Filter the formats which are supported by the vendor hardware.
6105 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006106 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006107 formats.insert(*it);
6108 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006109 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006110 if (pair.second.count(*it) != 0) {
6111 formats.insert(pair.first);
6112 break;
6113 }
6114 }
6115 }
6116 }
6117 }
6118 *numSurroundFormats = formats.size();
6119 for (const auto& format: formats) {
6120 if (formatsWritten < formatsMax) {
6121 surroundFormats[formatsWritten++] = format;
6122 }
6123 }
6124 return NO_ERROR;
6125}
6126
jiabin81772902018-04-02 17:52:27 -07006127status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6128{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006129 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006130 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6131 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006132 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006133 return BAD_VALUE;
6134 }
6135
Mikhail Naganov100f0122018-11-29 11:22:16 -08006136 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6137 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006138 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006139 return INVALID_OPERATION;
6140 }
6141
Mikhail Naganov100f0122018-11-29 11:22:16 -08006142 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006143 return NO_ERROR;
6144 }
6145
Mikhail Naganov100f0122018-11-29 11:22:16 -08006146 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006147 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006148 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006149 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006150 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006151 }
6152 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006153 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006154 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006155 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006156 }
6157 }
6158
6159 sp<SwAudioOutputDescriptor> outputDesc;
6160 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006161 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6162 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006163 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6164 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006165 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006166 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006167 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6168 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6169 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006170 name.c_str(),
6171 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006172 if (status != NO_ERROR) {
6173 continue;
6174 }
6175 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6176 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6177 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006178 name.c_str(),
6179 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006180 profileUpdated |= (status == NO_ERROR);
6181 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006182 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006183 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006184 AUDIO_DEVICE_IN_HDMI);
6185 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6186 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006187 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006188 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006189 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6190 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6191 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006192 name.c_str(),
6193 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006194 if (status != NO_ERROR) {
6195 continue;
6196 }
6197 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6198 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6199 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006200 name.c_str(),
6201 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006202 profileUpdated |= (status == NO_ERROR);
6203 }
6204
jiabin81772902018-04-02 17:52:27 -07006205 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006206 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006207 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006208 }
6209
6210 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6211}
6212
Eric Laurent5ada82e2019-08-29 17:53:54 -07006213void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006214{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006215 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006216 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006217 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006218 }
6219}
6220
jiabin6012f912018-11-02 17:06:30 -07006221bool AudioPolicyManager::isHapticPlaybackSupported()
6222{
6223 for (const auto& hwModule : mHwModules) {
6224 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6225 for (const auto &outProfile : outputProfiles) {
6226 struct audio_port audioPort;
6227 outProfile->toAudioPort(&audioPort);
6228 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6229 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6230 return true;
6231 }
6232 }
6233 }
6234 }
6235 return false;
6236}
6237
Carter Hsu325a8eb2022-01-19 19:56:51 +08006238bool AudioPolicyManager::isUltrasoundSupported()
6239{
6240 bool hasUltrasoundOutput = false;
6241 bool hasUltrasoundInput = false;
6242 for (const auto& hwModule : mHwModules) {
6243 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6244 if (!hasUltrasoundOutput) {
6245 for (const auto &outProfile : outputProfiles) {
6246 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6247 hasUltrasoundOutput = true;
6248 break;
6249 }
6250 }
6251 }
6252
6253 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6254 if (!hasUltrasoundInput) {
6255 for (const auto &inputProfile : inputProfiles) {
6256 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6257 hasUltrasoundInput = true;
6258 break;
6259 }
6260 }
6261 }
6262
6263 if (hasUltrasoundOutput && hasUltrasoundInput)
6264 return true;
6265 }
6266 return false;
6267}
6268
Atneya Nair698f5ef2022-12-15 16:15:09 -08006269bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6270{
6271 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6272 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6273 for (const auto& hwModule : mHwModules) {
6274 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6275 for (const auto &inputProfile : inputProfiles) {
6276 if ((inputProfile->getFlags() & mask) == mask) {
6277 return true;
6278 }
6279 }
6280 }
6281 return false;
6282}
6283
Eric Laurent8340e672019-11-06 11:01:08 -08006284bool AudioPolicyManager::isCallScreenModeSupported()
6285{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006286 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006287}
6288
6289
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006290status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006291{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006292 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006293 if (!sourceDesc->isConnected()) {
6294 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6295 return NO_ERROR;
6296 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006297 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6298 if (swOutput != 0) {
6299 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006300 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006301 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006302 }
jiabinbce0c1d2020-10-05 11:20:18 -07006303 if (releaseOutput(sourceDesc->portId())) {
6304 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6305 // no need to release audio patch here but just return NO_ERROR.
6306 return NO_ERROR;
6307 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006308 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006309 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006310 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006311 // close Hwoutput and remove from mHwOutputs
6312 } else {
6313 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6314 }
6315 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006316 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006317 sourceDesc->disconnect();
6318 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006319}
6320
François Gaffiec005e562018-11-06 15:04:49 +01006321sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6322 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006323{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006324 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006325 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006326 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006327 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006328 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6329 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006330 source = sourceDesc;
6331 break;
6332 }
6333 }
6334 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006335}
6336
Eric Laurentb4f42a92022-01-17 17:37:31 +01006337bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006338 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006339 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006340{
6341 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6342 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006343 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006344 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006345 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6346 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6347 return false;
6348 }
6349 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6350 return false;
6351 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006352 }
6353
Eric Laurentd332bc82023-08-04 11:45:23 +02006354 // The caller can have the audio config criteria ignored by either passing a null ptr or
6355 // the AUDIO_CONFIG_INITIALIZER value.
6356 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006357 // some positional channel masks and PCM format and for stereo if low latency performance
6358 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006359
6360 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006361 static const bool stereo_spatialization_enabled =
6362 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006363 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006364 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006365 ? audio_channel_mask_contains_stereo(config->channel_mask)
6366 : audio_is_channel_mask_spatialized(config->channel_mask);
6367 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006368 return false;
6369 }
6370 if (!audio_is_linear_pcm(config->format)) {
6371 return false;
6372 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006373 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6374 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6375 return false;
6376 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006377 }
6378
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006379 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006380 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006381 if (profile == nullptr) {
6382 return false;
6383 }
6384
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006385 return true;
6386}
6387
Shunkai Yao4c3af932024-04-26 04:12:21 +00006388// The Spatializer output is compatible with Haptic use cases if:
6389// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6390// with client if client haptic channel bits were set, or
6391// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6392// including the haptic bits or creating the HapticGenerator effect for same session.
6393bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6394 const audio_config_t* config, audio_session_t sessionId) const {
6395 const auto clientHapticChannel =
6396 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6397 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6398 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6399
6400 if (threadOutputHapticChannel) {
6401 // check format and sampleRate match if client haptic channel mask exist
6402 if (clientHapticChannel) {
6403 return mSpatializerOutput->getFormat() == config->format &&
6404 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6405 }
6406 return true;
6407 } else {
6408 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6409 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6410 // HapticGenerator effect for this session) are not supported.
6411 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006412 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006413 }
6414}
6415
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006416void AudioPolicyManager::checkVirtualizerClientRoutes() {
6417 std::set<audio_stream_type_t> streamsToInvalidate;
6418 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006419 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6420 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006421 audio_attributes_t attr = client->attributes();
6422 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6423 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6424 audio_config_base_t clientConfig = client->config();
6425 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006426 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006427 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006428 streamsToInvalidate.insert(client->stream());
6429 }
6430 }
6431 }
6432
jiabinc44b3462022-12-08 12:52:31 -08006433 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006434}
6435
Eric Laurente191d1b2022-04-15 11:59:25 +02006436
6437bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6438 const sp<SwAudioOutputDescriptor>& outputDesc) {
6439 if (outputDesc->isDuplicated()) {
6440 return false;
6441 }
6442 DeviceVector devices = outputDesc->supportedDevices();
6443 for (size_t i = 0; i < mOutputs.size(); i++) {
6444 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6445 if (desc == outputDesc || desc->isDuplicated()) {
6446 continue;
6447 }
6448 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6449 if (!sharedDevices.isEmpty()
6450 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6451 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6452 return false;
6453 }
6454 }
6455 return true;
6456}
6457
6458
Eric Laurentfa0f6742021-08-17 18:39:44 +02006459status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006460 const audio_attributes_t *attr,
6461 audio_io_handle_t *output) {
6462 *output = AUDIO_IO_HANDLE_NONE;
6463
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006464 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6465 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6466 audio_config_t *configPtr = nullptr;
6467 audio_config_t config;
6468 if (mixerConfig != nullptr) {
6469 config = audio_config_initializer(mixerConfig);
6470 configPtr = &config;
6471 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006472 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006473 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006474 return BAD_VALUE;
6475 }
6476
6477 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006478 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006479 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006480 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006481 return BAD_VALUE;
6482 }
6483
Eric Laurente191d1b2022-04-15 11:59:25 +02006484 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006485 for (size_t i = 0; i < mOutputs.size(); i++) {
6486 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006487 if (!desc->isDuplicated()
6488 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6489 spatializerOutputs.push_back(desc);
6490 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006491 }
6492 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006493 mSpatializerOutput.clear();
6494 bool outputsChanged = false;
6495 for (const auto& desc : spatializerOutputs) {
6496 if (desc->mProfile == profile
6497 && (configPtr == nullptr
6498 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6499 mSpatializerOutput = desc;
6500 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6501 } else {
6502 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6503 " and devices %s", __func__, desc->mIoHandle,
6504 configPtr != nullptr ? configPtr->channel_mask : 0,
6505 devices.toString().c_str());
6506 closeOutput(desc->mIoHandle);
6507 outputsChanged = true;
6508 }
Eric Laurent39095982021-08-24 18:29:27 +02006509 }
6510
Eric Laurente191d1b2022-04-15 11:59:25 +02006511 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006512 sp<SwAudioOutputDescriptor> desc =
6513 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006514 if (desc != nullptr) {
6515 mSpatializerOutput = desc;
6516 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006517 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006518 }
6519
6520 checkVirtualizerClientRoutes();
6521
Eric Laurente191d1b2022-04-15 11:59:25 +02006522 if (outputsChanged) {
6523 mPreviousOutputs = mOutputs;
6524 mpClientInterface->onAudioPortListUpdate();
6525 }
6526
6527 if (mSpatializerOutput == nullptr) {
6528 ALOGV("%s could not open spatializer output with requested config", __func__);
6529 return BAD_VALUE;
6530 }
Eric Laurent39095982021-08-24 18:29:27 +02006531 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006532 ALOGV("%s returning new spatializer output %d", __func__, *output);
6533 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006534}
6535
Eric Laurentfa0f6742021-08-17 18:39:44 +02006536status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6537 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006538 return INVALID_OPERATION;
6539 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006540 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006541 return BAD_VALUE;
6542 }
Eric Laurent39095982021-08-24 18:29:27 +02006543
Eric Laurente191d1b2022-04-15 11:59:25 +02006544 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6545 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6546 closeOutput(mSpatializerOutput->mIoHandle);
6547 //from now on mSpatializerOutput is null
6548 checkVirtualizerClientRoutes();
6549 }
Eric Laurent39095982021-08-24 18:29:27 +02006550
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006551 return NO_ERROR;
6552}
6553
Eric Laurente552edb2014-03-10 17:42:56 -07006554// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006555// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006556// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006557uint32_t AudioPolicyManager::nextAudioPortGeneration()
6558{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006559 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006560}
6561
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006562AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006563 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006564 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006565 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006566 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006567 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006568 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006569 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006570 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006571 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006572 mAudioPortGeneration(1),
6573 mBeaconMuteRefCount(0),
6574 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006575 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006576 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006577 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006578 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006579{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006580}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006581
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006582status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006583 if (mEngine == nullptr) {
6584 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006585 }
6586 mEngine->setObserver(this);
6587 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006588 if (status != NO_ERROR) {
6589 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6590 return status;
6591 }
François Gaffie2110e042015-03-24 08:41:51 +01006592
jiabin29230182023-04-04 21:02:36 +00006593 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6594 // at the end of this function.
6595 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006596 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6597 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6598
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006599 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006600 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006601 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006602
Eric Laurent3a4311c2014-03-17 12:00:47 -07006603 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006604 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6605 defaultOutputDevice == nullptr ||
6606 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6607 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6608 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006609 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006610 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006611 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006612
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006613 // Silence ALOGV statements
6614 property_set("log.tag." LOG_TAG, "D");
6615
Eric Laurente552edb2014-03-10 17:42:56 -07006616 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006617 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006618}
6619
Eric Laurente0720872014-03-11 09:30:41 -07006620AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006621{
Eric Laurente552edb2014-03-10 17:42:56 -07006622 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006623 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006624 }
6625 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006626 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006627 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006628 mAvailableOutputDevices.clear();
6629 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006630 mOutputs.clear();
6631 mInputs.clear();
6632 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006633 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006634 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006635}
6636
Eric Laurente0720872014-03-11 09:30:41 -07006637status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006638{
Eric Laurent87ffa392015-05-22 10:32:38 -07006639 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006640}
6641
Eric Laurente552edb2014-03-10 17:42:56 -07006642// ---
6643
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006644void AudioPolicyManager::onNewAudioModulesAvailable()
6645{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006646 DeviceVector newDevices;
6647 onNewAudioModulesAvailableInt(&newDevices);
6648 if (!newDevices.empty()) {
6649 nextAudioPortGeneration();
6650 mpClientInterface->onAudioPortListUpdate();
6651 }
6652}
6653
6654void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6655{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006656 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006657 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6658 continue;
6659 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006660 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006661 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6662 handle != AUDIO_MODULE_HANDLE_NONE) {
6663 hwModule->setHandle(handle);
6664 } else {
6665 ALOGW("could not load HW module %s", hwModule->getName());
6666 continue;
6667 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006668 }
6669 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006670 // open all output streams needed to access attached devices.
6671 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006672 // This also validates mAvailableOutputDevices list
6673 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6674 if (!outProfile->canOpenNewIo()) {
6675 ALOGE("Invalid Output profile max open count %u for profile %s",
6676 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6677 continue;
6678 }
6679 if (!outProfile->hasSupportedDevices()) {
6680 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6681 continue;
6682 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006683 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6684 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006685 mTtsOutputAvailable = true;
6686 }
6687
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006688 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006689 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006690 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006691 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6692 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006693 } else {
6694 // choose first device present in profile's SupportedDevices also part of
6695 // mAvailableOutputDevices.
6696 if (availProfileDevices.isEmpty()) {
6697 continue;
6698 }
6699 supportedDevice = availProfileDevices.itemAt(0);
6700 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006701 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006702 continue;
6703 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306704
6705 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6706 && availProfileDevices.areAllDevicesAttached()) {
6707 ALOGV("%s skip opening output for mmap profile %s", __func__,
6708 outProfile->getTagName().c_str());
6709 continue;
6710 }
6711
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006712 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6713 mpClientInterface);
6714 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006715 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6716 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006717 AUDIO_STREAM_DEFAULT,
6718 AUDIO_OUTPUT_FLAG_NONE, &output);
6719 if (status != NO_ERROR) {
6720 ALOGW("Cannot open output stream for devices %s on hw module %s",
6721 supportedDevice->toString().c_str(), hwModule->getName());
6722 continue;
6723 }
6724 for (const auto &device : availProfileDevices) {
6725 // give a valid ID to an attached device once confirmed it is reachable
6726 if (!device->isAttached()) {
6727 device->attach(hwModule);
6728 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006729 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006730 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006731 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6732 }
6733 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006734 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006735 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6736 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006737 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006738 }
Eric Laurent39095982021-08-24 18:29:27 +02006739 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006740 outputDesc->close();
6741 } else {
6742 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306743 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006744 DeviceVector(supportedDevice),
6745 true,
6746 0,
6747 NULL);
6748 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006749 }
6750 // open input streams needed to access attached devices to validate
6751 // mAvailableInputDevices list
6752 for (const auto& inProfile : hwModule->getInputProfiles()) {
6753 if (!inProfile->canOpenNewIo()) {
6754 ALOGE("Invalid Input profile max open count %u for profile %s",
6755 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6756 continue;
6757 }
6758 if (!inProfile->hasSupportedDevices()) {
6759 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6760 continue;
6761 }
6762 // chose first device present in profile's SupportedDevices also part of
6763 // available input devices
6764 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006765 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006766 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006767 ALOGV("%s: Input device list is empty! for profile %s",
6768 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006769 continue;
6770 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306771
6772 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6773 && availProfileDevices.areAllDevicesAttached()) {
6774 ALOGV("%s skip opening input for mmap profile %s", __func__,
6775 inProfile->getTagName().c_str());
6776 continue;
6777 }
6778
Eric Laurentc71b11b2024-06-03 12:54:53 +00006779 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6780 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006781
6782 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6783 status_t status = inputDesc->open(nullptr,
6784 availProfileDevices.itemAt(0),
6785 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306786 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006787 &input);
6788 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306789 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6790 __func__, availProfileDevices.toString().c_str(),
6791 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006792 continue;
6793 }
6794 for (const auto &device : availProfileDevices) {
6795 // give a valid ID to an attached device once confirmed it is reachable
6796 if (!device->isAttached()) {
6797 device->attach(hwModule);
6798 device->importAudioPortAndPickAudioProfile(inProfile, true);
6799 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006800 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006801 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6802 }
6803 }
6804 inputDesc->close();
6805 }
6806 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006807
6808 // Check if spatializer outputs can be closed until used.
6809 // mOutputs vector never contains duplicated outputs at this point.
6810 std::vector<audio_io_handle_t> outputsClosed;
6811 for (size_t i = 0; i < mOutputs.size(); i++) {
6812 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6813 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6814 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6815 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006816 nextAudioPortGeneration();
6817 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6818 if (index >= 0) {
6819 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6820 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6821 patchDesc->getAfHandle(), 0);
6822 mAudioPatches.removeItemsAt(index);
6823 mpClientInterface->onAudioPatchListUpdate();
6824 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006825 desc->close();
6826 }
6827 }
6828 for (auto output : outputsClosed) {
6829 removeOutput(output);
6830 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006831}
6832
Eric Laurent98e38192018-02-15 18:31:53 -08006833void AudioPolicyManager::addOutput(audio_io_handle_t output,
6834 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006835{
Eric Laurent1c333e22014-05-20 10:48:17 -07006836 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006837 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006838 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006839 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006840 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006841}
6842
François Gaffie53615e22015-03-19 09:24:12 +01006843void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6844{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006845 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6846 ALOGV("%s: removing primary output", __func__);
6847 mPrimaryOutput = nullptr;
6848 }
François Gaffie53615e22015-03-19 09:24:12 +01006849 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006850 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006851}
6852
Eric Laurent98e38192018-02-15 18:31:53 -08006853void AudioPolicyManager::addInput(audio_io_handle_t input,
6854 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006855{
Eric Laurent1c333e22014-05-20 10:48:17 -07006856 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006857 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006858}
Eric Laurente552edb2014-03-10 17:42:56 -07006859
François Gaffie11d30102018-11-02 16:09:09 +01006860status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006861 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006862 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006863{
François Gaffie11d30102018-11-02 16:09:09 +01006864 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006865 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006866 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006867
François Gaffie11d30102018-11-02 16:09:09 +01006868 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006869 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006870 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006871 }
Eric Laurente552edb2014-03-10 17:42:56 -07006872
Eric Laurent3b73df72014-03-11 09:06:29 -07006873 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006874 // first call getAudioPort to get the supported attributes from the HAL
6875 struct audio_port_v7 port = {};
6876 device->toAudioPort(&port);
6877 status_t status = mpClientInterface->getAudioPort(&port);
6878 if (status == NO_ERROR) {
6879 device->importAudioPort(port);
6880 }
6881
6882 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006883 for (size_t i = 0; i < mOutputs.size(); i++) {
6884 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006885 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006886 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006887 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6888 mOutputs.keyAt(i), device->toString().c_str());
6889 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006890 }
6891 }
6892 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006893 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006894 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006895 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6896 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006897 if (profile->supportsDevice(device)) {
6898 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306899 ALOGV("%s(): adding profile %s from module %s",
6900 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006901 }
6902 }
6903 }
6904
Eric Laurent7b279bb2015-12-14 10:18:23 -08006905 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006906
Eric Laurente552edb2014-03-10 17:42:56 -07006907 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006908 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006909 return BAD_VALUE;
6910 }
6911
6912 // open outputs for matching profiles if needed. Direct outputs are also opened to
6913 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6914 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006915 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006916
6917 // nothing to do if one output is already opened for this profile
6918 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006919 for (j = 0; j < outputs.size(); j++) {
6920 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006921 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006922 // matching profile: save the sample rates, format and channel masks supported
6923 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006924 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006925 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006926 }
Eric Laurente552edb2014-03-10 17:42:56 -07006927 break;
6928 }
6929 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006930 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006931 continue;
6932 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306933 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6934 ALOGV("%s skip opening output for mmap profile %s",
6935 __func__, profile->getTagName().c_str());
6936 continue;
6937 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006938 if (!profile->canOpenNewIo()) {
6939 ALOGW("Max Output number %u already opened for this profile %s",
6940 profile->maxOpenCount, profile->getTagName().c_str());
6941 continue;
6942 }
6943
Eric Laurent83efe1c2017-07-09 16:51:08 -07006944 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006945 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006946 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6947 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006948 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006949 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006950 profiles.removeAt(profile_index);
6951 profile_index--;
6952 } else {
6953 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006954 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006955 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006956 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6957 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006958 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006959 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006960
François Gaffie11d30102018-11-02 16:09:09 +01006961 if (device_distinguishes_on_address(deviceType)) {
6962 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6963 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306964 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6965 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006966 }
Eric Laurente552edb2014-03-10 17:42:56 -07006967 ALOGV("checkOutputsForDevice(): adding output %d", output);
6968 }
6969 }
6970
6971 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006972 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006973 return BAD_VALUE;
6974 }
Eric Laurentd4692962014-05-05 18:13:44 -07006975 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006976 // check if one opened output is not needed any more after disconnecting one device
6977 for (size_t i = 0; i < mOutputs.size(); i++) {
6978 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006979 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006980 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006981 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006982 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006983 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006984 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006985 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6986 mOutputs.keyAt(i));
6987 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006988 }
Eric Laurente552edb2014-03-10 17:42:56 -07006989 }
6990 }
Eric Laurentd4692962014-05-05 18:13:44 -07006991 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006992 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006993 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6994 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006995 if (!profile->supportsDevice(device)) {
6996 continue;
6997 }
Jaideep Sharma33173202024-06-18 17:46:45 +05306998 ALOGV("%s(): clearing direct output profile %s on module %s",
6999 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007000 profile->clearAudioProfiles();
7001 if (!profile->hasDynamicAudioProfile()) {
7002 continue;
7003 }
7004 // When a device is disconnected, if there is an IOProfile that contains dynamic
7005 // profiles and supports the disconnected device, call getAudioPort to repopulate
7006 // the capabilities of the devices that is supported by the IOProfile.
7007 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7008 if (supportedDevice == device ||
7009 !mAvailableOutputDevices.contains(supportedDevice)) {
7010 continue;
7011 }
7012 struct audio_port_v7 port;
7013 supportedDevice->toAudioPort(&port);
7014 status_t status = mpClientInterface->getAudioPort(&port);
7015 if (status == NO_ERROR) {
7016 supportedDevice->importAudioPort(port);
7017 }
Eric Laurente552edb2014-03-10 17:42:56 -07007018 }
7019 }
7020 }
7021 }
7022 return NO_ERROR;
7023}
7024
François Gaffie11d30102018-11-02 16:09:09 +01007025status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007026 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007027{
François Gaffie11d30102018-11-02 16:09:09 +01007028 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007029 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007030 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007031 }
7032
Eric Laurentd4692962014-05-05 18:13:44 -07007033 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007034 sp<AudioInputDescriptor> desc;
7035
jiabinbf5f4262023-04-12 21:48:34 +00007036 // first call getAudioPort to get the supported attributes from the HAL
7037 struct audio_port_v7 port = {};
7038 device->toAudioPort(&port);
7039 status_t status = mpClientInterface->getAudioPort(&port);
7040 if (status == NO_ERROR) {
7041 device->importAudioPort(port);
7042 }
7043
Eric Laurent0dd51852019-04-19 18:18:58 -07007044 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007045 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007046 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007047 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007048 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007049 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007050 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007051
François Gaffie11d30102018-11-02 16:09:09 +01007052 if (profile->supportsDevice(device)) {
7053 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307054 ALOGV("%s : adding profile %s from module %s", __func__,
7055 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007056 }
7057 }
7058 }
7059
Eric Laurent0dd51852019-04-19 18:18:58 -07007060 if (profiles.isEmpty()) {
7061 ALOGW("%s: No input profile available for device %s",
7062 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007063 return BAD_VALUE;
7064 }
7065
7066 // open inputs for matching profiles if needed. Direct inputs are also opened to
7067 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7068 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7069
Eric Laurent1c333e22014-05-20 10:48:17 -07007070 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007071
Eric Laurentd4692962014-05-05 18:13:44 -07007072 // nothing to do if one input is already opened for this profile
7073 size_t input_index;
7074 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7075 desc = mInputs.valueAt(input_index);
7076 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007077 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007078 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007079 }
Eric Laurentd4692962014-05-05 18:13:44 -07007080 break;
7081 }
7082 }
7083 if (input_index != mInputs.size()) {
7084 continue;
7085 }
7086
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307087 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7088 ALOGV("%s skip opening input for mmap profile %s",
7089 __func__, profile->getTagName().c_str());
7090 continue;
7091 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007092 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307093 ALOGW("%s Max Input number %u already opened for this profile %s",
7094 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007095 continue;
7096 }
7097
Eric Laurentc71b11b2024-06-03 12:54:53 +00007098 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007099 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307100 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307101 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7102 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007103
Eric Laurentcf2c0212014-07-25 16:20:43 -07007104 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007105 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007106 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007107 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007108 mpClientInterface->setParameters(input, String8(param));
7109 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007110 }
jiabin12537fc2023-10-12 17:56:08 +00007111 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007112 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307113 ALOGW("%s direct input missing param for profile %s", __func__,
7114 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007115 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007116 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007117 }
7118
Eric Laurent0dd51852019-04-19 18:18:58 -07007119 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007120 addInput(input, desc);
7121 }
7122 } // endif input != 0
7123
Eric Laurentcf2c0212014-07-25 16:20:43 -07007124 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307125 ALOGW("%s could not open input for device %s on profile %s", __func__,
7126 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007127 profiles.removeAt(profile_index);
7128 profile_index--;
7129 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007130 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007131 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007132 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307133 ALOGV("%s: adding input %d for profile %s", __func__,
7134 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007135
7136 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307137 ALOGV("%s: closing input %d for profile %s", __func__,
7138 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007139 closeInput(input);
7140 }
Eric Laurentd4692962014-05-05 18:13:44 -07007141 }
7142 } // end scan profiles
7143
7144 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007145 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007146 return BAD_VALUE;
7147 }
7148 } else {
7149 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007150 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007151 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007152 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007153 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007154 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007155 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007156 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307157 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7158 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007159 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007160 }
7161 }
7162 }
7163 } // end disconnect
7164
7165 return NO_ERROR;
7166}
7167
7168
Eric Laurente0720872014-03-11 09:30:41 -07007169void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007170{
7171 ALOGV("closeOutput(%d)", output);
7172
François Gaffie1c878552018-11-22 16:53:21 +01007173 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7174 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007175 ALOGW("closeOutput() unknown output %d", output);
7176 return;
7177 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007178 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007179 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007180
Eric Laurente552edb2014-03-10 17:42:56 -07007181 // look for duplicated outputs connected to the output being removed.
7182 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007183 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7184 if (dupOutput->isDuplicated() &&
7185 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7186 sp<SwAudioOutputDescriptor> remainingOutput =
7187 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007188 // As all active tracks on duplicated output will be deleted,
7189 // and as they were also referenced on the other output, the reference
7190 // count for their stream type must be adjusted accordingly on
7191 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007192 const bool wasActive = remainingOutput->isActive();
7193 // Note: no-op on the closing output where all clients has already been set inactive
7194 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007195 // stop() will be a no op if the output is still active but is needed in case all
7196 // active streams refcounts where cleared above
7197 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007198 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007199 }
Eric Laurente552edb2014-03-10 17:42:56 -07007200 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7201 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7202
7203 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007204 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007205 }
7206 }
7207
Eric Laurent05b90f82014-08-27 15:32:29 -07007208 nextAudioPortGeneration();
7209
François Gaffie1c878552018-11-22 16:53:21 +01007210 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007211 if (index >= 0) {
7212 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007213 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7214 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007215 mAudioPatches.removeItemsAt(index);
7216 mpClientInterface->onAudioPatchListUpdate();
7217 }
7218
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007219 if (closingOutputWasActive) {
7220 closingOutput->stop();
7221 }
François Gaffie1c878552018-11-22 16:53:21 +01007222 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007223 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007224 for (const auto device : closingOutput->devices()) {
7225 device->setPreferredConfig(nullptr);
7226 }
7227 }
Eric Laurente552edb2014-03-10 17:42:56 -07007228
François Gaffie53615e22015-03-19 09:24:12 +01007229 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007230 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007231 if (closingOutput == mSpatializerOutput) {
7232 mSpatializerOutput.clear();
7233 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007234
7235 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7236 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007237 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007238 bool directOutputOpen = false;
7239 for (size_t i = 0; i < mOutputs.size(); i++) {
7240 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7241 directOutputOpen = true;
7242 break;
7243 }
7244 }
7245 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007246 ALOGV("no direct outputs open, reset MSD patches");
7247 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7248 // how output devices for patching are resolved. Avoid by caching and reusing the
7249 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7250 // devices to patch to. This may be complicated by the fact that devices may become
7251 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007252 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007253 }
7254 }
jiabin220eea12024-05-17 17:55:20 +00007255
7256 if (closingOutput->mPreferredAttrInfo != nullptr) {
7257 closingOutput->mPreferredAttrInfo->resetActiveClient();
7258 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007259}
7260
7261void AudioPolicyManager::closeInput(audio_io_handle_t input)
7262{
7263 ALOGV("closeInput(%d)", input);
7264
7265 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7266 if (inputDesc == NULL) {
7267 ALOGW("closeInput() unknown input %d", input);
7268 return;
7269 }
7270
Eric Laurent6a94d692014-05-20 11:18:06 -07007271 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007272
François Gaffie11d30102018-11-02 16:09:09 +01007273 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007274 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007275 if (index >= 0) {
7276 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007277 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7278 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007279 mAudioPatches.removeItemsAt(index);
7280 mpClientInterface->onAudioPatchListUpdate();
7281 }
7282
François Gaffie6ebbce02023-07-19 13:27:53 +02007283 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007284 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007285 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007286
François Gaffie11d30102018-11-02 16:09:09 +01007287 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7288 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007289 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007290 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007291 }
Eric Laurente552edb2014-03-10 17:42:56 -07007292}
7293
François Gaffie11d30102018-11-02 16:09:09 +01007294SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7295 const DeviceVector &devices,
7296 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007297{
7298 SortedVector<audio_io_handle_t> outputs;
7299
François Gaffie11d30102018-11-02 16:09:09 +01007300 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007301 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007302 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007303 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007304 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007305 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007306 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007307 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007308 outputs.add(openOutputs.keyAt(i));
7309 }
7310 }
7311 return outputs;
7312}
7313
Mikhail Naganov37977152018-07-11 15:54:44 -07007314void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7315{
7316 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7317 // output is suspended before any tracks are moved to it
7318 checkA2dpSuspend();
7319 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007320 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007321 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007322 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007323 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007324 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7325 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7326 // configuration changes will ultimately be rerouted correctly. We can still avoid
7327 // unnecessary rerouting by caching and reusing the arguments to
7328 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7329 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007330 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007331 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007332 // an event that changed routing likely occurred, inform upper layers
7333 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007334}
7335
François Gaffiec005e562018-11-06 15:04:49 +01007336bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7337 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007338{
François Gaffiec005e562018-11-06 15:04:49 +01007339 return mEngine->getProductStrategyForAttributes(lAttr) ==
7340 mEngine->getProductStrategyForAttributes(rAttr);
7341}
7342
Francois Gaffieff1eb522020-05-06 18:37:04 +02007343void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7344{
7345 for (size_t i = 0; i < mAudioSources.size(); i++) {
7346 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7347 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007348 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007349 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007350 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007351 }
7352 }
7353}
7354
7355void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7356{
7357 for (size_t i = 0; i < mAudioSources.size(); i++) {
7358 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7359 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7360 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7361 disconnectAudioSource(sourceDesc);
7362 }
7363 }
7364}
7365
François Gaffiec005e562018-11-06 15:04:49 +01007366void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7367{
7368 auto psId = mEngine->getProductStrategyForAttributes(attr);
7369
7370 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7371 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007372
François Gaffie11d30102018-11-02 16:09:09 +01007373 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7374 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007375
Eric Laurentc209fe42020-06-05 18:11:23 -07007376 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007377 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007378 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007379 // take into account dynamic audio policies related changes: if a client is now associated
7380 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007381 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007382 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7383 if (desc->isDuplicated()) {
7384 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007385 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007386 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7387 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7388 continue;
7389 }
7390 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007391 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007392 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7393 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7394 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007395 if (status != OK) {
7396 continue;
7397 }
yucliuf4de36d2020-09-14 14:57:56 -07007398 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007399 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007400 maxLatency = desc->latency();
7401 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007402 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007403 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007404 }
7405 }
7406
Eric Laurent56ed8842022-11-15 16:04:41 +01007407 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007408 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7409 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007410 for (audio_io_handle_t srcOut : srcOutputs) {
7411 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007412 if (desc == nullptr) continue;
7413
7414 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007415 maxLatency = desc->latency();
7416 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007417
Eric Laurent56ed8842022-11-15 16:04:41 +01007418 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007419 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007420 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007421 // a client on a non direct outputs has necessarily a linear PCM format
7422 // so we can call selectOutput() safely
7423 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7424 client->flags(),
7425 client->config().format,
7426 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007427 client->config().sample_rate,
7428 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007429 if (newOutput != srcOut) {
7430 invalidate = true;
7431 break;
7432 }
7433 } else {
7434 sp<IOProfile> profile = getProfileForOutput(newDevices,
7435 client->config().sample_rate,
7436 client->config().format,
7437 client->config().channel_mask,
7438 client->flags(),
7439 true /* directOnly */);
7440 if (profile != desc->mProfile) {
7441 invalidate = true;
7442 break;
7443 }
7444 }
7445 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007446 // mute strategy while moving tracks from one output to another
7447 if (invalidate) {
7448 invalidatedOutputs.push_back(desc);
7449 if (desc->isStrategyActive(psId)) {
7450 setStrategyMute(psId, true, desc);
7451 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7452 newDevices.types());
7453 }
Eric Laurente552edb2014-03-10 17:42:56 -07007454 }
François Gaffiec005e562018-11-06 15:04:49 +01007455 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007456 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007457 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007458 }
Eric Laurente552edb2014-03-10 17:42:56 -07007459 }
7460
Eric Laurent56ed8842022-11-15 16:04:41 +01007461 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7462 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7463 std::to_string(srcOutputs[0]).c_str(),
7464 std::to_string(dstOutputs[0]).c_str());
7465
François Gaffiec005e562018-11-06 15:04:49 +01007466 // Move effects associated to this stream from previous output to new output
7467 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007468 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007469 }
François Gaffiec005e562018-11-06 15:04:49 +01007470 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007471 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007472 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007473 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007474 desc->setTracksInvalidatedStatusByStrategy(psId);
7475 }
Eric Laurente552edb2014-03-10 17:42:56 -07007476 }
7477 }
7478}
7479
Eric Laurente0720872014-03-11 09:30:41 -07007480void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007481{
François Gaffiec005e562018-11-06 15:04:49 +01007482 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7483 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7484 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007485 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007486 }
Eric Laurente552edb2014-03-10 17:42:56 -07007487}
7488
Kevin Rocard153f92d2018-12-18 18:33:28 -08007489void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007490 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007491 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007492 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007493 for (size_t i = 0; i < mOutputs.size(); i++) {
7494 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7495 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007496 sp<AudioPolicyMix> primaryMix;
7497 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007498 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007499 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7500 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7501 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007502 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7503 for (auto &secondaryMix : secondaryMixes) {
7504 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7505 if (outputDesc != nullptr &&
7506 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7507 secondaryDescs.push_back(outputDesc);
7508 }
7509 }
7510
jiabinc44b3462022-12-08 12:52:31 -08007511 if (status != OK &&
7512 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7513 // When it failed to query secondary output, only invalidate the client that is not
7514 // MMAP. The reason is that MMAP stream will not support secondary output.
7515 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007516 } else if (!std::equal(
7517 client->getSecondaryOutputs().begin(),
7518 client->getSecondaryOutputs().end(),
7519 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007520 if (!audio_is_linear_pcm(client->config().format)) {
7521 // If the format is not PCM, the tracks should be invalidated to get correct
7522 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007523 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007524 } else {
7525 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7526 std::vector<audio_io_handle_t> secondaryOutputIds;
7527 for (const auto &secondaryDesc: secondaryDescs) {
7528 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7529 weakSecondaryDescs.push_back(secondaryDesc);
7530 }
7531 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7532 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007533 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007534 }
7535 }
7536 }
jiabin10a03f12021-05-07 23:46:28 +00007537 if (!trackSecondaryOutputs.empty()) {
7538 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7539 }
jiabinc44b3462022-12-08 12:52:31 -08007540 if (!clientsToInvalidate.empty()) {
7541 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7542 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007543 }
7544}
7545
Eric Laurent2517af32020-11-25 15:31:27 +01007546bool AudioPolicyManager::isScoRequestedForComm() const {
7547 AudioDeviceTypeAddrVector devices;
7548 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7549 for (const auto &device : devices) {
7550 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7551 return true;
7552 }
7553 }
7554 return false;
7555}
7556
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007557bool AudioPolicyManager::isHearingAidUsedForComm() const {
7558 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7559 true /*fromCache*/);
7560 for (const auto &device : devices) {
7561 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7562 return true;
7563 }
7564 }
7565 return false;
7566}
7567
7568
Eric Laurente0720872014-03-11 09:30:41 -07007569void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007570{
François Gaffie53615e22015-03-19 09:24:12 +01007571 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007572 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007573 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007574 return;
7575 }
7576
Eric Laurent3a4311c2014-03-17 12:00:47 -07007577 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007578 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7579 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007580 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007581
7582 // if suspended, restore A2DP output if:
7583 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007584 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007585 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007586 //
Eric Laurentf732e072016-08-03 19:30:28 -07007587 // if not suspended, suspend A2DP output if:
7588 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007589 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007590 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007591 //
7592 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007593 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007594 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007595 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007596 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007597
7598 mpClientInterface->restoreOutput(a2dpOutput);
7599 mA2dpSuspended = false;
7600 }
7601 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007602 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007603 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007604 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007605 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007606
7607 mpClientInterface->suspendOutput(a2dpOutput);
7608 mA2dpSuspended = true;
7609 }
7610 }
7611}
7612
François Gaffie11d30102018-11-02 16:09:09 +01007613DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7614 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007615{
François Gaffiedb1755b2023-09-01 11:50:35 +02007616 if (outputDesc == nullptr) {
7617 return DeviceVector{};
7618 }
François Gaffie11d30102018-11-02 16:09:09 +01007619
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007620 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007621 if (index >= 0) {
7622 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007623 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007624 ALOGV("%s device %s forced by patch %d", __func__,
7625 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7626 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007627 }
7628 }
7629
Dean Wheatley514b4312020-06-17 21:45:00 +10007630 // Do not retrieve engine device for outputs through MSD
7631 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7632 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7633 return outputDesc->devices();
7634 }
7635
Eric Laurent97ac8712018-07-27 18:59:02 -07007636 // Honor explicit routing requests only if no client using default routing is active on this
7637 // input: a specific app can not force routing for other apps by setting a preferred device.
7638 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007639 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007640 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007641 if (device != nullptr) {
7642 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007643 }
7644
François Gaffiea807ef92018-11-05 10:44:33 +01007645 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7646 // of setForceUse / Default Bus device here
7647 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7648 if (device != nullptr) {
7649 return DeviceVector(device);
7650 }
7651
François Gaffiedb1755b2023-09-01 11:50:35 +02007652 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007653 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7654 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307655 auto hasStreamActive = [&](auto stream) {
7656 return hasStream(streams, stream) && isStreamActive(stream, 0);
7657 };
Eric Laurent484e9272018-06-07 17:29:23 -07007658
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307659 auto doGetOutputDevicesForVoice = [&]() {
7660 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007661 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307662 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007663 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7664 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307665 };
7666
7667 // With low-latency playing on speaker, music on WFD, when the first low-latency
7668 // output is stopped, getNewOutputDevices checks for a product strategy
7669 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007670 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307671 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7672 // stream is associated to the output descriptor.
7673 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7674 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7675 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7676 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007677 // Retrieval of devices for voice DL is done on primary output profile, cannot
7678 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007679 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007680 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7681 break;
7682 }
Eric Laurente552edb2014-03-10 17:42:56 -07007683 }
François Gaffiec005e562018-11-06 15:04:49 +01007684 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007685 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007686}
7687
François Gaffie11d30102018-11-02 16:09:09 +01007688sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7689 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007690{
François Gaffie11d30102018-11-02 16:09:09 +01007691 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007692
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007693 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007694 if (index >= 0) {
7695 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007696 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007697 ALOGV("getNewInputDevice() device %s forced by patch %d",
7698 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7699 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007700 }
7701 }
7702
Eric Laurent97ac8712018-07-27 18:59:02 -07007703 // Honor explicit routing requests only if no client using default routing is active on this
7704 // input: a specific app can not force routing for other apps by setting a preferred device.
7705 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007706 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7707 if (device != nullptr) {
7708 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007709 }
7710
Eric Laurentdc95a252018-04-12 12:46:56 -07007711 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007712 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007713 audio_attributes_t attributes;
7714 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007715 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007716 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7717 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007718 attributes = topClient->attributes();
7719 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007720 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007721 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007722 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7723 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007724 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007725 }
7726
Francois Gaffie716e1432019-01-14 16:58:59 +01007727 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7728 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007729 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007730 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007731 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007732 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007733
Eric Laurente552edb2014-03-10 17:42:56 -07007734 return device;
7735}
7736
Eric Laurent794fde22016-03-11 09:50:45 -08007737bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7738 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007739 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007740}
7741
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007742status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007743 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007744 if (devices == nullptr) {
7745 return BAD_VALUE;
7746 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007747
Andy Hung6d23c0f2022-02-16 09:37:15 -08007748 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007749 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7750 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007751 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007752 for (const auto& device : curDevices) {
7753 devices->push_back(device->getDeviceTypeAddr());
7754 }
7755 return NO_ERROR;
7756}
7757
Eric Laurente0720872014-03-11 09:30:41 -07007758void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007759 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007760 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007761 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007762 updateDevicesAndOutputs();
7763 break;
7764 default:
7765 break;
7766 }
7767}
7768
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007769uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007770
7771 // skip beacon mute management if a dedicated TTS output is available
7772 if (mTtsOutputAvailable) {
7773 return 0;
7774 }
7775
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007776 switch(event) {
7777 case STARTING_OUTPUT:
7778 mBeaconMuteRefCount++;
7779 break;
7780 case STOPPING_OUTPUT:
7781 if (mBeaconMuteRefCount > 0) {
7782 mBeaconMuteRefCount--;
7783 }
7784 break;
7785 case STARTING_BEACON:
7786 mBeaconPlayingRefCount++;
7787 break;
7788 case STOPPING_BEACON:
7789 if (mBeaconPlayingRefCount > 0) {
7790 mBeaconPlayingRefCount--;
7791 }
7792 break;
7793 }
7794
7795 if (mBeaconMuteRefCount > 0) {
7796 // any playback causes beacon to be muted
7797 return setBeaconMute(true);
7798 } else {
7799 // no other playback: unmute when beacon starts playing, mute when it stops
7800 return setBeaconMute(mBeaconPlayingRefCount == 0);
7801 }
7802}
7803
7804uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7805 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7806 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7807 // keep track of muted state to avoid repeating mute/unmute operations
7808 if (mBeaconMuted != mute) {
7809 // mute/unmute AUDIO_STREAM_TTS on all outputs
7810 ALOGV("\t muting %d", mute);
7811 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007812 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7813 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7814 ALOGV("\t no tts volume source available");
7815 return 0;
7816 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007817 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007818 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007819 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007820 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007821 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007822 maxLatency = latency;
7823 }
7824 }
7825 mBeaconMuted = mute;
7826 return maxLatency;
7827 }
7828 return 0;
7829}
7830
Eric Laurente0720872014-03-11 09:30:41 -07007831void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007832{
François Gaffiec005e562018-11-06 15:04:49 +01007833 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007834 mPreviousOutputs = mOutputs;
7835}
7836
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007837uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007838 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007839 uint32_t delayMs)
7840{
7841 // mute/unmute strategies using an incompatible device combination
7842 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7843 // if unmuting, unmute only after the specified delay
7844 if (outputDesc->isDuplicated()) {
7845 return 0;
7846 }
7847
7848 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007849 DeviceVector devices = outputDesc->devices();
7850 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007851
François Gaffiec005e562018-11-06 15:04:49 +01007852 auto productStrategies = mEngine->getOrderedProductStrategies();
7853 for (const auto &productStrategy : productStrategies) {
7854 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7855 DeviceVector curDevices =
7856 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7857 curDevices = curDevices.filter(outputDesc->supportedDevices());
7858 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007859 bool doMute = false;
7860
François Gaffiec005e562018-11-06 15:04:49 +01007861 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007862 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007863 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7864 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007865 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007866 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007867 }
Eric Laurent99401132014-05-07 19:48:15 -07007868 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007869 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007870 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007871 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007872 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007873 continue;
7874 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307875 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007876 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7877 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7878 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007879 if (mute) {
7880 // FIXME: should not need to double latency if volume could be applied
7881 // immediately by the audioflinger mixer. We must account for the delay
7882 // between now and the next time the audioflinger thread for this output
7883 // will process a buffer (which corresponds to one buffer size,
7884 // usually 1/2 or 1/4 of the latency).
7885 if (muteWaitMs < desc->latency() * 2) {
7886 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007887 }
7888 }
7889 }
7890 }
7891 }
7892 }
7893
Eric Laurent99401132014-05-07 19:48:15 -07007894 // temporary mute output if device selection changes to avoid volume bursts due to
7895 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007896 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007897 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007898
Eric Laurentdc462862016-07-19 12:29:53 -07007899 if (muteWaitMs < tempMuteWaitMs) {
7900 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007901 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007902
7903 // If recommended duration is defined, replace temporary mute duration to avoid
7904 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7905 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7906 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7907 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7908 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7909
François Gaffieaaac0fd2018-11-22 17:56:39 +01007910 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7911 // make sure that we do not start the temporary mute period too early in case of
7912 // delayed device change
7913 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7914 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007915 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007916 }
7917 }
7918
Eric Laurente552edb2014-03-10 17:42:56 -07007919 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7920 if (muteWaitMs > delayMs) {
7921 muteWaitMs -= delayMs;
7922 usleep(muteWaitMs * 1000);
7923 return muteWaitMs;
7924 }
7925 return 0;
7926}
7927
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307928uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7929 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007930 const DeviceVector &devices,
7931 bool force,
7932 int delayMs,
7933 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007934 bool requiresMuteCheck, bool requiresVolumeCheck,
7935 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007936{
jiabin3ff8d7d2022-12-13 06:27:44 +00007937 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307938 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7939 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7940 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007941 uint32_t muteWaitMs;
7942
7943 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307944 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007945 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307946 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007947 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007948 return muteWaitMs;
7949 }
Eric Laurente552edb2014-03-10 17:42:56 -07007950
7951 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007952 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007953 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007954 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007955
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307956 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7957 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007958
7959 if (!filteredDevices.isEmpty()) {
7960 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007961 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007962
7963 // if the outputs are not materially active, there is no need to mute.
7964 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007965 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007966 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307967 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7968 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007969 muteWaitMs = 0;
7970 }
Eric Laurente552edb2014-03-10 17:42:56 -07007971
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007972 bool outputRouted = outputDesc->isRouted();
7973
Eric Laurent79ea9582020-06-11 18:49:24 -07007974 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7975 // output profile or if new device is not supported AND previous device(s) is(are) still
7976 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007977 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307978 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7979 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007980 // restore previous device after evaluating strategy mute state
7981 outputDesc->setDevices(prevDevices);
7982 return muteWaitMs;
7983 }
7984
Eric Laurente552edb2014-03-10 17:42:56 -07007985 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007986 // the requested device is AUDIO_DEVICE_NONE
7987 // OR the requested device is the same as current device
7988 // AND force is not specified
7989 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007990 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007991 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307992 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7993 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7994 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007995 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307996 ALOGV("%s %s setting same device on routed output, force apply volumes",
7997 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007998 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7999 }
Eric Laurente552edb2014-03-10 17:42:56 -07008000 return muteWaitMs;
8001 }
8002
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308003 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8004 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008005
Eric Laurente552edb2014-03-10 17:42:56 -07008006 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008007 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008008 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008009 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008010 PatchBuilder patchBuilder;
8011 patchBuilder.addSource(outputDesc);
8012 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8013 for (const auto &filteredDevice : filteredDevices) {
8014 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008015 }
8016
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008017 // Add half reported latency to delayMs when muteWaitMs is null in order
8018 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008019 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8020 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8021 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008022 }
Eric Laurente552edb2014-03-10 17:42:56 -07008023
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008024 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8025 if (!skipMuteDelay) {
8026 // update stream volumes according to new device
8027 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8028 }
Eric Laurente552edb2014-03-10 17:42:56 -07008029
8030 return muteWaitMs;
8031}
8032
Eric Laurentc75307b2015-03-17 15:29:32 -07008033status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008034 int delayMs,
8035 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008036{
Eric Laurent6a94d692014-05-20 11:18:06 -07008037 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008038 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8039 return INVALID_OPERATION;
8040 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008041 if (patchHandle) {
8042 index = mAudioPatches.indexOfKey(*patchHandle);
8043 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008044 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008045 }
8046 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008047 return INVALID_OPERATION;
8048 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008049 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008050 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008051 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008052 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008053 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008054 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008055 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008056 return status;
8057}
8058
8059status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008060 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008061 bool force,
8062 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008063{
8064 status_t status = NO_ERROR;
8065
Eric Laurent1f2f2232014-06-02 12:01:23 -07008066 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008067 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8068 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008069
François Gaffie11d30102018-11-02 16:09:09 +01008070 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008071 PatchBuilder patchBuilder;
8072 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008073 // AUDIO_SOURCE_HOTWORD is for internal use only:
8074 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008075 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8076 auto result = usecase;
8077 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8078 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8079 }
8080 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008081 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008082 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008083 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008084 }
8085 }
8086 return status;
8087}
8088
Eric Laurent6a94d692014-05-20 11:18:06 -07008089status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8090 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008091{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008092 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008093 ssize_t index;
8094 if (patchHandle) {
8095 index = mAudioPatches.indexOfKey(*patchHandle);
8096 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008097 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008098 }
8099 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008100 return INVALID_OPERATION;
8101 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008102 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008103 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008104 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008105 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008106 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008107 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008108 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008109 return status;
8110}
8111
François Gaffie11d30102018-11-02 16:09:09 +01008112sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008113 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008114 audio_format_t& format,
8115 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008116 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008117{
8118 // Choose an input profile based on the requested capture parameters: select the first available
8119 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008120 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008121
Atneya Nair0f0a8032022-12-12 16:20:12 -08008122 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8123 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8124 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8125
8126 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008127
jiabin2fd710d2022-05-02 23:20:22 +00008128 for (;;) {
8129 sp<IOProfile> firstInexact = nullptr;
8130 uint32_t updatedSamplingRate = 0;
8131 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8132 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8133 for (const auto& hwModule : mHwModules) {
8134 for (const auto& profile : hwModule->getInputProfiles()) {
8135 // profile->log();
8136 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008137 if (profile->getCompatibilityScore(
8138 DeviceVector(device),
8139 samplingRate,
8140 &updatedSamplingRate,
8141 format,
8142 &updatedFormat,
8143 channelMask,
8144 &updatedChannelMask,
8145 // FIXME ugly cast
8146 (audio_output_flags_t) flags,
8147 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8148 samplingRate = updatedSamplingRate;
8149 format = updatedFormat;
8150 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008151 return profile;
8152 }
jiabin66acc432024-02-06 00:57:36 +00008153 if (firstInexact == nullptr
8154 && profile->getCompatibilityScore(
8155 DeviceVector(device),
8156 samplingRate,
8157 &updatedSamplingRate,
8158 format,
8159 &updatedFormat,
8160 channelMask,
8161 &updatedChannelMask,
8162 // FIXME ugly cast
8163 (audio_output_flags_t) flags,
8164 false /*exactMatchRequiredForInputFlags*/)
8165 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008166 firstInexact = profile;
8167 }
8168 }
8169 }
8170
8171 if (firstInexact != nullptr) {
8172 samplingRate = updatedSamplingRate;
8173 format = updatedFormat;
8174 channelMask = updatedChannelMask;
8175 return firstInexact;
8176 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8177 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8178 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8179 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8180 flags = AUDIO_INPUT_FLAG_NONE;
8181 } else { // fail
8182 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8183 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8184 samplingRate, format, channelMask, oriFlags);
8185 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008186 }
8187 }
jiabin2fd710d2022-05-02 23:20:22 +00008188
8189 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008190}
8191
Vlad Popa87e0e582024-05-20 18:49:20 -07008192float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8193 VolumeSource volumeSource,
8194 int index,
8195 const DeviceTypeSet &deviceTypes)
8196{
8197 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8198 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8199 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8200
8201 if (com_android_media_audio_abs_volume_index_fix()) {
8202 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8203 mAbsoluteVolumeDrivingStreams.end()) {
8204 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8205 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8206 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8207 ALOGD("%s: no group matching with %s", __FUNCTION__,
8208 toString(attributesToDriveAbs).c_str());
8209 return volumeDb;
8210 }
8211
8212 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8213 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8214 if (vsToDriveAbs == volumeSource) {
8215 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008216 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008217 } else {
8218 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8219 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8220 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8221 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8222 curvesAbs.getVolumeIndexMax());
8223 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8224 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8225 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8226 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8227 return newVolumeDb;
8228 }
8229 }
8230 return volumeDb;
8231 } else {
8232 return volumeDb;
8233 }
8234}
8235
François Gaffieaaac0fd2018-11-22 17:56:39 +01008236float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8237 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008238 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008239 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008240 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008241 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008242{
Vlad Popa9d482762024-06-21 16:40:23 -07008243 float volumeDb;
8244 if (adjustAttenuation) {
8245 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8246 } else {
8247 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8248 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008249 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8250 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8251
8252 if (!computeInternalInteraction) {
8253 return volumeDb;
8254 }
8255
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008256 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8257 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8258 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8259 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008260 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8261 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8262 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8263 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8264 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008265 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008266 mOutputs.isActive(ringVolumeSrc, 0)) {
8267 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008268 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008269 adjustAttenuation,
8270 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008271 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008272 }
8273
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008274 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008275 if ((volumeSource != callVolumeSrc && (isInCall() ||
8276 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008277 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008278 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8279 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008280 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8281 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8282 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008283 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008284 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008285 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008286 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008287 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008288 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008289 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008290 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8291 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8292 // programmatically muted.
8293 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8294 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8295 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008296 bool exemptFromCapping =
8297 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8298 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008299 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8300 volumeSource, volumeDb);
8301 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008302 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8303 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8304 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008305 }
8306 }
Eric Laurente552edb2014-03-10 17:42:56 -07008307 // if a headset is connected, apply the following rules to ring tones and notifications
8308 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008309 // - always attenuate notifications volume by 6dB
8310 // - attenuate ring tones volume by 6dB unless music is not playing and
8311 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008312 // - if music is playing, always limit the volume to current music volume,
8313 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008314 if (!Intersection(deviceTypes,
8315 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8316 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008317 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8318 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008319 ((volumeSource == alarmVolumeSrc ||
8320 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008321 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8322 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8323 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008324 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8325 curves.canBeMuted()) {
8326
Eric Laurente552edb2014-03-10 17:42:56 -07008327 // when the phone is ringing we must consider that music could have been paused just before
8328 // by the music application and behave as if music was active if the last music track was
8329 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008330 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8331 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008332 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008333 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008334 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8335 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008336 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008337 float musicVolDb = computeVolume(musicCurves,
8338 musicVolumeSrc,
8339 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008340 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008341 adjustAttenuation,
8342 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008343 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8344 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8345 if (volumeDb > minVolDb) {
8346 volumeDb = minVolDb;
8347 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008348 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008349 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8350 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008351 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8352 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8353 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8354 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008355 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008356 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008357 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8358 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008359 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8360 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008361 }
8362 }
jiabin9a3361e2019-10-01 09:38:30 -07008363 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008364 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008365 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008366 }
8367 }
8368
François Gaffie43c73442018-11-08 08:21:55 +01008369 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008370}
8371
Eric Laurent3839bc02018-07-10 18:33:34 -07008372int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008373 VolumeSource fromVolumeSource,
8374 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008375{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008376 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008377 return srcIndex;
8378 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008379 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8380 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008381 float minSrc = (float)srcCurves.getVolumeIndexMin();
8382 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8383 float minDst = (float)dstCurves.getVolumeIndexMin();
8384 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008385
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008386 // preserve mute request or correct range
8387 if (srcIndex < minSrc) {
8388 if (srcIndex == 0) {
8389 return 0;
8390 }
8391 srcIndex = minSrc;
8392 } else if (srcIndex > maxSrc) {
8393 srcIndex = maxSrc;
8394 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008395 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8396}
8397
François Gaffieaaac0fd2018-11-22 17:56:39 +01008398status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8399 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008400 int index,
8401 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008402 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008403 int delayMs,
8404 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008405{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008406 // do not change actual attributes volume if the attributes is muted
8407 if (outputDesc->isMuted(volumeSource)) {
8408 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8409 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008410 return NO_ERROR;
8411 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008412
Eric Laurentae6e88c2024-01-10 14:42:57 +01008413 bool isVoiceVolSrc;
8414 bool isBtScoVolSrc;
8415 if (!isVolumeConsistentForCalls(
8416 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008417 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008418 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008419 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008420 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008421
jiabin9a3361e2019-10-01 09:38:30 -07008422 if (deviceTypes.empty()) {
8423 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008424 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008425 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008426 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008427 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008428
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008429 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8430 ALOGE("invalid volume index range");
8431 return BAD_VALUE;
8432 }
8433
jiabin9a3361e2019-10-01 09:38:30 -07008434 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8435 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008436 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008437 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008438 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8439 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008440 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008441 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008442 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008443 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8444 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008445
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008446 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008447 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8448 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8449 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008450 }
Eric Laurente552edb2014-03-10 17:42:56 -07008451 return NO_ERROR;
8452}
8453
Eric Laurentae6e88c2024-01-10 14:42:57 +01008454void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008455 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008456 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008457 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008458 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008459 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008460 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8461 } else {
8462 voiceVolume = index == 0 ? 0.0 : 1.0;
8463 }
8464 if (voiceVolume != mLastVoiceVolume) {
8465 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8466 mLastVoiceVolume = voiceVolume;
8467 }
8468}
8469
8470bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8471 const DeviceTypeSet& deviceTypes,
8472 bool& isVoiceVolSrc,
8473 bool& isBtScoVolSrc,
8474 const char* caller) {
8475 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008476 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8477
Eric Laurentae6e88c2024-01-10 14:42:57 +01008478 const bool isScoRequested = isScoRequestedForComm();
8479 const bool isHAUsed = isHearingAidUsedForComm();
8480
Vlad Popa695b76b2024-06-14 16:49:25 -07008481 if (com_android_media_audio_replace_stream_bt_sco()) {
8482 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8483 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8484 (isScoRequested || isHAUsed);
8485 return true;
8486 }
8487
8488 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008489 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8490
8491 if ((callVolSrc != btScoVolSrc) &&
8492 ((isVoiceVolSrc && isScoRequested) ||
8493 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8494 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8495 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8496 volumeSource, isScoRequested ? " " : " not ");
8497 return false;
8498 }
8499 return true;
8500}
8501
Eric Laurentc75307b2015-03-17 15:29:32 -07008502void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008503 const DeviceTypeSet& deviceTypes,
8504 int delayMs,
8505 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008506{
jiabincd510522020-01-22 09:40:55 -08008507 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008508 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8509 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8510 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008511 curves.getVolumeIndex(deviceTypes),
8512 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008513 }
8514}
8515
François Gaffiec005e562018-11-06 15:04:49 +01008516void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8517 bool on,
8518 const sp<AudioOutputDescriptor>& outputDesc,
8519 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008520 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008521{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008522 std::vector<VolumeSource> sourcesToMute;
8523 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8524 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8525 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008526 VolumeSource source = toVolumeSource(attributes, false);
8527 if ((source != VOLUME_SOURCE_NONE) &&
8528 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8529 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008530 sourcesToMute.push_back(source);
8531 }
Eric Laurente552edb2014-03-10 17:42:56 -07008532 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008533 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008534 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008535 }
8536
Eric Laurente552edb2014-03-10 17:42:56 -07008537}
8538
François Gaffieaaac0fd2018-11-22 17:56:39 +01008539void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8540 bool on,
8541 const sp<AudioOutputDescriptor>& outputDesc,
8542 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008543 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008544{
jiabin9a3361e2019-10-01 09:38:30 -07008545 if (deviceTypes.empty()) {
8546 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008547 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008548 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008549 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008550 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008551 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008552 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008553 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8554 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008555 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008556 }
8557 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008558 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8559 // ignored
8560 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008561 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008562 if (!outputDesc->isMuted(volumeSource)) {
8563 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008564 return;
8565 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008566 if (outputDesc->decMuteCount(volumeSource) == 0) {
8567 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008568 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008569 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008570 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008571 delayMs);
8572 }
8573 }
8574}
8575
François Gaffie53615e22015-03-19 09:24:12 +01008576bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8577{
François Gaffiec005e562018-11-06 15:04:49 +01008578 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008579 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8580 return true;
8581 }
8582
8583 // has known usage?
8584 switch (paa->usage) {
8585 case AUDIO_USAGE_UNKNOWN:
8586 case AUDIO_USAGE_MEDIA:
8587 case AUDIO_USAGE_VOICE_COMMUNICATION:
8588 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8589 case AUDIO_USAGE_ALARM:
8590 case AUDIO_USAGE_NOTIFICATION:
8591 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8592 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8593 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8594 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8595 case AUDIO_USAGE_NOTIFICATION_EVENT:
8596 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8597 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8598 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8599 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008600 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008601 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008602 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008603 case AUDIO_USAGE_EMERGENCY:
8604 case AUDIO_USAGE_SAFETY:
8605 case AUDIO_USAGE_VEHICLE_STATUS:
8606 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008607 break;
8608 default:
8609 return false;
8610 }
8611 return true;
8612}
8613
François Gaffie2110e042015-03-24 08:41:51 +01008614audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8615{
8616 return mEngine->getForceUse(usage);
8617}
8618
Eric Laurent96d1dda2022-03-14 17:14:19 +01008619bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008620 return isStateInCall(mEngine->getPhoneState());
8621}
8622
Eric Laurent96d1dda2022-03-14 17:14:19 +01008623bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008624 return is_state_in_call(state);
8625}
8626
Eric Laurentf9cccec2022-11-16 19:12:00 +01008627bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008628 audio_mode_t mode = mEngine->getPhoneState();
8629 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008630 || (mode == AUDIO_MODE_CALL_SCREEN)
8631 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008632}
8633
Eric Laurentf9cccec2022-11-16 19:12:00 +01008634bool AudioPolicyManager::isInCallOrScreening() const {
8635 audio_mode_t mode = mEngine->getPhoneState();
8636 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8637}
8638
Eric Laurentd60560a2015-04-10 11:31:20 -07008639void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8640{
8641 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008642 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008643 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008644 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008645 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008646 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008647 }
8648 }
8649
8650 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8651 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8652 bool release = false;
8653 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8654 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8655 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8656 source->ext.device.type == deviceDesc->type()) {
8657 release = true;
8658 }
8659 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008660 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008661 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8662 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8663 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008664 sink->ext.device.type == deviceDesc->type() &&
8665 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8666 || strncmp(sink->ext.device.address, address,
8667 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008668 release = true;
8669 }
8670 }
8671 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008672 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8673 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008674 }
8675 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008676
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008677 mInputs.clearSessionRoutesForDevice(deviceDesc);
8678
Francois Gaffie716e1432019-01-14 16:58:59 +01008679 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008680}
8681
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008682void AudioPolicyManager::modifySurroundFormats(
8683 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008684 std::unordered_set<audio_format_t> enforcedSurround(
8685 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008686 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008687 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008688 allSurround.insert(pair.first);
8689 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8690 }
Phil Burk09bc4612016-02-24 15:58:15 -08008691
8692 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8693 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008694 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008695 // This is the resulting set of formats depending on the surround mode:
8696 // 'all surround' = allSurround
8697 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8698 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8699 // 'manual surround' = mManualSurroundFormats
8700 // AUTO: formats v 'enforced surround'
8701 // ALWAYS: formats v 'all surround' v 'enforced surround'
8702 // NEVER: formats ^ 'non-surround'
8703 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008704
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008705 std::unordered_set<audio_format_t> formatSet;
8706 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8707 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008708 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008709 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008710 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008711 formatSet.insert(*formatIter);
8712 }
8713 }
8714 } else {
8715 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8716 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008717 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008718
jiabin81772902018-04-02 17:52:27 -07008719 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008720 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008721 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8722 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8723 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008724 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008725 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8726 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8727 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008728 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008729 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008730 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008731 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008732 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008733 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008734}
8735
jiabin06e4bab2019-07-29 10:13:34 -07008736void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8737 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008738 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8739 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8740
8741 // If NEVER, then remove support for channelMasks > stereo.
8742 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008743 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8744 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008745 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008746 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008747 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008748 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008749 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008750 }
8751 }
jiabin81772902018-04-02 17:52:27 -07008752 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8753 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8754 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008755 bool supports5dot1 = false;
8756 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008757 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008758 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8759 supports5dot1 = true;
8760 break;
8761 }
8762 }
8763 // If not then add 5.1 support.
8764 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008765 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008766 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008767 }
Phil Burk09bc4612016-02-24 15:58:15 -08008768 }
8769}
8770
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008771void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008772 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008773 const sp<IOProfile>& profile) {
8774 if (!profile->hasDynamicAudioProfile()) {
8775 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008776 }
François Gaffie112b0af2015-11-19 16:13:25 +01008777
jiabin12537fc2023-10-12 17:56:08 +00008778 audio_port_v7 devicePort;
8779 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008780
jiabin12537fc2023-10-12 17:56:08 +00008781 audio_port_v7 mixPort;
8782 profile->toAudioPort(&mixPort);
8783 mixPort.ext.mix.handle = ioHandle;
8784
8785 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8786 if (status != NO_ERROR) {
8787 ALOGE("%s failed to query the attributes of the mix port", __func__);
8788 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008789 }
jiabin12537fc2023-10-12 17:56:08 +00008790
8791 std::set<audio_format_t> supportedFormats;
8792 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8793 supportedFormats.insert(mixPort.audio_profiles[i].format);
8794 }
8795 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8796 mReportedFormatsMap[devDesc] = formats;
8797
8798 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8799 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8800 modifySurroundFormats(devDesc, &formats);
8801 size_t modifiedNumProfiles = 0;
8802 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8803 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8804 formats.end()) {
8805 // Skip the format that is not present after modifying surround formats.
8806 continue;
8807 }
8808 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8809 sizeof(struct audio_profile));
8810 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8811 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8812 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8813 modifySurroundChannelMasks(&channels);
8814 std::copy(channels.begin(), channels.end(),
8815 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8816 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8817 }
8818 mixPort.num_audio_profiles = modifiedNumProfiles;
8819 }
8820 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008821}
Eric Laurentd60560a2015-04-10 11:31:20 -07008822
Mikhail Naganovdc769682018-05-04 15:34:08 -07008823status_t AudioPolicyManager::installPatch(const char *caller,
8824 audio_patch_handle_t *patchHandle,
8825 AudioIODescriptorInterface *ioDescriptor,
8826 const struct audio_patch *patch,
8827 int delayMs)
8828{
8829 ssize_t index = mAudioPatches.indexOfKey(
8830 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8831 *patchHandle : ioDescriptor->getPatchHandle());
8832 sp<AudioPatch> patchDesc;
8833 status_t status = installPatch(
8834 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8835 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008836 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008837 }
8838 return status;
8839}
8840
8841status_t AudioPolicyManager::installPatch(const char *caller,
8842 ssize_t index,
8843 audio_patch_handle_t *patchHandle,
8844 const struct audio_patch *patch,
8845 int delayMs,
8846 uid_t uid,
8847 sp<AudioPatch> *patchDescPtr)
8848{
8849 sp<AudioPatch> patchDesc;
8850 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8851 if (index >= 0) {
8852 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008853 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008854 }
8855
8856 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8857 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8858 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8859 if (status == NO_ERROR) {
8860 if (index < 0) {
8861 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008862 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008863 } else {
8864 patchDesc->mPatch = *patch;
8865 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008866 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008867 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008868 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008869 }
8870 nextAudioPortGeneration();
8871 mpClientInterface->onAudioPatchListUpdate();
8872 }
8873 if (patchDescPtr) *patchDescPtr = patchDesc;
8874 return status;
8875}
8876
jiabinbce0c1d2020-10-05 11:20:18 -07008877bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8878{
8879 const TrackClientVector activeClients = output->getActiveClients();
8880 if (activeClients.empty()) {
8881 return true;
8882 }
8883 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8884 if (index < 0) {
8885 ALOGE("%s, no audio patch found while there are active clients on output %d",
8886 __func__, output->getId());
8887 return false;
8888 }
8889 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8890 DeviceVector routedDevices;
8891 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8892 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8893 patchDesc->mPatch.sinks[i].id);
8894 if (device == nullptr) {
8895 ALOGE("%s, no audio device found with id(%d)",
8896 __func__, patchDesc->mPatch.sinks[i].id);
8897 return false;
8898 }
8899 routedDevices.add(device);
8900 }
8901 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008902 if (client->isInvalid()) {
8903 // No need to take care about invalidated clients.
8904 continue;
8905 }
jiabinbce0c1d2020-10-05 11:20:18 -07008906 sp<DeviceDescriptor> preferredDevice =
8907 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8908 if (mEngine->getOutputDevicesForAttributes(
8909 client->attributes(), preferredDevice, false) == routedDevices) {
8910 return false;
8911 }
8912 }
8913 return true;
8914}
8915
8916sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008917 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008918 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8919 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008920{
8921 for (const auto& device : devices) {
8922 // TODO: This should be checking if the profile supports the device combo.
8923 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008924 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8925 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008926 return nullptr;
8927 }
8928 }
8929 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8930 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008931 status_t status = desc->open(halConfig, mixerConfig, devices,
8932 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008933 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008934 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008935 return nullptr;
8936 }
jiabin14b50cc2023-12-13 19:01:52 +00008937 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8938 auto portConfig = desc->getConfig();
8939 for (const auto& device : devices) {
8940 device->setPreferredConfig(&portConfig);
8941 }
8942 }
jiabinbce0c1d2020-10-05 11:20:18 -07008943
8944 // Here is where the out_set_parameters() for card & device gets called
8945 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8946 const audio_devices_t deviceType = device->type();
8947 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008948 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008949 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8950 mpClientInterface->setParameters(output, String8(param));
8951 free(param);
8952 }
jiabin12537fc2023-10-12 17:56:08 +00008953 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008954 if (!profile->hasValidAudioProfile()) {
8955 ALOGW("%s() missing param", __func__);
8956 desc->close();
8957 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008958 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8959 // Reopen the output with the best audio profile picked by APM when the profile supports
8960 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008961 desc->close();
8962 output = AUDIO_IO_HANDLE_NONE;
8963 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8964 profile->pickAudioProfile(
8965 config.sample_rate, config.channel_mask, config.format);
8966 config.offload_info.sample_rate = config.sample_rate;
8967 config.offload_info.channel_mask = config.channel_mask;
8968 config.offload_info.format = config.format;
8969
jiabina84c3d32022-12-02 18:59:55 +00008970 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008971 if (status != NO_ERROR) {
8972 return nullptr;
8973 }
8974 }
8975
8976 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008977 setOutputDevices(__func__, desc,
8978 devices,
8979 true,
8980 0,
8981 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008982 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8983 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8984
jiabinbce0c1d2020-10-05 11:20:18 -07008985 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8986 sp<AudioPolicyMix> policyMix;
8987 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8988 policyMix->setOutput(desc);
8989 desc->mPolicyMix = policyMix;
8990 } else {
8991 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008992 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008993 }
8994
baek.kim -61c20122022-07-27 10:05:32 +00008995 } else if (hasPrimaryOutput() && speaker != nullptr
8996 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008997 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8998 // no duplicated output for:
8999 // - direct outputs
9000 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009001 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009002 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9003
9004 //TODO: configure audio effect output stage here
9005
9006 // open a duplicating output thread for the new output and the primary output
9007 sp<SwAudioOutputDescriptor> dupOutputDesc =
9008 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9009 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9010 if (status == NO_ERROR) {
9011 // add duplicated output descriptor
9012 addOutput(duplicatedOutput, dupOutputDesc);
9013 } else {
9014 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9015 mPrimaryOutput->mIoHandle, output);
9016 desc->close();
9017 removeOutput(output);
9018 nextAudioPortGeneration();
9019 return nullptr;
9020 }
9021 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009022 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9023 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9024 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009025 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009026 }
jiabinbce0c1d2020-10-05 11:20:18 -07009027 return desc;
9028}
9029
jiabinf1c73972022-04-14 16:28:52 -07009030status_t AudioPolicyManager::getDevicesForAttributes(
9031 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
9032 // Devices are determined in the following precedence:
9033 //
9034 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9035 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9036 //
9037 // If no such dynamic policy then
9038 // 2) Devices containing an active client using setPreferredDevice
9039 // with same strategy as the attributes.
9040 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9041 //
9042 // If no corresponding active client with setPreferredDevice then
9043 // 3) Devices associated with the strategy determined by the attributes
9044 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9045 //
9046 // See related getOutputForAttrInt().
9047
9048 // check dynamic policies but only for primary descriptors (secondary not used for audible
9049 // audio routing, only used for duplication for playback capture)
9050 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009051 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009052 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009053 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9054 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9055 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009056 if (status != OK) {
9057 return status;
9058 }
9059
9060 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9061 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9062 // as they are unaffected by device/stream volume
9063 // (per SwAudioOutputDescriptor::isFixedVolume()).
9064 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9065 ) {
9066 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9067 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9068 devices.add(deviceDesc);
9069 } else {
9070 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9071 // which selects setPreferredDevice if active. This means forVolume call
9072 // will take an active setPreferredDevice, if such exists.
9073
9074 devices = mEngine->getOutputDevicesForAttributes(
9075 attr, nullptr /* preferredDevice */, false /* fromCache */);
9076 }
9077
9078 if (forVolume) {
9079 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9080 // for single volume control in AudioService (such relationship should exist if
9081 // SPEAKER_SAFE is present).
9082 //
9083 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9084 DeviceVector speakerSafeDevices =
9085 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9086 if (!speakerSafeDevices.isEmpty()) {
9087 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9088 devices.remove(speakerSafeDevices);
9089 }
9090 }
9091
9092 return NO_ERROR;
9093}
9094
9095status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9096 AudioProfileVector& audioProfiles,
9097 uint32_t flags,
9098 bool isInput) {
9099 for (const auto& hwModule : mHwModules) {
9100 // the MSD module checks for different conditions
9101 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9102 continue;
9103 }
9104 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9105 : hwModule->getOutputProfiles();
9106 for (const auto& profile : ioProfiles) {
9107 if (!profile->areAllDevicesSupported(devices) ||
9108 !profile->isCompatibleProfileForFlags(
9109 flags, false /*exactMatchRequiredForInputFlags*/)) {
9110 continue;
9111 }
9112 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9113 }
9114 }
9115
9116 if (!isInput) {
9117 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9118 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9119 if (msdModule != nullptr) {
9120 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9121 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9122 for (const auto &profile: msdModule->getOutputProfiles()) {
9123 if (!profile->asAudioPort()->isDirectOutput()) {
9124 continue;
9125 }
9126 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9127 }
9128 } else {
9129 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9130 }
9131 }
9132 }
9133
9134 return NO_ERROR;
9135}
9136
jiabin3ff8d7d2022-12-13 06:27:44 +00009137sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9138 const audio_config_t *config,
9139 audio_output_flags_t flags,
9140 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009141 closeOutput(outputDesc->mIoHandle);
9142 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9143 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9144 if (preferredOutput == nullptr) {
9145 ALOGE("%s failed to reopen output device=%d, caller=%s",
9146 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009147 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009148 return preferredOutput;
9149}
9150
9151void AudioPolicyManager::reopenOutputsWithDevices(
9152 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9153 for (const auto& [output, devices] : outputsToReopen) {
9154 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9155 closeOutput(output);
9156 openOutputWithProfileAndDevice(desc->mProfile, devices);
9157 }
jiabina84c3d32022-12-02 18:59:55 +00009158}
9159
jiabinc44b3462022-12-08 12:52:31 -08009160PortHandleVector AudioPolicyManager::getClientsForStream(
9161 audio_stream_type_t streamType) const {
9162 PortHandleVector clients;
9163 for (size_t i = 0; i < mOutputs.size(); ++i) {
9164 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9165 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9166 }
9167 return clients;
9168}
9169
9170void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9171 PortHandleVector clients;
9172 for (auto stream : streams) {
9173 PortHandleVector clientsForStream = getClientsForStream(stream);
9174 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9175 }
9176 mpClientInterface->invalidateTracks(clients);
9177}
9178
jiabin220eea12024-05-17 17:55:20 +00009179void AudioPolicyManager::updateClientsInternalMute(
9180 const sp<android::SwAudioOutputDescriptor> &desc) {
9181 if (!desc->isBitPerfect() ||
9182 !com::android::media::audioserver::
9183 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9184 // This is only used for bit perfect output now.
9185 return;
9186 }
9187 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9188 bool bitPerfectClientInternalMute = false;
9189 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9190 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9191 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9192 bitPerfectClient = client;
9193 continue;
9194 }
9195 bool muted = false;
9196 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9197 // System sound is muted.
9198 muted = true;
9199 } else {
9200 bitPerfectClientInternalMute = true;
9201 }
9202 if (client->setInternalMute(muted)) {
9203 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9204 if (!result.ok()) {
9205 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9206 continue;
9207 }
9208 media::TrackInternalMuteInfo info;
9209 info.portId = result.value();
9210 info.muted = client->getInternalMute();
9211 clientsInternalMute.push_back(std::move(info));
9212 }
9213 }
9214 if (bitPerfectClient != nullptr &&
9215 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9216 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9217 if (result.ok()) {
9218 media::TrackInternalMuteInfo info;
9219 info.portId = result.value();
9220 info.muted = bitPerfectClient->getInternalMute();
9221 clientsInternalMute.push_back(std::move(info));
9222 } else {
9223 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9224 __func__, bitPerfectClient->portId());
9225 }
9226 }
9227 if (!clientsInternalMute.empty()) {
9228 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9229 status != NO_ERROR) {
9230 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9231 }
9232 }
9233}
9234
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009235} // namespace android