blob: 2024f04fa9d28613042802ddc39a0b09d52e8dac [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())
Andy Hungdb27c442024-08-14 11:37:57 -07001295 && (!audio_is_linear_pcm(config->format) ||
1296 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001297 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001298 return BAD_VALUE;
1299 }
1300 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001301 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001302 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1303 primaryMix->mDeviceAddress,
1304 AUDIO_FORMAT_DEFAULT);
1305 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001306 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001307 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1308 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001309 // if a direct output can be opened to deliver the track's multi-channel content to the
1310 // output rather than being downmixed by the primary output, then use this direct
1311 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1312 // mix.
1313 bool tryDirectForChannelMask = policyDesc != nullptr
1314 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1315 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001316 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001317 audio_io_handle_t newOutput;
1318 status = openDirectOutput(
1319 *stream, session, config,
1320 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001321 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001322 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001323 policyDesc = mOutputs.valueFor(newOutput);
1324 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001325 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001326 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001327 policyDesc = nullptr;
1328 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001329 }
1330 if (policyDesc != nullptr) {
1331 policyDesc->mPolicyMix = primaryMix;
1332 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001333 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1334 : AUDIO_PORT_HANDLE_NONE;
1335 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1336 // Remove direct flag as it is not on a direct output.
1337 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1338 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001339
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001340 ALOGV("getOutputForAttr() returns output %d", *output);
1341 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1342 *outputType = API_OUT_MIX_PLAYBACK;
1343 } else {
1344 *outputType = API_OUTPUT_LEGACY;
1345 }
1346 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001347 } else {
1348 if (policyMixDevice != nullptr) {
1349 ALOGE("%s, try to use primary mix but no output found", __func__);
1350 return INVALID_OPERATION;
1351 }
1352 // Fallback to default engine selection as the selected primary mix device is not
1353 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001354 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001355 }
François Gaffiec005e562018-11-06 15:04:49 +01001356 // Virtual sources must always be dynamicaly or explicitly routed
1357 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1358 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1359 return BAD_VALUE;
1360 }
1361 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1362 // in order to let the choice of the order to future vendor engine
1363 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001364
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001365 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001366 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001367 }
1368
Nadav Barb2f18162018-07-18 13:01:53 +03001369 // Set incall music only if device was explicitly set, and fallback to the device which is
1370 // chosen by the engine if not.
1371 // FIXME: provide a more generic approach which is not device specific and move this back
1372 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001373 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001374 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001375 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001376 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001377 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001378 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001379 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001380 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001381 }
1382 }
1383
François Gaffiec005e562018-11-06 15:04:49 +01001384 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1385 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1386 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001387
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001388 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001389 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001390 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001391 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001392 ALOGV("%s() Using MSD devices %s instead of devices %s",
1393 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 } else {
1395 *output = AUDIO_IO_HANDLE_NONE;
1396 }
1397 }
1398 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001399 sp<PreferredMixerAttributesInfo> info = nullptr;
1400 if (outputDevices.size() == 1) {
1401 info = getPreferredMixerAttributesInfo(
1402 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001403 mEngine->getProductStrategyForAttributes(*resultAttr),
1404 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001405 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1406 // and it is currently active.
1407 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001408 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001409 info = nullptr;
1410 }
jiabin220eea12024-05-17 17:55:20 +00001411 if (com::android::media::audioserver::
1412 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1413 if (info != nullptr && info->getUid() == uid &&
1414 info->configMatches(*config) &&
1415 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1416 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1417 [this, &outputDevices](audio_usage_t usage) {
1418 return mOutputs.isUsageActiveOnDevice(
1419 usage, outputDevices[0]); }))) {
1420 // Bit-perfect request is not allowed when the phone mode is not normal or
1421 // there is any higher priority user case active.
1422 return INVALID_OPERATION;
1423 }
1424 }
jiabina84c3d32022-12-02 18:59:55 +00001425 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001426 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001427 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001428 // The client will be active if the client is currently preferred mixer owner and the
1429 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001430 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001431 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001432 && info->getUid() == uid
1433 && *output != AUDIO_IO_HANDLE_NONE
1434 // When bit-perfect output is selected for the preferred mixer attributes owner,
1435 // only need to consider the config matches.
1436 && mOutputs.valueFor(*output)->isConfigurationMatched(
1437 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001438
1439 if (*isBitPerfect) {
1440 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1441 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001442 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001443 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001444 AudioProfileVector profiles;
1445 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1446 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001447 const auto channels = profiles[0]->getChannels();
1448 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1449 config->channel_mask = *channels.begin();
1450 }
1451 const auto sampleRates = profiles[0]->getSampleRates();
1452 if (!sampleRates.empty() &&
1453 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1454 config->sample_rate = *sampleRates.begin();
1455 }
jiabinf1c73972022-04-14 16:28:52 -07001456 config->format = profiles[0]->getFormat();
1457 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001458 return INVALID_OPERATION;
1459 }
Paul McLeanaa981192015-03-21 09:55:15 -07001460
François Gaffiec005e562018-11-06 15:04:49 +01001461 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001462 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001463 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001464 *selectedDeviceId = outputDevice->getId();
1465 break;
1466 }
1467 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001468
Eric Laurent8a1095a2019-11-08 14:44:16 -08001469 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1470 *outputType = API_OUTPUT_TELEPHONY_TX;
1471 } else {
1472 *outputType = API_OUTPUT_LEGACY;
1473 }
1474
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001475 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1476
1477 return NO_ERROR;
1478}
1479
1480status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1481 audio_io_handle_t *output,
1482 audio_session_t session,
1483 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001484 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001485 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001486 audio_output_flags_t *flags,
1487 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001488 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001489 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001490 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001491 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001492 bool *isBitPerfect,
1493 float *volume)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001494{
1495 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1496 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1497 return INVALID_OPERATION;
1498 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001499 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001500 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001501 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001502 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001503 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001504 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001505 const sp<DeviceDescriptor> requestedDevice =
1506 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1507
1508 // Prevent from storing invalid requested device id in clients
1509 const audio_port_handle_t sanitizedRequestedPortId =
1510 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1511 *selectedDeviceId = sanitizedRequestedPortId;
1512
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001513 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001514 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001515 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1516 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001517 if (status != NO_ERROR) {
1518 return status;
1519 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001520 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001521 if (secondaryOutputs != nullptr) {
1522 for (auto &secondaryMix : secondaryMixes) {
1523 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1524 if (outputDesc != nullptr &&
1525 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1526 secondaryOutputs->push_back(outputDesc->mIoHandle);
1527 weakSecondaryOutputDescs.push_back(outputDesc);
1528 }
1529 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001530 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001531
Eric Laurent8fc147b2018-07-22 19:13:55 -07001532 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001533 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001534 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001535 };
jiabin4ef93452019-09-10 14:29:54 -07001536 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001537
Eric Laurentc209fe42020-06-05 18:11:23 -07001538 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001539 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001540 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001541 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001542 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001543 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001544 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001545 std::move(weakSecondaryOutputDescs),
1546 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001547 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001548
Andy Hung6b137d12024-08-27 22:35:17 +00001549 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
1550
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001551 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1552 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001553
Eric Laurente83b55d2014-11-14 10:06:21 -08001554 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001555}
1556
Eric Laurentc529cf62020-04-17 18:19:10 -07001557status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1558 audio_session_t session,
1559 const audio_config_t *config,
1560 audio_output_flags_t flags,
1561 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001562 audio_io_handle_t *output,
1563 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001564
1565 *output = AUDIO_IO_HANDLE_NONE;
1566
1567 // skip direct output selection if the request can obviously be attached to a mixed output
1568 // and not explicitly requested
1569 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1570 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1571 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1572 return NAME_NOT_FOUND;
1573 }
1574
1575 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1576 // This prevents creating an offloaded track and tearing it down immediately after start
1577 // when audioflinger detects there is an active non offloadable effect.
1578 // FIXME: We should check the audio session here but we do not have it in this context.
1579 // This may prevent offloading in rare situations where effects are left active by apps
1580 // in the background.
1581 sp<IOProfile> profile;
1582 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1583 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1584 profile = getProfileForOutput(
1585 devices, config->sample_rate, config->format, config->channel_mask,
1586 flags, true /* directOnly */);
1587 }
1588
1589 if (profile == nullptr) {
1590 return NAME_NOT_FOUND;
1591 }
1592
1593 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1594 for (size_t i = 0; i < mOutputs.size(); i++) {
1595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1596 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1597 // reuse direct output if currently open by the same client
1598 // and configured with same parameters
1599 if ((config->sample_rate == desc->getSamplingRate()) &&
1600 (config->format == desc->getFormat()) &&
1601 (config->channel_mask == desc->getChannelMask()) &&
1602 (session == desc->mDirectClientSession)) {
1603 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301604 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001605 mOutputs.keyAt(i), session);
1606 *output = mOutputs.keyAt(i);
1607 return NO_ERROR;
1608 }
1609 }
1610 }
1611
1612 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001613 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301614 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1615 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001616 return NAME_NOT_FOUND;
1617 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1618 // MMAP gracefully handles lack of an exclusive track resource by mixing
1619 // above the audio framework. For AAudio to know that the limit is reached,
1620 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301621 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1622 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001623 return NAME_NOT_FOUND;
1624 } else {
1625 // Close outputs on this profile, if available, to free resources for this request
1626 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1627 const auto desc = mOutputs.valueAt(i);
1628 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301629 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1630 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001631 closeOutput(desc->mIoHandle);
1632 }
1633 }
1634 }
1635 }
1636
1637 // Unable to close streams to find free resources for this request
1638 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301639 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1640 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001641 return NAME_NOT_FOUND;
1642 }
1643
Atneya Nairb16666a2023-12-11 20:18:33 -08001644 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001645
Michael Chan6fb34492020-12-08 15:44:49 +11001646 // An MSD patch may be using the only output stream that can service this request. Release
1647 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001649
Eric Laurentf1f22e72021-07-13 14:04:14 +02001650 status_t status =
Haofan Wangf6e304f2024-07-09 23:06:58 -07001651 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1652 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001653
1654 // only accept an output with the requested parameters
1655 if (status != NO_ERROR ||
1656 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1657 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1658 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1659 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1660 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1661 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1662 config->channel_mask, outputDesc->getChannelMask());
1663 if (*output != AUDIO_IO_HANDLE_NONE) {
1664 outputDesc->close();
1665 }
1666 // fall back to mixer output if possible when the direct output could not be open
1667 if (audio_is_linear_pcm(config->format) &&
1668 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1669 return NAME_NOT_FOUND;
1670 }
1671 *output = AUDIO_IO_HANDLE_NONE;
1672 return BAD_VALUE;
1673 }
1674 outputDesc->mDirectOpenCount = 1;
1675 outputDesc->mDirectClientSession = session;
1676
1677 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001678 setOutputDevices(__func__, outputDesc,
1679 devices,
1680 true,
1681 0,
1682 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001683 mPreviousOutputs = mOutputs;
1684 ALOGV("%s returns new direct output %d", __func__, *output);
1685 mpClientInterface->onAudioPortListUpdate();
1686 return NO_ERROR;
1687}
1688
François Gaffie11d30102018-11-02 16:09:09 +01001689audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1690 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001691 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001692 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001693 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001694 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001695 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001696 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001697 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001698{
Andy Hungc88b0642018-04-27 15:42:35 -07001699 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001700
jiabine375d412019-02-26 12:54:53 -08001701 // Discard haptic channel mask when forcing muting haptic channels.
1702 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001703 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1704 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001705
Eric Laurente552edb2014-03-10 17:42:56 -07001706 // open a direct output if required by specified parameters
1707 //force direct flag if offload flag is set: offloading implies a direct output stream
1708 // and all common behaviors are driven by checking only the direct flag
1709 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001710 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1711 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001712 }
Nadav Bar766fb022018-01-07 12:18:03 +02001713 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1714 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001715 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001716
1717 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1718
Eric Laurente83b55d2014-11-14 10:06:21 -08001719 // only allow deep buffering for music stream type
1720 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001721 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001722 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001723 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001724 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1725 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001726 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001727 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001728 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001729 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001730 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001731 audio_is_linear_pcm(config->format) &&
1732 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001733 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001734 AUDIO_OUTPUT_FLAG_DIRECT);
1735 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001736 }
Eric Laurente552edb2014-03-10 17:42:56 -07001737
Carter Hsua3abb402021-10-26 11:11:20 +08001738 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1739 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1740 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1741 }
1742
Eric Laurentf9230d52024-01-26 18:49:09 +01001743 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001744 // was specified and offload or direct playback is not explicitly requested, and there is no
1745 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001746 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001747 if (mSpatializerOutput != nullptr &&
1748 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1749 prefMixerConfigInfo == nullptr &&
1750 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1751 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001752 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001753 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001754 }
1755
Eric Laurentc529cf62020-04-17 18:19:10 -07001756 audio_config_t directConfig = *config;
1757 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001758
1759 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1760 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001761 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001762 return output;
1763 }
1764
Eric Laurent14cbfca2016-03-17 09:42:16 -07001765 // A request for HW A/V sync cannot fallback to a mixed output because time
1766 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001767 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001768 return AUDIO_IO_HANDLE_NONE;
1769 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001770 // A request for Tuner cannot fallback to a mixed output
1771 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1772 return AUDIO_IO_HANDLE_NONE;
1773 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001774
Eric Laurente552edb2014-03-10 17:42:56 -07001775 // ignoring channel mask due to downmix capability in mixer
1776
1777 // open a non direct output
1778
1779 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001780 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001781 // get which output is suitable for the specified stream. The actual
1782 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001783 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001784 if (prefMixerConfigInfo != nullptr) {
1785 for (audio_io_handle_t outputHandle : outputs) {
1786 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1787 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1788 output = outputHandle;
1789 break;
1790 }
1791 }
1792 if (output == AUDIO_IO_HANDLE_NONE) {
1793 // No output open with the preferred profile. Open a new one.
1794 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1795 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1796 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1797 config.format = prefMixerConfigInfo->getConfigBase().format;
1798 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1799 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1800 &config, prefMixerConfigInfo->getFlags());
1801 if (preferredOutput == nullptr) {
1802 ALOGE("%s failed to open output with preferred mixer config", __func__);
1803 } else {
1804 output = preferredOutput->mIoHandle;
1805 }
1806 }
1807 } else {
1808 // at this stage we should ignore the DIRECT flag as no direct output could be
1809 // found earlier
1810 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001811 if (com::android::media::audioserver::
1812 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1813 // If the preferred mixer attributes is null, do not select the bit-perfect output
1814 // unless the bit-perfect output is the only output.
1815 // The bit-perfect output can exist while the passed in preferred mixer attributes
1816 // info is null when it is a high priority client. The high priority clients are
1817 // ringtone or alarm, which is not a bit-perfect use case.
1818 size_t i = 0;
1819 while (i < outputs.size() && outputs.size() > 1) {
1820 auto desc = mOutputs.valueFor(outputs[i]);
1821 // The output descriptor must not be null here.
1822 if (desc->isBitPerfect()) {
1823 outputs.removeItemsAt(i);
1824 } else {
1825 i += 1;
1826 }
1827 }
1828 }
jiabina84c3d32022-12-02 18:59:55 +00001829 output = selectOutput(
1830 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1831 }
Eric Laurente552edb2014-03-10 17:42:56 -07001832 }
François Gaffie11d30102018-11-02 16:09:09 +01001833 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001834 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001835 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001836
Eric Laurente552edb2014-03-10 17:42:56 -07001837 return output;
1838}
1839
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001840sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001841 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1842 mAvailableInputDevices);
1843 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1844}
1845
1846DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1847 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1848 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849}
1850
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001851const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001853 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1854 if (msdModule != 0) {
1855 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1856 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1857 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1858 const struct audio_port_config *source = &patch->mPatch.sources[j];
1859 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1860 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001861 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001862 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001863 }
1864 }
1865 }
1866 return msdPatches;
1867}
1868
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001869bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1870 ssize_t index = mAudioPatches.indexOfKey(handle);
1871 if (index < 0) {
1872 return false;
1873 }
1874 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1875 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1876 if (msdModule == nullptr) {
1877 return false;
1878 }
1879 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1880 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1881 return true;
1882 }
1883 index = getMsdOutputPatches().indexOfKey(handle);
1884 if (index < 0) {
1885 return false;
1886 }
1887 return true;
1888}
1889
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1891 const InputProfileCollection &inputProfiles,
1892 const OutputProfileCollection &outputProfiles,
1893 const sp<DeviceDescriptor> &sourceDevice,
1894 const sp<DeviceDescriptor> &sinkDevice,
1895 AudioProfileVector& sourceProfiles,
1896 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001897 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001898 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 return NO_INIT;
1900 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001902 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 return NO_INIT;
1904 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001906 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1907 inProfile->supportsDevice(sourceDevice)) {
1908 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001909 }
1910 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001911 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001912 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001913 outProfile->supportsDevice(sinkDevice)) {
1914 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001915 }
1916 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001917 return NO_ERROR;
1918}
1919
1920status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1921 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1922 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1923{
Dean Wheatley16809da2022-12-09 14:55:46 +11001924 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1925 static const std::vector<audio_format_t> formatsOrder = {{
1926 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001927 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1928 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001929 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1930 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1931 // preferred).
1932 std::vector<audio_channel_mask_t> masks = {{
1933 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1934 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1935 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1936 // insert index masks (higher counts most preferred) as preferred over position masks
1937 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1938 masks.insert(
1939 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1940 }
1941 return masks;
1942 }();
1943
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001944 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001945 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1946 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001948 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1949 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001950 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 }
1952 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1953 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1954 sinkConfig->format = bestSinkConfig.format;
1955 // For encoded streams force direct flag to prevent downstream mixing.
1956 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1957 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001958 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1959 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001960 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001961 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1962 // raw and IEC61937 framed streams.
1963 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1964 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1965 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1967 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001968 sourceConfig->channel_mask =
1969 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1970 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1971 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001972 sourceConfig->format = bestSinkConfig.format;
1973 // Copy input stream directly without any processing (e.g. resampling).
1974 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1975 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1976 if (hwAvSync) {
1977 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1978 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1979 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1980 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1981 }
1982 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1983 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1984 sinkConfig->config_mask |= config_mask;
1985 sourceConfig->config_mask |= config_mask;
1986 return NO_ERROR;
1987}
1988
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001989PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1990 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001991{
1992 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001993 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1994 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1995 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1996 if (deviceModule == nullptr) {
1997 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1998 return patchBuilder;
1999 }
2000 const InputProfileCollection inputProfiles = msdIsSource ?
2001 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2002 const OutputProfileCollection outputProfiles = msdIsSource ?
2003 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2004
2005 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2006 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2007 device : getMsdAudioOutDevices().itemAt(0);
2008 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2009
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2011 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002012 AudioProfileVector sourceProfiles;
2013 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002014 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2015 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002016 for (auto hwAvSync : { true, false }) {
2017 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2018 sourceProfiles, sinkProfiles) != NO_ERROR) {
2019 continue;
2020 }
2021 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2022 &sinkConfig) == NO_ERROR) {
2023 // Found a matching config. Re-create PatchBuilder with this config.
2024 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2025 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002026 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002027 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002028 " supporting PCM format conversion.", __func__);
2029 return patchBuilder;
2030}
2031
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002032status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002033 DeviceVector devices;
2034 if (outputDevices != nullptr && outputDevices->size() > 0) {
2035 devices.add(*outputDevices);
2036 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002037 // Use media strategy for unspecified output device. This should only
2038 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2039 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002040 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002041 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002042 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002043 }
Michael Chan6fb34492020-12-08 15:44:49 +11002044 std::vector<PatchBuilder> patchesToCreate;
2045 for (auto i = 0u; i < devices.size(); ++i) {
2046 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002047 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002048 }
2049 // Retain only the MSD patches associated with outputDevices request.
2050 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002051 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002052 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2053 auto retainedPatch = false;
2054 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2055 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2056 patchesToRemove.removeItemsAt(i);
2057 retainedPatch = true;
2058 break;
2059 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002060 }
Michael Chan6fb34492020-12-08 15:44:49 +11002061 if (retainedPatch) {
2062 it = patchesToCreate.erase(it);
2063 continue;
2064 }
2065 ++it;
2066 }
2067 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2068 return NO_ERROR;
2069 }
2070 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2071 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002072 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002073 }
Michael Chan6fb34492020-12-08 15:44:49 +11002074 status_t status = NO_ERROR;
2075 for (const auto &p : patchesToCreate) {
2076 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2077 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2078 char message[256];
2079 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2080 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2081 currStatus == NO_ERROR ? "Success" : "Error",
2082 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2083 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2084 if (currStatus == NO_ERROR) {
2085 ALOGD("%s", message);
2086 } else {
2087 ALOGE("%s", message);
2088 if (status == NO_ERROR) {
2089 status = currStatus;
2090 }
2091 }
2092 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002093 return status;
2094}
2095
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002096void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2097 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002098 for (size_t i = 0; i < msdPatches.size(); i++) {
2099 const auto& patch = msdPatches[i];
2100 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2101 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2102 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2103 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2104 releaseAudioPatch(patch->getHandle(), mUidCached);
2105 break;
2106 }
2107 }
2108 }
2109}
2110
Dorin Drimus94d94412022-02-02 09:05:02 +01002111bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002112 DeviceVector devicesToCheck =
2113 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002114 AudioPatchCollection msdPatches = getMsdOutputPatches();
2115 for (size_t i = 0; i < msdPatches.size(); i++) {
2116 const auto& patch = msdPatches[i];
2117 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2118 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2119 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2120 const auto& foundDevice = devicesToCheck.getDevice(
2121 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2122 if (foundDevice != nullptr) {
2123 devicesToCheck.remove(foundDevice);
2124 if (devicesToCheck.isEmpty()) {
2125 return true;
2126 }
2127 }
2128 }
2129 }
2130 }
2131 return false;
2132}
2133
Eric Laurente0720872014-03-11 09:30:41 -07002134audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002135 audio_output_flags_t flags,
2136 audio_format_t format,
2137 audio_channel_mask_t channelMask,
2138 uint32_t samplingRate,
2139 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002140{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002141 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2142 "%s called with format %#x", __func__, format);
2143
jiabinebb6af42020-06-09 17:31:17 -07002144 // Return the output that haptic-generating attached to when 1) session id is specified,
2145 // 2) haptic-generating effect exists for given session id and 3) the output that
2146 // haptic-generating effect attached to is in given outputs.
2147 if (sessionId != AUDIO_SESSION_NONE) {
2148 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2149 sessionId, FX_IID_HAPTICGENERATOR);
2150 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2151 return hapticGeneratingOutput;
2152 }
2153 }
2154
Eric Laurent16c66dd2019-05-01 17:54:10 -07002155 // Flags disqualifying an output: the match must happen before calling selectOutput()
2156 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2157 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2158
2159 // Flags expressing a functional request: must be honored in priority over
2160 // other criteria
2161 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2162 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002163 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2164 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002165 // Flags expressing a performance request: have lower priority than serving
2166 // requested sampling rate or channel mask
2167 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2168 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2169 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2170
2171 const audio_output_flags_t functionalFlags =
2172 (audio_output_flags_t)(flags & kFunctionalFlags);
2173 const audio_output_flags_t performanceFlags =
2174 (audio_output_flags_t)(flags & kPerformanceFlags);
2175
2176 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2177
Eric Laurente552edb2014-03-10 17:42:56 -07002178 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002179 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002180 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002181 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002182 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002183 // with tiebreak preferring the minimum number of extra functional flags
2184 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002185 // 3: the output supporting the exact channel mask
2186 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002187 // 5: the output with the highest sampling rate if the requested sample rate is
2188 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002189 // 6: the output with the highest number of requested performance flags
2190 // 7: the output with the bit depth the closest to the requested one
2191 // 8: the primary output
2192 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002193
Eric Laurent16c66dd2019-05-01 17:54:10 -07002194 // matching criteria values in priority order for best matching output so far
2195 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002196
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002197 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002198 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2199 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2200 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002201
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002202 for (audio_io_handle_t output : outputs) {
2203 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002204 // matching criteria values in priority order for current output
2205 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002206
Eric Laurent16c66dd2019-05-01 17:54:10 -07002207 if (outputDesc->isDuplicated()) {
2208 continue;
2209 }
2210 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2211 continue;
2212 }
Eric Laurent8838a382014-09-08 16:44:28 -07002213
Eric Laurent16c66dd2019-05-01 17:54:10 -07002214 // If haptic channel is specified, use the haptic output if present.
2215 // When using haptic output, same audio format and sample rate are required.
2216 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002217 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002218 // skip if haptic channel specified but output does not support it, or output support haptic
2219 // but there is no haptic channel requested AND no orphan haptic effect exist
2220 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2221 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002222 continue;
2223 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002224 // In the case of audio-coupled-haptic playback, there is no format conversion and
2225 // resampling in the framework, same format/channel/sampleRate for client and the output
2226 // thread is required. In the case of HapticGenerator effect, do not require format
2227 // matching.
2228 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2229 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002230 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002231 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002232 }
2233
2234 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002235 const int matchingFunctionalFlags =
2236 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2237 const int totalFunctionalFlags =
2238 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2239 // Prefer matching functional flags, but subtract unnecessary functional flags.
2240 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002241
2242 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002243 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2244 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002245 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2246 channelCount <= outputChannelCount) {
2247 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002248 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2249 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002250 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002251 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002252 currentMatchCriteria[3] = outputChannelCount;
2253 }
2254
2255 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002256 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002257 int diff; // avoid unsigned integer overflow.
2258 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2259
2260 // prefer the closest output sampling rate greater than or equal to target
2261 // if none exists, prefer the closest output sampling rate less than target.
2262 //
2263 // criteria is offset to make non-negative.
2264 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002265 }
2266
2267 // performance flags match
2268 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2269
2270 // format match
2271 if (format != AUDIO_FORMAT_INVALID) {
2272 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002273 PolicyAudioPort::kFormatDistanceMax -
2274 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002275 }
2276
2277 // primary output match
2278 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2279
2280 // compare match criteria by priority then value
2281 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2282 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2283 bestMatchCriteria = currentMatchCriteria;
2284 bestOutput = output;
2285
2286 std::stringstream result;
2287 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2288 std::ostream_iterator<int>(result, " "));
2289 ALOGV("%s new bestOutput %d criteria %s",
2290 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002291 }
2292 }
2293
Eric Laurent16c66dd2019-05-01 17:54:10 -07002294 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002295}
2296
Eric Laurent8fc147b2018-07-22 19:13:55 -07002297status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002298{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002299 ALOGV("%s portId %d", __FUNCTION__, portId);
2300
2301 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2302 if (outputDesc == 0) {
2303 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002304 return BAD_VALUE;
2305 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002306 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002307
Eric Laurent8fc147b2018-07-22 19:13:55 -07002308 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002310
jiabin220eea12024-05-17 17:55:20 +00002311 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2312 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2313 && outputDesc->isBitPerfect()) {
2314 // Usually, APM selects bit-perfect output for high priority use cases only when
2315 // bit-perfect output is the only output that can be routed to the selected device.
2316 // However, here is no need to play high priority use cases such as ringtone and alarm
2317 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2318 // can attach to new output.
2319 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2320 __func__, client->stream());
2321 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2322 return DEAD_OBJECT;
2323 }
2324
Eric Laurent733ce942017-12-07 12:18:25 -08002325 status_t status = outputDesc->start();
2326 if (status != NO_ERROR) {
2327 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002328 }
2329
Eric Laurent97ac8712018-07-27 18:59:02 -07002330 uint32_t delayMs;
2331 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002332
2333 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002334 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002335 if (status == DEAD_OBJECT) {
2336 sp<SwAudioOutputDescriptor> desc =
2337 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2338 if (desc == nullptr) {
2339 // This is not common, it may indicate something wrong with the HAL.
2340 ALOGE("%s unable to open output with default config", __func__);
2341 return status;
2342 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002343 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002344 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002345 }
jiabina84c3d32022-12-02 18:59:55 +00002346
2347 // If the client is the first one active on preferred mixer parameters, reopen the output
2348 // if the current mixer parameters doesn't match the preferred one.
2349 if (outputDesc->devices().size() == 1) {
2350 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2351 outputDesc->devices()[0]->getId(), client->strategy());
2352 if (info != nullptr && info->getUid() == client->uid()) {
2353 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2354 info->getConfigBase(), info->getFlags())) {
2355 stopSource(outputDesc, client);
2356 outputDesc->stop();
2357 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2358 config.channel_mask = info->getConfigBase().channel_mask;
2359 config.sample_rate = info->getConfigBase().sample_rate;
2360 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002361 sp<SwAudioOutputDescriptor> desc =
2362 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2363 if (desc == nullptr) {
2364 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002365 }
jiabin220eea12024-05-17 17:55:20 +00002366 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002367 // Intentionally return error to let the client side resending request for
2368 // creating and starting.
2369 return DEAD_OBJECT;
2370 }
2371 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002372 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002373 // If it is first bit-perfect client, reroute all clients that will be routed to
2374 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2375 PortHandleVector clientsToInvalidate;
2376 for (size_t i = 0; i < mOutputs.size(); i++) {
2377 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002378 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002379 continue;
2380 }
2381 for (const auto& c : mOutputs[i]->getClientIterable()) {
2382 clientsToInvalidate.push_back(c->portId());
2383 }
2384 }
2385 if (!clientsToInvalidate.empty()) {
2386 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2387 __func__);
2388 mpClientInterface->invalidateTracks(clientsToInvalidate);
2389 }
2390 }
jiabina84c3d32022-12-02 18:59:55 +00002391 }
2392 }
2393
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002394 if (client->hasPreferredDevice()) {
2395 // playback activity with preferred device impacts routing occurred, inform upper layers
2396 mpClientInterface->onRoutingUpdated();
2397 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002398 if (delayMs != 0) {
2399 usleep(delayMs * 1000);
2400 }
2401
jiabin220eea12024-05-17 17:55:20 +00002402 if (status == NO_ERROR &&
2403 outputDesc->mPreferredAttrInfo != nullptr &&
2404 outputDesc->isBitPerfect() &&
2405 com::android::media::audioserver::
2406 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2407 // A new client is started on bit-perfect output, update all clients internal mute.
2408 updateClientsInternalMute(outputDesc);
2409 }
2410
Eric Laurentc75307b2015-03-17 15:29:32 -07002411 return status;
2412}
2413
Eric Laurent96d1dda2022-03-14 17:14:19 +01002414bool AudioPolicyManager::isLeUnicastActive() const {
2415 if (isInCall()) {
2416 return true;
2417 }
2418 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2419}
2420
2421bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2422 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2423 return false;
2424 }
2425 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2426 ALOGV("%s active %d", __func__, active);
2427 return active;
2428}
2429
Eric Laurent97ac8712018-07-27 18:59:02 -07002430status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2431 const sp<TrackClientDescriptor>& client,
2432 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002433{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002434 // cannot start playback of STREAM_TTS if any other output is being used
2435 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002436
2437 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002439 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002440 auto clientStrategy = client->strategy();
2441 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002442 if (stream == AUDIO_STREAM_TTS) {
2443 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002444 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002445 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002446 return INVALID_OPERATION;
2447 } else {
2448 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2449 }
2450 } else {
2451 // some playback other than beacon starts
2452 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2453 }
2454
Eric Laurent77305a62016-07-25 16:39:22 -07002455 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002456 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002457 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002458
François Gaffie11d30102018-11-02 16:09:09 +01002459 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002460 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002461 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002462 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002463 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002464 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002465 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002466 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002467 } else {
2468 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002469 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002470 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2471 AUDIO_FORMAT_DEFAULT);
2472 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2473 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002474 }
2475
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002476 // requiresMuteCheck is false when we can bypass mute strategy.
2477 // It covers a common case when there is no materially active audio
2478 // and muting would result in unnecessary delay and dropped audio.
2479 const uint32_t outputLatencyMs = outputDesc->latency();
2480 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002481 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002482
Eric Laurente552edb2014-03-10 17:42:56 -07002483 // increment usage count for this stream on the requested output:
2484 // NOTE that the usage count is the same for duplicated output and hardware output which is
2485 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002486 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002487
2488 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002489 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002490 // Preferred device may be exclusive, use only if no other active clients on this output
2491 devices = DeviceVector(
2492 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2493 } else {
2494 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2495 }
François Gaffie11d30102018-11-02 16:09:09 +01002496 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002497 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002498 }
2499 }
Eric Laurente552edb2014-03-10 17:42:56 -07002500
François Gaffiec005e562018-11-06 15:04:49 +01002501 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002502 selectOutputForMusicEffects();
2503 }
2504
François Gaffie1c878552018-11-22 16:53:21 +01002505 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002506 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002507 if (devices.isEmpty()) {
2508 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002509 }
François Gaffiec005e562018-11-06 15:04:49 +01002510 bool shouldWait =
2511 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2512 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2513 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002514 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002515 const bool needToCloseBitPerfectOutput =
2516 (com::android::media::audioserver::
2517 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2518 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2519 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002520 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002521 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002522 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002523 // An output has a shared device if
2524 // - managed by the same hw module
2525 // - supports the currently selected device
2526 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002527 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002528
Eric Laurent77305a62016-07-25 16:39:22 -07002529 // force a device change if any other output is:
2530 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002531 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002532 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002533 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002534 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002535 // change the device currently selected by the other output.
2536 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002537 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002538 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002539 force = true;
2540 }
2541 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002542 // a notification so that audio focus effect can propagate, or that a mute/unmute
2543 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002544 const uint32_t latencyMs = desc->latency();
2545 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2546
2547 if (shouldWait && isActive && (waitMs < latencyMs)) {
2548 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002549 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002550
2551 // Require mute check if another output is on a shared device
2552 // and currently active to have proper drain and avoid pops.
2553 // Note restoring AudioTracks onto this output needs to invoke
2554 // a volume ramp if there is no mute.
2555 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002556
2557 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2558 outputsToReopen.push_back(desc);
2559 }
Eric Laurente552edb2014-03-10 17:42:56 -07002560 }
2561 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002562
jiabin220eea12024-05-17 17:55:20 +00002563 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002564 // If the output is open with preferred mixer attributes, but the routed device is
2565 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2566 // changed.
2567 return DEAD_OBJECT;
2568 }
jiabin220eea12024-05-17 17:55:20 +00002569 for (auto& outputToReopen : outputsToReopen) {
2570 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2571 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002572 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302573 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2574 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002575
Eric Laurente552edb2014-03-10 17:42:56 -07002576 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002577 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002578 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002579 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002580 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002581 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002582 outputDesc->useHwGain() /*force*/)) {
2583 // request AudioService to reinitialize the volume curves asynchronously
2584 ALOGE("checkAndSetVolume failed, requesting volume range init");
2585 mpClientInterface->onVolumeRangeInitRequest();
2586 };
Eric Laurente552edb2014-03-10 17:42:56 -07002587
2588 // update the outputs if starting an output with a stream that can affect notification
2589 // routing
2590 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002591
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002592 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002593 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002594 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002595 }
Eric Laurentdc462862016-07-19 12:29:53 -07002596
2597 if (waitMs > muteWaitMs) {
2598 *delayMs = waitMs - muteWaitMs;
2599 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002600
2601 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2602 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2603 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2604 // change occurs after the MixerThread starts and causes a stream volume
2605 // glitch.
2606 //
2607 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002608 }
Eric Laurentdc462862016-07-19 12:29:53 -07002609
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002610 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002611 mEngine->getForceUse(
2612 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002613 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002614 }
2615
Eric Laurent97ac8712018-07-27 18:59:02 -07002616 // Automatically enable the remote submix input when output is started on a re routing mix
2617 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002618 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2619 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002620 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2621 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2622 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002623 "remote-submix",
2624 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 }
2626
Eric Laurent96d1dda2022-03-14 17:14:19 +01002627 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2628
Eric Laurente552edb2014-03-10 17:42:56 -07002629 return NO_ERROR;
2630}
2631
Eric Laurent96d1dda2022-03-14 17:14:19 +01002632void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2633 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2634 bool isUnicastActive = isLeUnicastActive();
2635
2636 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002637 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002638 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2639 for (size_t i = 0; i < mOutputs.size(); i++) {
2640 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2641 if (desc != ignoredOutput && desc->isActive()
2642 && ((isUnicastActive &&
2643 !desc->devices().
2644 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2645 || (wasUnicastActive &&
2646 !desc->devices().getDevicesFromTypes(
2647 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2648 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2649 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002650 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002651 // If the device is using preferred mixer attributes, the output need to reopen
2652 // with default configuration when the new selected devices are different from
2653 // current routing devices.
2654 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2655 continue;
2656 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302657 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002658 // re-apply device specific volume if not done by setOutputDevice()
2659 if (!force) {
2660 applyStreamVolumes(desc, newDevices.types(), delayMs);
2661 }
2662 }
2663 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002664 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002665 }
2666}
2667
Eric Laurent8fc147b2018-07-22 19:13:55 -07002668status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002669{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002670 ALOGV("%s portId %d", __FUNCTION__, portId);
2671
2672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2673 if (outputDesc == 0) {
2674 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002675 return BAD_VALUE;
2676 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002677 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002678
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002679 if (client->hasPreferredDevice(true)) {
2680 // playback activity with preferred device impacts routing occurred, inform upper layers
2681 mpClientInterface->onRoutingUpdated();
2682 }
2683
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 ALOGV("stopOutput() output %d, stream %d, session %d",
2685 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002686
Eric Laurent97ac8712018-07-27 18:59:02 -07002687 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002688
Eric Laurent733ce942017-12-07 12:18:25 -08002689 if (status == NO_ERROR ) {
2690 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002691 } else {
2692 return status;
2693 }
2694
2695 if (outputDesc->devices().size() == 1) {
2696 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2697 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002698 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002699 if (info != nullptr && info->getUid() == client->uid()) {
2700 info->decreaseActiveClient();
2701 if (info->getActiveClientCount() == 0) {
2702 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002703 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002704 }
2705 }
jiabin220eea12024-05-17 17:55:20 +00002706 if (com::android::media::audioserver::
2707 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2708 !outputReopened && outputDesc->isBitPerfect()) {
2709 // Only need to update the clients' internal mute when the output is bit-perfect and it
2710 // is not reopened.
2711 updateClientsInternalMute(outputDesc);
2712 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002713 }
2714 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002715}
2716
Eric Laurent97ac8712018-07-27 18:59:02 -07002717status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2718 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002719{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002720 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002721 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002722 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002723 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002724
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002725 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2726
François Gaffie1c878552018-11-22 16:53:21 +01002727 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2728 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002729 // Automatically disable the remote submix input when output is stopped on a
2730 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002731 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002732 if (isSingleDeviceType(
2733 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002734 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002735 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002736 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2737 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002738 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002739 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002740 }
2741 }
2742 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002743 if (client->hasPreferredDevice(true) &&
2744 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002745 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002746 forceDeviceUpdate = true;
2747 }
2748
Eric Laurente552edb2014-03-10 17:42:56 -07002749 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002750 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002751
Eric Laurente552edb2014-03-10 17:42:56 -07002752 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002753 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002754 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002755 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002756
2757 // If the routing does not change, if an output is routed on a device using HwGain
2758 // (aka setAudioPortConfig) and there are still active clients following different
2759 // volume group(s), force reapply volume
2760 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2761 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2762
Eric Laurente552edb2014-03-10 17:42:56 -07002763 // delay the device switch by twice the latency because stopOutput() is executed when
2764 // the track stop() command is received and at that time the audio track buffer can
2765 // still contain data that needs to be drained. The latency only covers the audio HAL
2766 // and kernel buffers. Also the latency does not always include additional delay in the
2767 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302768 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002769 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002770
2771 // force restoring the device selection on other active outputs if it differs from the
2772 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002773 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002774 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002775 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002776 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002777 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002778 desc->isActive() &&
2779 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002780 (newDevices != desc->devices())) {
2781 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2782 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002783
jiabin220eea12024-05-17 17:55:20 +00002784 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002785 // If the device is using preferred mixer attributes, the output need to
2786 // reopen with default configuration when the new selected devices are
2787 // different from current routing devices.
2788 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2789 continue;
2790 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302791 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002792
Eric Laurent57de36c2016-09-28 16:59:11 -07002793 // re-apply device specific volume if not done by setOutputDevice()
2794 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002795 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002796 }
Eric Laurente552edb2014-03-10 17:42:56 -07002797 }
2798 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002799 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002800 // update the outputs if stopping one with a stream that can affect notification routing
2801 handleNotificationRoutingForStream(stream);
2802 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002803
2804 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2805 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002806 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002807 }
2808
François Gaffiec005e562018-11-06 15:04:49 +01002809 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002810 selectOutputForMusicEffects();
2811 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002812
2813 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2814
Eric Laurente552edb2014-03-10 17:42:56 -07002815 return NO_ERROR;
2816 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002817 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002818 return INVALID_OPERATION;
2819 }
2820}
2821
jiabinbce0c1d2020-10-05 11:20:18 -07002822bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002823{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002824 ALOGV("%s portId %d", __FUNCTION__, portId);
2825
2826 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2827 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002828 // If an output descriptor is closed due to a device routing change,
2829 // then there are race conditions with releaseOutput from tracks
2830 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2831 // destroyed shortly thereafter.
2832 //
2833 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002835 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002836 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002837
2838 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002839
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302840 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2841 if (outputDesc->isClientActive(client)) {
2842 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2843 stopOutput(portId);
2844 }
2845
Eric Laurent8fc147b2018-07-22 19:13:55 -07002846 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2847 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002848 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002849 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002850 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002851 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002852 if (--outputDesc->mDirectOpenCount == 0) {
2853 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002854 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002855 }
2856 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302857
Andy Hung39efb7a2018-09-26 15:39:28 -07002858 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002859 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2860 // The output is pending reopened to query dynamic profiles and
2861 // there is no active clients
2862 closeOutput(outputDesc->mIoHandle);
2863 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2864 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2865 if (newOutputDesc == nullptr) {
2866 ALOGE("%s failed to open output", __func__);
2867 }
2868 return true;
2869 }
2870 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002871}
2872
Eric Laurentcaf7f482014-11-25 17:50:47 -08002873status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2874 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002875 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002876 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002877 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002878 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002879 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002880 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002881 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002882 audio_port_handle_t *portId,
2883 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002884{
François Gaffiec005e562018-11-06 15:04:49 +01002885 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002886 "flags %#x attributes=%s requested device ID %d",
2887 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2888 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002889
Eric Laurentad2e7b92017-09-14 20:06:42 -07002890 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002891 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002892 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002893 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002895 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002896 sp<RecordClientDescriptor> clientDesc;
2897 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002898 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002899 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002900
2901 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2902 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2903 return INVALID_OPERATION;
2904 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002905
Francois Gaffie716e1432019-01-14 16:58:59 +01002906 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2907 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002908 }
2909
Paul McLean466dc8e2015-04-17 13:15:36 -06002910 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002911 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002912 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002913
Eric Laurentad2e7b92017-09-14 20:06:42 -07002914 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2915 // possible
2916 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2917 *input != AUDIO_IO_HANDLE_NONE) {
2918 ssize_t index = mInputs.indexOfKey(*input);
2919 if (index < 0) {
2920 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2921 status = BAD_VALUE;
2922 goto error;
2923 }
2924 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002925 RecordClientVector clients = inputDesc->getClientsForSession(session);
2926 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002927 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2928 status = BAD_VALUE;
2929 goto error;
2930 }
2931 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2932 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002933 // corresponds to a new client and is only permitted from the same UID.
2934 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002935 if (clients.size() > 1) {
2936 for (const auto& client : clients) {
2937 // The client map is ordered by key values (portId) and portIds are allocated
2938 // incrementaly. So the first client in this list is the one opened by audio flinger
2939 // when the mmap stream is created and should be ignored as it does not correspond
2940 // to an actual client
2941 if (client == *clients.cbegin()) {
2942 continue;
2943 }
2944 if (uid != client->uid() && !client->isSilenced()) {
2945 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2946 uid, client->portId(), client->uid());
2947 status = INVALID_OPERATION;
2948 goto error;
2949 }
Eric Laurent331679c2018-04-16 17:03:16 -07002950 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002951 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002952 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002953 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002954
Eric Laurentfecbceb2021-02-09 14:46:43 +01002955 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002956 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002957 }
2958
2959 *input = AUDIO_IO_HANDLE_NONE;
2960 *inputType = API_INPUT_INVALID;
2961
Francois Gaffie716e1432019-01-14 16:58:59 +01002962 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002963 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002964 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002965 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002966 ALOGW("%s could not find input mix for attr %s",
2967 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002968 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002969 }
jiabinc1de2df2019-05-07 14:26:40 -07002970 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2971 String8(attr->tags + strlen("addr=")),
2972 AUDIO_FORMAT_DEFAULT);
2973 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002974 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002975 __func__, attributes.source, attributes.tags);
2976 status = BAD_VALUE;
2977 goto error;
2978 }
2979
Kevin Rocard25f9b052019-02-27 15:08:54 -08002980 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2981 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2982 } else {
2983 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2984 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002985 if (virtualDeviceId) {
2986 *virtualDeviceId = policyMix->mVirtualDeviceId;
2987 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002988 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002989 if (explicitRoutingDevice != nullptr) {
2990 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002991 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002992 // Prevent from storing invalid requested device id in clients
2993 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002994 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002995 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2996 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002997 }
François Gaffie11d30102018-11-02 16:09:09 +01002998 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002999 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003000 status = BAD_VALUE;
3001 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003002 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003003 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3004 *inputType = API_INPUT_MIX_CAPTURE;
3005 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003006 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3007 // there is an external policy, but this input is attached to a mix of recorders,
3008 // meaning it receives audio injected into the framework, so the recorder doesn't
3009 // know about it and is therefore considered "legacy"
3010 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003011
3012 if (virtualDeviceId) {
3013 *virtualDeviceId = policyMix->mVirtualDeviceId;
3014 }
François Gaffie11d30102018-11-02 16:09:09 +01003015 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003016 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003017 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003018 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003019 } else {
3020 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003021 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003022
Eric Laurent599c7582015-12-07 18:05:55 -08003023 }
3024
François Gaffiec005e562018-11-06 15:04:49 +01003025 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003026 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003027 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003028 AudioProfileVector profiles;
3029 status_t ret = getProfilesForDevices(
3030 DeviceVector(device), profiles, flags, true /*isInput*/);
3031 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003032 const auto channels = profiles[0]->getChannels();
3033 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3034 config->channel_mask = *channels.begin();
3035 }
3036 const auto sampleRates = profiles[0]->getSampleRates();
3037 if (!sampleRates.empty() &&
3038 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3039 config->sample_rate = *sampleRates.begin();
3040 }
jiabinf1c73972022-04-14 16:28:52 -07003041 config->format = profiles[0]->getFormat();
3042 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003043 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003044 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003045
Marvin Ramine5a122d2023-12-07 13:57:59 +01003046
3047 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3048 *virtualDeviceId = policyMix->mVirtualDeviceId;
3049 }
3050
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051exit:
3052
François Gaffiec005e562018-11-06 15:04:49 +01003053 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3054 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003055
Francois Gaffie716e1432019-01-14 16:58:59 +01003056 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003057 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003058 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059
Mikhail Naganov2996f672019-04-18 12:29:59 -07003060 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003061 requestedDeviceId, attributes.source, flags,
3062 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003063 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003064 // Move (if found) effect for the client session to its input
3065 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003066 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003067
3068 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3069 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003070
Eric Laurent599c7582015-12-07 18:05:55 -08003071 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003072
3073error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003074 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003075}
3076
3077
François Gaffie11d30102018-11-02 16:09:09 +01003078audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003079 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003080 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003081 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003082 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003083 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003084{
3085 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003086 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003087 bool isSoundTrigger = false;
3088
François Gaffiec005e562018-11-06 15:04:49 +01003089 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003090 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3091 if (index >= 0) {
3092 input = mSoundTriggerSessions.valueFor(session);
3093 isSoundTrigger = true;
3094 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3095 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3096 } else {
3097 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003098 }
François Gaffiec005e562018-11-06 15:04:49 +01003099 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003100 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003101 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003102 }
3103
Carter Hsua3abb402021-10-26 11:11:20 +08003104 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3105 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3106 }
3107
Eric Laurentfe231122017-11-17 17:48:06 -08003108 // sampling rate and flags may be updated by getInputProfile
3109 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3110 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003111 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003112 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003113 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003114 // find a compatible input profile (not necessarily identical in parameters)
3115 sp<IOProfile> profile = getInputProfile(
3116 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3117 if (profile == nullptr) {
3118 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003119 }
jiabin2fd710d2022-05-02 23:20:22 +00003120
Glenn Kasten05ddca52016-02-11 08:17:12 -08003121 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003122 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003123 if (samplingRate == 0) {
3124 samplingRate = profileSamplingRate;
3125 }
Eric Laurente552edb2014-03-10 17:42:56 -07003126
Eric Laurent322b4d22015-04-03 15:57:54 -07003127 if (profile->getModuleHandle() == 0) {
3128 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003129 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003130 }
3131
Eric Laurentec376dc2021-04-08 20:41:22 +02003132 // Reuse an already opened input if a client with the same session ID already exists
3133 // on that input
3134 for (size_t i = 0; i < mInputs.size(); i++) {
3135 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3136 if (desc->mProfile != profile) {
3137 continue;
3138 }
3139 RecordClientVector clients = desc->clientsList();
3140 for (const auto &client : clients) {
3141 if (session == client->session()) {
3142 return desc->mIoHandle;
3143 }
3144 }
3145 }
3146
Eric Laurentc71b11b2024-06-03 12:54:53 +00003147 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003148 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003149 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3150 // First pick best candidate for preemption (there may not be any):
3151 // - Preempt and input if:
3152 // - It has only strictly lower priority use cases than the new client
3153 // - It has equal priority use cases than the new client, was not
3154 // opened thanks to preemption or has been active since opened.
3155 // - Order the preemption candidates by inactive first and priority second
3156 sp<AudioInputDescriptor> closeCandidate;
3157 int leastCloseRank = INT_MAX;
3158 static const int sCloseActive = 0x100;
3159
3160 for (size_t i = 0; i < mInputs.size(); i++) {
3161 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3162 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003163 continue;
3164 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003165 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3166 if (topPrioClient == nullptr) {
3167 continue;
3168 }
3169 int topPrio = source_priority(topPrioClient->source());
3170 if (topPrio < source_priority(attributes.source)
3171 || (topPrio == source_priority(attributes.source)
3172 && !desc->isPreemptor())) {
3173 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3174 if (closeRank < leastCloseRank) {
3175 leastCloseRank = closeRank;
3176 closeCandidate = desc;
3177 }
3178 }
3179 }
3180
3181 if (closeCandidate != nullptr) {
3182 closeInput(closeCandidate->mIoHandle);
3183 // Mark the new input as being issued from a preemption
3184 // so that is will not be preempted later
3185 isPreemptor = true;
3186 } else {
3187 // Then pick the best reusable input (There is always one)
3188 // The order of preference is:
3189 // 1) active inputs with same use case as the new client
3190 // 2) inactive inputs with same use case
3191 // 3) active inputs with different use cases
3192 // 4) inactive inputs with different use cases
3193 sp<AudioInputDescriptor> reuseCandidate;
3194 int leastReuseRank = INT_MAX;
3195 static const int sReuseDifferentUseCase = 0x100;
3196
3197 for (size_t i = 0; i < mInputs.size(); i++) {
3198 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3199 if (desc->mProfile != profile) {
3200 continue;
3201 }
3202 int reuseRank = sReuseDifferentUseCase;
3203 for (const auto& client: desc->getClientIterable()) {
3204 if (client->source() == attributes.source) {
3205 reuseRank = 0;
3206 break;
3207 }
3208 }
3209 reuseRank += desc->isActive() ? 0 : 1;
3210 if (reuseRank < leastReuseRank) {
3211 leastReuseRank = reuseRank;
3212 reuseCandidate = desc;
3213 }
3214 }
3215 return reuseCandidate->mIoHandle;
3216 }
3217 } else { // fix_input_sharing_logic()
3218 for (size_t i = 0; i < mInputs.size(); ) {
3219 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3220 if (desc->mProfile != profile) {
3221 i++;
3222 continue;
3223 }
3224 // if sound trigger, reuse input if used by other sound trigger on same session
3225 // else
3226 // reuse input if active client app is not in IDLE state
3227 //
3228 RecordClientVector clients = desc->clientsList();
3229 bool doClose = false;
3230 for (const auto& client : clients) {
3231 if (isSoundTrigger != client->isSoundTrigger()) {
3232 continue;
3233 }
3234 if (client->isSoundTrigger()) {
3235 if (session == client->session()) {
3236 return desc->mIoHandle;
3237 }
3238 continue;
3239 }
3240 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003241 return desc->mIoHandle;
3242 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003243 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003244 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003245 if (doClose) {
3246 closeInput(desc->mIoHandle);
3247 } else {
3248 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003249 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003250 }
3251 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003252 }
3253
Eric Laurentc71b11b2024-06-03 12:54:53 +00003254 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3255 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003256
Eric Laurentfe231122017-11-17 17:48:06 -08003257 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3258 lConfig.sample_rate = profileSamplingRate;
3259 lConfig.channel_mask = profileChannelMask;
3260 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003261
François Gaffie11d30102018-11-02 16:09:09 +01003262 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003263
3264 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003265 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003266 (profileSamplingRate != lConfig.sample_rate) ||
3267 !audio_formats_match(profileFormat, lConfig.format) ||
3268 (profileChannelMask != lConfig.channel_mask)) {
3269 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003270 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003271 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003272 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003273 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003274 }
Eric Laurent599c7582015-12-07 18:05:55 -08003275 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003276 }
3277
Eric Laurentc722f302014-12-10 11:21:49 -08003278 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003279
Eric Laurent599c7582015-12-07 18:05:55 -08003280 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003281 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003282
Eric Laurent599c7582015-12-07 18:05:55 -08003283 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003284}
3285
Eric Laurent4eb58f12018-12-07 16:41:02 -08003286status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003287{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003288 ALOGV("%s portId %d", __FUNCTION__, portId);
3289
3290 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3291 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003292 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003293 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003294 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003295 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003296 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003297 if (client->active()) {
3298 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3299 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003300 }
3301
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 audio_session_t session = client->session();
3303
Eric Laurent4eb58f12018-12-07 16:41:02 -08003304 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003305
Eric Laurent4eb58f12018-12-07 16:41:02 -08003306 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003307
Eric Laurent4eb58f12018-12-07 16:41:02 -08003308 status_t status = inputDesc->start();
3309 if (status != NO_ERROR) {
3310 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003311 }
Eric Laurente552edb2014-03-10 17:42:56 -07003312
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003313 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003314 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003316
Eric Laurent8f42ea12018-08-08 09:08:25 -07003317 // indicate active capture to sound trigger service if starting capture from a mic on
3318 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003319 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003320 if (device != nullptr) {
3321 status = setInputDevice(input, device, true /* force */);
3322 } else {
3323 ALOGW("%s no new input device can be found for descriptor %d",
3324 __FUNCTION__, inputDesc->getId());
3325 status = BAD_VALUE;
3326 }
Eric Laurente552edb2014-03-10 17:42:56 -07003327
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003328 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003329 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003330 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003331 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003332 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3333 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003335 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003336
François Gaffie11d30102018-11-02 16:09:09 +01003337 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3338 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003339 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003340 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003341 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003342
Eric Laurent8f42ea12018-08-08 09:08:25 -07003343 // automatically enable the remote submix output when input is started if not
3344 // used by a policy mix of type MIX_TYPE_RECORDERS
3345 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003346 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003348 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003349 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003350 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3351 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003352 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003353 if (address != "") {
3354 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3355 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003356 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003357 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003358 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003359 } else if (status != NO_ERROR) {
3360 // Restore client activity state.
3361 inputDesc->setClientActive(client, false);
3362 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003363 }
3364
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003365 ALOGV("%s input %d source = %d status = %d exit",
3366 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003368 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003369}
3370
Eric Laurent8fc147b2018-07-22 19:13:55 -07003371status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003372{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003373 ALOGV("%s portId %d", __FUNCTION__, portId);
3374
3375 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3376 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003377 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003378 return BAD_VALUE;
3379 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003380 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003381 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003382 if (!client->active()) {
3383 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003384 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003385 }
Carter Hsue6139d52021-07-08 10:30:20 +08003386 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003388
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 inputDesc->stop();
3390 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003391 auto current_source = inputDesc->source();
3392 setInputDevice(input, getNewInputDevice(inputDesc),
3393 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003395 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003396 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003397 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003398 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3399 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003400 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003401 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003402
3403 // automatically disable the remote submix output when input is stopped if not
3404 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003405 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003406 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003407 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003409 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3410 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003411 }
3412 if (address != "") {
3413 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3414 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003415 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003416 }
3417 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003418 resetInputDevice(input);
3419
3420 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3421 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003422 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3423 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003424 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003425 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003426 }
3427 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003428 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003429 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003430}
3431
Eric Laurent8fc147b2018-07-22 19:13:55 -07003432void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003433{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003434 ALOGV("%s portId %d", __FUNCTION__, portId);
3435
3436 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3437 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003438 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003439 return;
3440 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003441 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003442 audio_io_handle_t input = inputDesc->mIoHandle;
3443
Eric Laurent8f42ea12018-08-08 09:08:25 -07003444 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003445
Andy Hung39efb7a2018-09-26 15:39:28 -07003446 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003447
3448 // If no more clients are present in this session, park effects to an orphan chain
3449 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3450 if (clientsOnSession.size() == 0) {
3451 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3452 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003453 if (inputDesc->getClientCount() > 0) {
3454 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003455 return;
3456 }
3457
Eric Laurent05b90f82014-08-27 15:32:29 -07003458 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003459 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003460 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003461}
3462
Eric Laurent8f42ea12018-08-08 09:08:25 -07003463void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003464{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003465 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003466
3467 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003468 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003469 }
3470}
3471
Eric Laurent8f42ea12018-08-08 09:08:25 -07003472void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3473{
3474 stopInput(portId);
3475 releaseInput(portId);
3476}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003477
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003478bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3479 if (input->clientsList().size() == 0
3480 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3481 return true;
3482 }
3483 for (const auto& client : input->clientsList()) {
3484 sp<DeviceDescriptor> device =
3485 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3486 client->session());
3487 if (!input->supportedDevices().contains(device)) {
3488 return true;
3489 }
3490 }
3491 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3492 return false;
3493}
3494
Eric Laurent0dd51852019-04-19 18:18:58 -07003495void AudioPolicyManager::checkCloseInputs() {
3496 // After connecting or disconnecting an input device, close input if:
3497 // - it has no client (was just opened to check profile) OR
3498 // - none of its supported devices are connected anymore OR
3499 // - one of its clients cannot be routed to one of its supported
3500 // devices anymore. Otherwise update device selection
3501 std::vector<audio_io_handle_t> inputsToClose;
3502 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003503 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003504 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003505 }
3506 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003507 for (const audio_io_handle_t handle : inputsToClose) {
3508 ALOGV("%s closing input %d", __func__, handle);
3509 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003510 }
Eric Laurentd4692962014-05-05 18:13:44 -07003511}
3512
Vlad Popa87e0e582024-05-20 18:49:20 -07003513status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3514 const char *address __unused,
3515 bool enabled,
3516 audio_stream_type_t streamToDriveAbs)
3517{
Vlad Popaa536eb32024-07-18 16:00:35 -07003518 if (!enabled) {
3519 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3520 return NO_ERROR;
3521 }
3522
Vlad Popa87e0e582024-05-20 18:49:20 -07003523 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3524 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3525 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3526 toString(streamToDriveAbs).c_str());
3527 return BAD_VALUE;
3528 }
3529
Vlad Popaa536eb32024-07-18 16:00:35 -07003530 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003531 return NO_ERROR;
3532}
3533
François Gaffie251c7f02018-11-07 10:41:08 +01003534void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003535{
3536 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003537 if (indexMin < 0 || indexMax < 0) {
3538 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3539 return;
3540 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003541 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003542
3543 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003544 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3545 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003546 continue;
3547 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003548 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003549 }
Eric Laurente552edb2014-03-10 17:42:56 -07003550}
3551
Eric Laurente0720872014-03-11 09:30:41 -07003552status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003553 int index,
3554 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003555{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003556 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003557 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3558 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3559 return NO_ERROR;
3560 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303561 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3562 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003563 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003564}
3565
Eric Laurente0720872014-03-11 09:30:41 -07003566status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003567 int *index,
3568 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003569{
François Gaffiec005e562018-11-06 15:04:49 +01003570 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3571 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003572 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003573 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003574 deviceTypes = mEngine->getOutputDevicesForStream(
3575 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003576 }
jiabin9a3361e2019-10-01 09:38:30 -07003577 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003578}
3579
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003580status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003581 int index,
3582 audio_devices_t device)
3583{
3584 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003585 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3586 if (group == VOLUME_GROUP_NONE) {
3587 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003588 return BAD_VALUE;
3589 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003590 ALOGV("%s: group %d matching with %s index %d",
3591 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003592 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003593 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003594 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003595 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3596 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3597 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3598 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003599 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3600
3601 status = setVolumeCurveIndex(index, device, curves);
3602 if (status != NO_ERROR) {
3603 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3604 return status;
3605 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003606
jiabin9a3361e2019-10-01 09:38:30 -07003607 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003608 auto curCurvAttrs = curves.getAttributes();
3609 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3610 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003611 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003612 } else if (!curves.getStreamTypes().empty()) {
3613 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003614 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003615 } else {
3616 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3617 return BAD_VALUE;
3618 }
jiabin9a3361e2019-10-01 09:38:30 -07003619 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3620 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003621
François Gaffiecfe17322018-11-07 13:41:29 +01003622 // update volume on all outputs and streams matching the following:
3623 // - The requested stream (or a stream matching for volume control) is active on the output
3624 // - The device (or devices) selected by the engine for this stream includes
3625 // the requested device
3626 // - For non default requested device, currently selected device on the output is either the
3627 // requested device or one of the devices selected by the engine for this stream
3628 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3629 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003630 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003631 for (size_t i = 0; i < mOutputs.size(); i++) {
3632 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003633 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003634
jiabin9a3361e2019-10-01 09:38:30 -07003635 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3636 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003637 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003638
3639 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003640 continue;
3641 }
3642 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3643 curDevices.find(device) == curDevices.end()) {
3644 continue;
3645 }
3646 bool applyVolume = false;
3647 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3648 curSrcDevices.insert(device);
3649 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003650 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3651 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003652 } else {
3653 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3654 }
3655 if (!applyVolume) {
3656 continue; // next output
3657 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003658 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3659 // If a higher priority strategy is active, and the output is routed to a device with a
3660 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003661 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003662 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003663 // If the volume source is active with higher priority source, ensure at least Sw Muted
3664 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003665 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3666 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3667 false /*preferredDevice*/);
3668 if (activeClients.empty()) {
3669 continue;
3670 }
3671 bool isPreempted = false;
3672 bool isHigherPriority = productStrategy < strategy;
3673 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003674 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003675 ALOGV("%s: Strategy=%d (\nrequester:\n"
3676 " group %d, volumeGroup=%d attributes=%s)\n"
3677 " higher priority source active:\n"
3678 " volumeGroup=%d attributes=%s) \n"
3679 " on output %zu, bailing out", __func__, productStrategy,
3680 group, group, toString(attributes).c_str(),
3681 client->volumeSource(), toString(client->attributes()).c_str(), i);
3682 applyVolume = false;
3683 isPreempted = true;
3684 break;
3685 }
3686 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003687 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003688 applyVolume = true;
3689 }
3690 }
3691 if (isPreempted || applyVolume) {
3692 break;
3693 }
3694 }
3695 if (!applyVolume) {
3696 continue; // next output
3697 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003698 }
François Gaffieed91f582020-01-31 10:35:37 +01003699 //FIXME: workaround for truncated touch sounds
3700 // delayed volume change for system stream to be removed when the problem is
3701 // handled by system UI
3702 status_t volStatus = checkAndSetVolume(
3703 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003704 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003705 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3706 if (volStatus != NO_ERROR) {
3707 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003708 }
3709 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003710
3711 // update voice volume if the an active call route exists
3712 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3713 && (curSrcDevices.find(
3714 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3715 != curSrcDevices.end())) {
3716 bool isVoiceVolSrc;
3717 bool isBtScoVolSrc;
3718 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3719 isVoiceVolSrc, isBtScoVolSrc, __func__)
3720 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003721 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3722 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3723 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003724 }
3725 }
3726
François Gaffiecfe17322018-11-07 13:41:29 +01003727 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3728 return status;
3729}
3730
François Gaffieaaac0fd2018-11-22 17:56:39 +01003731status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003732 audio_devices_t device,
3733 IVolumeCurves &volumeCurves)
3734{
3735 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3736 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003737 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3738 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003739 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303740 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3741 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003742 return BAD_VALUE;
3743 }
3744 if (!audio_is_output_device(device)) {
3745 return BAD_VALUE;
3746 }
3747
3748 // Force max volume if stream cannot be muted
3749 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3750
François Gaffieaaac0fd2018-11-22 17:56:39 +01003751 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003752 volumeCurves.addCurrentVolumeIndex(device, index);
3753 return NO_ERROR;
3754}
3755
3756status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3757 int &index,
3758 audio_devices_t device)
3759{
3760 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3761 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003762 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003763 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003764 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003765 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003766 }
jiabin9a3361e2019-10-01 09:38:30 -07003767 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003768}
3769
3770status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3771 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003772 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003773{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003774 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003775 return BAD_VALUE;
3776 }
jiabin9a3361e2019-10-01 09:38:30 -07003777 index = curves.getVolumeIndex(deviceTypes);
3778 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003779 return NO_ERROR;
3780}
3781
3782status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3783 int &index)
3784{
3785 index = getVolumeCurves(attr).getVolumeIndexMin();
3786 return NO_ERROR;
3787}
3788
3789status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3790 int &index)
3791{
3792 index = getVolumeCurves(attr).getVolumeIndexMax();
3793 return NO_ERROR;
3794}
3795
Eric Laurent36829f92017-04-07 19:04:42 -07003796audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003797{
3798 // select one output among several suitable for global effects.
3799 // The priority is as follows:
3800 // 1: An offloaded output. If the effect ends up not being offloadable,
3801 // AudioFlinger will invalidate the track and the offloaded output
3802 // will be closed causing the effect to be moved to a PCM output.
3803 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003804 // 3: The primary output
3805 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003806
François Gaffiec005e562018-11-06 15:04:49 +01003807 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3808 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003809 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003810
Eric Laurent36829f92017-04-07 19:04:42 -07003811 if (outputs.size() == 0) {
3812 return AUDIO_IO_HANDLE_NONE;
3813 }
Eric Laurente552edb2014-03-10 17:42:56 -07003814
Eric Laurent36829f92017-04-07 19:04:42 -07003815 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3816 bool activeOnly = true;
3817
3818 while (output == AUDIO_IO_HANDLE_NONE) {
3819 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3820 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3821 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3822
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003823 for (audio_io_handle_t output : outputs) {
3824 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003825 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003826 continue;
3827 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003828 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3829 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003830 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003831 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003832 }
3833 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003834 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003835 }
3836 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003837 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003838 }
3839 }
3840 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3841 output = outputOffloaded;
3842 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3843 output = outputDeepBuffer;
3844 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3845 output = outputPrimary;
3846 } else {
3847 output = outputs[0];
3848 }
3849 activeOnly = false;
3850 }
3851
3852 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003853 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3854 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003855 mMusicEffectOutput = output;
3856 }
3857
3858 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003859 return output;
3860}
3861
Eric Laurent36829f92017-04-07 19:04:42 -07003862audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3863{
3864 return selectOutputForMusicEffects();
3865}
3866
Eric Laurente0720872014-03-11 09:30:41 -07003867status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003868 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003869 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003870 int session,
3871 int id)
3872{
Shunkai Yao29d10572024-03-19 04:31:47 +00003873 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003874 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003875 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003876 index = mInputs.indexOfKey(io);
3877 if (index < 0) {
3878 ALOGW("registerEffect() unknown io %d", io);
3879 return INVALID_OPERATION;
3880 }
Eric Laurente552edb2014-03-10 17:42:56 -07003881 }
3882 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003883 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3884 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3885 || strategy == PRODUCT_STRATEGY_NONE));
3886 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003887}
3888
Eric Laurentc241b0d2018-11-28 09:08:49 -08003889status_t AudioPolicyManager::unregisterEffect(int id)
3890{
3891 if (mEffects.getEffect(id) == nullptr) {
3892 return INVALID_OPERATION;
3893 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003894 if (mEffects.isEffectEnabled(id)) {
3895 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3896 setEffectEnabled(id, false);
3897 }
3898 return mEffects.unregisterEffect(id);
3899}
3900
3901status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3902{
3903 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3904 if (effect == nullptr) {
3905 return INVALID_OPERATION;
3906 }
3907
3908 status_t status = mEffects.setEffectEnabled(id, enabled);
3909 if (status == NO_ERROR) {
3910 mInputs.trackEffectEnabled(effect, enabled);
3911 }
3912 return status;
3913}
3914
Eric Laurent6c796322019-04-09 14:13:17 -07003915
3916status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3917{
3918 mEffects.moveEffects(ids, io);
3919 return NO_ERROR;
3920}
3921
Eric Laurentc75307b2015-03-17 15:29:32 -07003922bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3923{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003924 auto vs = toVolumeSource(stream, false);
3925 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003926}
3927
3928bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3929{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003930 auto vs = toVolumeSource(stream, false);
3931 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003932}
3933
Eric Laurente0720872014-03-11 09:30:41 -07003934bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003935{
3936 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003937 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003938 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003939 return true;
3940 }
3941 }
3942 return false;
3943}
3944
Eric Laurent275e8e92014-11-30 15:14:47 -08003945// Register a list of custom mixes with their attributes and format.
3946// When a mix is registered, corresponding input and output profiles are
3947// added to the remote submix hw module. The profile contains only the
3948// parameters (sampling rate, format...) specified by the mix.
3949// The corresponding input remote submix device is also connected.
3950//
3951// When a remote submix device is connected, the address is checked to select the
3952// appropriate profile and the corresponding input or output stream is opened.
3953//
3954// When capture starts, getInputForAttr() will:
3955// - 1 look for a mix matching the address passed in attribtutes tags if any
3956// - 2 if none found, getDeviceForInputSource() will:
3957// - 2.1 look for a mix matching the attributes source
3958// - 2.2 if none found, default to device selection by policy rules
3959// At this time, the corresponding output remote submix device is also connected
3960// and active playback use cases can be transferred to this mix if needed when reconnecting
3961// after AudioTracks are invalidated
3962//
3963// When playback starts, getOutputForAttr() will:
3964// - 1 look for a mix matching the address passed in attribtutes tags if any
3965// - 2 if none found, look for a mix matching the attributes usage
3966// - 3 if none found, default to device and output selection by policy rules.
3967
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003968status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003969{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003970 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3971 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003972 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003973 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003974 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003975 // examine each mix's route type
3976 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003977 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003978 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3979 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3980 ALOGE("Unsupported Policy Mix %zu of %zu: "
3981 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3982 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003983 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003984 break;
3985 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003986 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3987 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003988 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003989 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3990 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003991 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003992 rSubmixModule = mHwModules.getModuleFromName(
3993 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3994 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003995 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003996 i);
3997 res = INVALID_OPERATION;
3998 break;
3999 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004000 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004001
Eric Laurent97ac8712018-07-27 18:59:02 -07004002 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004003 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004004 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004005 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004006 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4007 } else {
4008 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4009 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004010 }
François Gaffie036e1e92015-03-19 10:16:24 +01004011
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004012 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004013 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004014 res = INVALID_OPERATION;
4015 break;
4016 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004017 audio_config_t outputConfig = mix.mFormat;
4018 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004019 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4020 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004021 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4022 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004023 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004024 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4025 audio_is_linear_pcm(outputConfig.format)
4026 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004027 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004028 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4029 audio_is_linear_pcm(inputConfig.format)
4030 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004031
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004032 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004033 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004034 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004035 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004036 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004037 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004038 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004039 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4040 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004041 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004042 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004043 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004044
4045 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4046 mix.mDeviceType, mix.mDeviceAddress,
4047 String8(), AUDIO_FORMAT_DEFAULT);
4048 if (device == nullptr) {
4049 res = INVALID_OPERATION;
4050 break;
4051 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004052
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004053 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004054 // First try to find an already opened output supporting the device
4055 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004057
Eric Laurentc529cf62020-04-17 18:19:10 -07004058 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004059 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004060 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004061 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004062 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004063 } else {
4064 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004065 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004066 }
4067 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004068 // If no output found, try to find a direct output profile supporting the device
4069 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4070 sp<HwModule> module = mHwModules[i];
4071 for (size_t j = 0;
4072 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4073 j++) {
4074 sp<IOProfile> profile = module->getOutputProfiles()[j];
4075 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4076 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4077 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004078 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004079 res = INVALID_OPERATION;
4080 } else {
4081 foundOutput = true;
4082 }
4083 }
4084 }
4085 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004086 if (res != NO_ERROR) {
4087 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004088 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004089 res = INVALID_OPERATION;
4090 break;
4091 } else if (!foundOutput) {
4092 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004093 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004094 res = INVALID_OPERATION;
4095 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004096 } else {
4097 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004098 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004099 }
Eric Laurentc722f302014-12-10 11:21:49 -08004100 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004101 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004102 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004103 if (audio_flags::audio_mix_ownership()) {
4104 // Only unregister mixes that were actually registered to not accidentally unregister
4105 // mixes that already existed previously.
4106 unregisterPolicyMixes(registeredMixes);
4107 registeredMixes.clear();
4108 } else {
4109 unregisterPolicyMixes(mixes);
4110 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004111 } else if (checkOutputs) {
4112 checkForDeviceAndOutputChanges();
4113 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004114 }
4115 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004116}
4117
4118status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4119{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004120 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004121 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004122 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004123 sp<HwModule> rSubmixModule;
4124 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004125 for (const auto& mix : mixes) {
4126 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004127
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004128 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004129 rSubmixModule = mHwModules.getModuleFromName(
4130 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4131 if (rSubmixModule == 0) {
4132 res = INVALID_OPERATION;
4133 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004134 }
4135 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004136
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004137 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004138
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004139 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004140 res = INVALID_OPERATION;
4141 continue;
4142 }
4143
Marvin Ramin0783e202024-03-05 12:45:50 +01004144 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004145 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004146 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4147 status_t currentRes =
4148 setDeviceConnectionStateInt(device,
4149 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4150 address.c_str(),
4151 "remote-submix",
4152 AUDIO_FORMAT_DEFAULT);
4153 if (!audio_flags::audio_mix_ownership()) {
4154 res = currentRes;
4155 }
4156 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004157 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004158 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004159 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004160 }
4161 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004162 }
jiabin5740f082019-08-19 15:08:30 -07004163 rSubmixModule->removeOutputProfile(address.c_str());
4164 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004165
Kevin Rocard153f92d2018-12-18 18:33:28 -08004166 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004167 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004168 res = INVALID_OPERATION;
4169 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004170 } else {
4171 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004173 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004174 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004175
4176 if (res == NO_ERROR && checkOutputs) {
4177 checkForDeviceAndOutputChanges();
4178 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004179 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004180 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004181}
4182
Marvin Raminbdefaf02023-11-01 09:10:32 +01004183status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4184 if (!audio_flags::audio_mix_test_api()) {
4185 return INVALID_OPERATION;
4186 }
4187
4188 _aidl_return.clear();
4189 _aidl_return.reserve(mPolicyMixes.size());
4190 for (const auto &policyMix: mPolicyMixes) {
4191 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4192 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4193 policyMix->mCbFlags);
4194 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004195 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004196 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004197 }
4198
Vlad Popaa5d73f32024-03-08 16:05:38 -08004199 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004200 return OK;
4201}
4202
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004203status_t AudioPolicyManager::updatePolicyMix(
4204 const AudioMix& mix,
4205 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4206 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4207 if (res == NO_ERROR) {
4208 checkForDeviceAndOutputChanges();
4209 updateCallAndOutputRouting();
4210 }
4211 return res;
4212}
4213
Mikhail Naganov100f0122018-11-29 11:22:16 -08004214void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4215{
4216 size_t i = 0;
4217 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4218 for (const auto& fmt : mManualSurroundFormats) {
4219 if (i++ != 0) dst->append(", ");
4220 std::string sfmt;
4221 FormatConverter::toString(fmt, sfmt);
4222 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4223 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4224 }
4225}
4226
Eric Laurentc529cf62020-04-17 18:19:10 -07004227// Returns true if all devices types match the predicate and are supported by one HW module
4228bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004229 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004230 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004231 const char *context,
4232 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004233 for (size_t i = 0; i < devices.size(); i++) {
4234 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004235 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004236 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004237 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004238 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004239 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004240 return false;
4241 }
4242 }
4243 return true;
4244}
4245
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004246void AudioPolicyManager::changeOutputDevicesMuteState(
4247 const AudioDeviceTypeAddrVector& devices) {
4248 ALOGVV("%s() num devices %zu", __func__, devices.size());
4249
4250 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4251 getSoftwareOutputsForDevices(devices);
4252
4253 for (size_t i = 0; i < outputs.size(); i++) {
4254 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4255 DeviceVector prevDevices = outputDesc->devices();
4256 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4257 }
4258}
4259
4260std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4261 const AudioDeviceTypeAddrVector& devices) const
4262{
4263 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4264 DeviceVector deviceDescriptors;
4265 for (size_t j = 0; j < devices.size(); j++) {
4266 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4267 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4268 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4269 ALOGE("%s: device type %#x address %s not supported or not an output device",
4270 __func__, devices[j].mType, devices[j].getAddress());
4271 continue;
4272 }
4273 deviceDescriptors.add(desc);
4274 }
4275 for (size_t i = 0; i < mOutputs.size(); i++) {
4276 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4277 continue;
4278 }
4279 outputs.push_back(mOutputs.valueAt(i));
4280 }
4281 return outputs;
4282}
4283
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004284status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004285 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004286 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004287 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4288 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004289 }
4290 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004291 if (res != NO_ERROR) {
4292 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4293 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004294 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004295
4296 checkForDeviceAndOutputChanges();
4297 updateCallAndOutputRouting();
4298
4299 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004300}
4301
4302status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4303 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004304 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4305 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004306 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004307 __FUNCTION__, uid);
4308 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004309 }
4310
Eric Laurentc529cf62020-04-17 18:19:10 -07004311 checkForDeviceAndOutputChanges();
4312 updateCallAndOutputRouting();
4313
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004314 return res;
4315}
4316
Eric Laurent2517af32020-11-25 15:31:27 +01004317
jiabin0a488932020-08-07 17:32:40 -07004318status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4319 device_role_t role,
4320 const AudioDeviceTypeAddrVector &devices) {
4321 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4322 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004323
Eric Laurentc529cf62020-04-17 18:19:10 -07004324 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004325 return BAD_VALUE;
4326 }
jiabin0a488932020-08-07 17:32:40 -07004327 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004328 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004329 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4330 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004331 return status;
4332 }
4333
4334 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004335
4336 bool forceVolumeReeval = false;
4337 // FIXME: workaround for truncated touch sounds
4338 // to be removed when the problem is handled by system UI
4339 uint32_t delayMs = 0;
4340 if (strategy == mCommunnicationStrategy) {
4341 forceVolumeReeval = true;
4342 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4343 updateInputRouting();
4344 }
4345 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004346
4347 return NO_ERROR;
4348}
4349
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004350void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4351 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004352{
4353 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004354 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004355 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004356 // Only apply special touch sound delay once
4357 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004358 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004359 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004360 for (size_t i = 0; i < mOutputs.size(); i++) {
4361 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4362 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004363 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4364 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004365 // As done in setDeviceConnectionState, we could also fix default device issue by
4366 // preventing the force re-routing in case of default dev that distinguishes on address.
4367 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004368 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004369 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004370 // If the device is using preferred mixer attributes, the output need to reopen
4371 // with default configuration when the new selected devices are different from
4372 // current routing devices.
4373 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4374 continue;
4375 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304376
4377 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4378 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004379 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004380 // Only apply special touch sound delay once
4381 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004382 }
4383 if (forceVolumeReeval && !newDevices.isEmpty()) {
4384 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4385 }
4386 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004387 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004388 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004389}
4390
Eric Laurent2517af32020-11-25 15:31:27 +01004391void AudioPolicyManager::updateInputRouting() {
4392 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304393 // Skip for hotword recording as the input device switch
4394 // is handled within sound trigger HAL
4395 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4396 continue;
4397 }
Eric Laurent2517af32020-11-25 15:31:27 +01004398 auto newDevice = getNewInputDevice(activeDesc);
4399 // Force new input selection if the new device can not be reached via current input
4400 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4401 setInputDevice(activeDesc->mIoHandle, newDevice);
4402 } else {
4403 closeInput(activeDesc->mIoHandle);
4404 }
4405 }
4406}
4407
Paul Wang5d7cdb52022-11-22 09:45:06 +00004408status_t
4409AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4410 device_role_t role,
4411 const AudioDeviceTypeAddrVector &devices) {
4412 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4413 dumpAudioDeviceTypeAddrVector(devices).c_str());
4414
Eric Laurent78fedbf2023-03-09 14:40:44 +01004415 if (!areAllDevicesSupported(
4416 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004417 return BAD_VALUE;
4418 }
4419 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4420 if (status != NO_ERROR) {
4421 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4422 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4423 return status;
4424 }
4425
4426 checkForDeviceAndOutputChanges();
4427
4428 bool forceVolumeReeval = false;
4429 // TODO(b/263479999): workaround for truncated touch sounds
4430 // to be removed when the problem is handled by system UI
4431 uint32_t delayMs = 0;
4432 if (strategy == mCommunnicationStrategy) {
4433 forceVolumeReeval = true;
4434 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4435 updateInputRouting();
4436 }
4437 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4438
4439 return NO_ERROR;
4440}
4441
4442status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4443 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004444{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004445 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004446
Paul Wang5d7cdb52022-11-22 09:45:06 +00004447 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004448 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004449 ALOGW_IF(status != NAME_NOT_FOUND,
4450 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004451 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004452 return status;
4453 }
4454
4455 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004456
4457 bool forceVolumeReeval = false;
4458 // FIXME: workaround for truncated touch sounds
4459 // to be removed when the problem is handled by system UI
4460 uint32_t delayMs = 0;
4461 if (strategy == mCommunnicationStrategy) {
4462 forceVolumeReeval = true;
4463 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4464 updateInputRouting();
4465 }
4466 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004467
4468 return NO_ERROR;
4469}
4470
jiabin0a488932020-08-07 17:32:40 -07004471status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4472 device_role_t role,
4473 AudioDeviceTypeAddrVector &devices) {
4474 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004475}
4476
Jiabin Huang3b98d322020-09-03 17:54:16 +00004477status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4478 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4479 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4480 dumpAudioDeviceTypeAddrVector(devices).c_str());
4481
Mikhail Naganov55773032020-10-01 15:08:13 -07004482 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004483 return BAD_VALUE;
4484 }
4485 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4486 ALOGW_IF(status != NO_ERROR,
4487 "Engine could not set preferred devices %s for audio source %d role %d",
4488 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4489
4490 return status;
4491}
4492
4493status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4494 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4495 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4496 dumpAudioDeviceTypeAddrVector(devices).c_str());
4497
Mikhail Naganov55773032020-10-01 15:08:13 -07004498 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004499 return BAD_VALUE;
4500 }
4501 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4502 ALOGW_IF(status != NO_ERROR,
4503 "Engine could not add preferred devices %s for audio source %d role %d",
4504 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4505
Eric Laurent2517af32020-11-25 15:31:27 +01004506 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004507 return status;
4508}
4509
4510status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4511 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4512{
4513 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4514 dumpAudioDeviceTypeAddrVector(devices).c_str());
4515
Eric Laurent78fedbf2023-03-09 14:40:44 +01004516 if (!areAllDevicesSupported(
4517 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004518 return BAD_VALUE;
4519 }
4520
4521 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4522 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004523 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004524 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004525 if (status == NO_ERROR) {
4526 updateInputRouting();
4527 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004528 return status;
4529}
4530
4531status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4532 device_role_t role) {
4533 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4534
4535 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004536 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004537 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004538 if (status == NO_ERROR) {
4539 updateInputRouting();
4540 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004541 return status;
4542}
4543
4544status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4545 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4546 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4547}
4548
Oscar Azucena90e77632019-11-27 17:12:28 -08004549status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004550 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004551 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004552 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4553 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004554 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004555 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4556 if (status != NO_ERROR) {
4557 ALOGE("%s() could not set device affinity for userId %d",
4558 __FUNCTION__, userId);
4559 return status;
4560 }
4561
4562 // reevaluate outputs for all devices
4563 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004564 changeOutputDevicesMuteState(devices);
4565 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4566 true /* skipDelays */);
4567 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004568
4569 return NO_ERROR;
4570}
4571
4572status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004573 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004574 AudioDeviceTypeAddrVector devices;
4575 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004576 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4577 if (status != NO_ERROR) {
4578 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4579 __FUNCTION__, userId);
4580 return status;
4581 }
4582
4583 // reevaluate outputs for all devices
4584 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004585 changeOutputDevicesMuteState(devices);
4586 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4587 true /* skipDelays */);
4588 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004589
4590 return NO_ERROR;
4591}
4592
Andy Hungc29d82b2018-10-05 12:23:17 -07004593void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004594{
Andy Hungc29d82b2018-10-05 12:23:17 -07004595 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004596 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004597 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004598 std::string stateLiteral;
4599 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004600 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004601 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4602 "communications", "media", "record", "dock", "system",
4603 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4604 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4605 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004606 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4607 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4608 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4609 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4610 dst->append(" (MANUAL: ");
4611 dumpManualSurroundFormats(dst);
4612 dst->append(")");
4613 }
4614 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004615 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004616 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4617 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004618 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004619 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004620
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004621 dst->append("\n");
4622 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4623 dst->append("\n");
4624 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004625 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004626 mOutputs.dump(dst);
4627 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004628 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004629 mAudioPatches.dump(dst);
4630 mPolicyMixes.dump(dst);
4631 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004632
Kevin Rocardb99cc752019-03-21 20:52:24 -07004633 dst->appendFormat(" AllowedCapturePolicies:\n");
4634 for (auto& policy : mAllowedCapturePolicies) {
4635 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4636 }
4637
jiabina84c3d32022-12-02 18:59:55 +00004638 dst->appendFormat(" Preferred mixer audio configuration:\n");
4639 for (const auto it : mPreferredMixerAttrInfos) {
4640 dst->appendFormat(" - device port id: %d\n", it.first);
4641 for (const auto preferredMixerInfoIt : it.second) {
4642 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4643 preferredMixerInfoIt.second->dump(dst);
4644 }
4645 }
4646
François Gaffiec005e562018-11-06 15:04:49 +01004647 dst->appendFormat("\nPolicy Engine dump:\n");
4648 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004649
4650 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4651 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4652 dst->appendFormat(" - device type: %s, driving stream %d\n",
4653 dumpDeviceTypes({it.first}).c_str(),
4654 mEngine->getVolumeGroupForAttributes(it.second));
4655 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004656}
4657
4658status_t AudioPolicyManager::dump(int fd)
4659{
4660 String8 result;
4661 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004662 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004663 return NO_ERROR;
4664}
4665
Kevin Rocardb99cc752019-03-21 20:52:24 -07004666status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4667{
4668 mAllowedCapturePolicies[uid] = capturePolicy;
4669 return NO_ERROR;
4670}
4671
Eric Laurente552edb2014-03-10 17:42:56 -07004672// This function checks for the parameters which can be offloaded.
4673// This can be enhanced depending on the capability of the DSP and policy
4674// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004675audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004676{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004677 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004678 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004679 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004680 offloadInfo.format,
4681 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4682 offloadInfo.has_video);
4683
jiabin2b9d5a12021-12-10 01:06:29 +00004684 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004685 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004686 }
4687
4688 // See if there is a profile to support this.
4689 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004690 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004691 offloadInfo.sample_rate,
4692 offloadInfo.format,
4693 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004694 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4695 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004696 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4697 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4698 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004699 if (profile == nullptr) {
4700 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4701 }
4702 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4703 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4704 }
4705 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004706}
4707
Michael Chana94fbb22018-04-24 14:31:19 +10004708bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4709 const audio_attributes_t& attributes) {
4710 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004711 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004712 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4713 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004714 config.sample_rate,
4715 config.format,
4716 config.channel_mask,
4717 output_flags,
4718 true /* directOnly */);
4719 ALOGV("%s() profile %sfound with name: %s, "
4720 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4721 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004722 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004723 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004724
4725 // also try the MSD module if compatible profile not found
4726 if (profile == nullptr) {
4727 profile = getMsdProfileForOutput(outputDevices,
4728 config.sample_rate,
4729 config.format,
4730 config.channel_mask,
4731 output_flags,
4732 true /* directOnly */);
4733 ALOGV("%s() MSD profile %sfound with name: %s, "
4734 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4735 __FUNCTION__, profile != 0 ? "" : "NOT ",
4736 (profile != 0 ? profile->getTagName().c_str() : "null"),
4737 config.sample_rate, config.format, config.channel_mask, output_flags);
4738 }
4739 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004740}
4741
jiabin2b9d5a12021-12-10 01:06:29 +00004742bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4743 bool durationIgnored) {
4744 if (mMasterMono) {
4745 return false; // no offloading if mono is set.
4746 }
4747
4748 // Check if offload has been disabled
4749 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4750 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4751 return false;
4752 }
4753
4754 // Check if stream type is music, then only allow offload as of now.
4755 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4756 {
4757 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4758 return false;
4759 }
4760
4761 //TODO: enable audio offloading with video when ready
4762 const bool allowOffloadWithVideo =
4763 property_get_bool("audio.offload.video", false /* default_value */);
4764 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4765 ALOGV("%s: has_video == true, returning false", __func__);
4766 return false;
4767 }
4768
4769 //If duration is less than minimum value defined in property, return false
4770 const int min_duration_secs = property_get_int32(
4771 "audio.offload.min.duration.secs", -1 /* default_value */);
4772 if (!durationIgnored) {
4773 if (min_duration_secs >= 0) {
4774 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4775 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4776 __func__, min_duration_secs);
4777 return false;
4778 }
4779 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4780 ALOGV("%s: Offload denied by duration < default min(=%u)",
4781 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4782 return false;
4783 }
4784 }
4785
4786 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4787 // creating an offloaded track and tearing it down immediately after start when audioflinger
4788 // detects there is an active non offloadable effect.
4789 // FIXME: We should check the audio session here but we do not have it in this context.
4790 // This may prevent offloading in rare situations where effects are left active by apps
4791 // in the background.
4792 if (mEffects.isNonOffloadableEffectEnabled()) {
4793 return false;
4794 }
4795
4796 return true;
4797}
4798
4799audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4800 const audio_config_t *config) {
4801 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4802 offloadInfo.format = config->format;
4803 offloadInfo.sample_rate = config->sample_rate;
4804 offloadInfo.channel_mask = config->channel_mask;
4805 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4806 offloadInfo.has_video = false;
4807 offloadInfo.is_streaming = false;
4808 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4809
4810 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4811 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4812 audio_flags_to_audio_output_flags(attr->flags, &flags);
4813 // only retain flags that will drive compressed offload or passthrough
4814 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4815 if (offloadPossible) {
4816 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4817 }
4818 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4819
Dorin Drimusfae3c642022-03-17 18:36:30 +01004820 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004821 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004822 DeviceVector outputDevices = engineOutputDevices;
4823 // the MSD module checks for different conditions and output devices
4824 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4825 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4826 continue;
4827 }
4828 outputDevices = getMsdAudioOutDevices();
4829 }
jiabin2b9d5a12021-12-10 01:06:29 +00004830 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004831 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004832 config->sample_rate, nullptr /*updatedSamplingRate*/,
4833 config->format, nullptr /*updatedFormat*/,
4834 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004835 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004836 continue;
4837 }
4838 // reject profiles not corresponding to a device currently available
4839 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4840 continue;
4841 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004842 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4843 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004844 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004845 != AUDIO_DIRECT_NOT_SUPPORTED) {
4846 // Already reports offload gapless supported. No need to report offload support.
4847 continue;
4848 }
4849 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4850 != AUDIO_OUTPUT_FLAG_NONE) {
4851 // If offload gapless is reported, no need to report offload support.
4852 directMode = (audio_direct_mode_t) ((directMode &
4853 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4854 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4855 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004856 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004857 }
4858 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004859 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004860 }
4861 }
4862 }
4863 return directMode;
4864}
4865
Dorin Drimusf2196d82022-01-03 12:11:18 +01004866status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4867 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004868 if (mEffects.isNonOffloadableEffectEnabled()) {
4869 return OK;
4870 }
jiabinf1c73972022-04-14 16:28:52 -07004871 DeviceVector devices;
4872 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004873 if (status != OK) {
4874 return status;
4875 }
4876 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4877 if (devices.empty()) {
4878 return OK; // no output devices for the attributes
4879 }
jiabinf1c73972022-04-14 16:28:52 -07004880 return getProfilesForDevices(devices, audioProfilesVector,
4881 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004882}
4883
jiabina84c3d32022-12-02 18:59:55 +00004884status_t AudioPolicyManager::getSupportedMixerAttributes(
4885 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4886 ALOGV("%s, portId=%d", __func__, portId);
4887 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4888 if (deviceDescriptor == nullptr) {
4889 ALOGE("%s the requested device is currently unavailable", __func__);
4890 return BAD_VALUE;
4891 }
jiabin96daffc2023-05-11 17:51:55 +00004892 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4893 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4894 deviceDescriptor->type());
4895 return BAD_VALUE;
4896 }
jiabina84c3d32022-12-02 18:59:55 +00004897 for (const auto& hwModule : mHwModules) {
4898 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4899 if (curProfile->supportsDevice(deviceDescriptor)) {
4900 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4901 }
4902 }
4903 }
4904 return NO_ERROR;
4905}
4906
4907status_t AudioPolicyManager::setPreferredMixerAttributes(
4908 const audio_attributes_t *attr,
4909 audio_port_handle_t portId,
4910 uid_t uid,
4911 const audio_mixer_attributes_t *mixerAttributes) {
4912 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4913 "mixerBehavior=%d}, uid=%d, portId=%u",
4914 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4915 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4916 mixerAttributes->mixer_behavior, uid, portId);
4917 if (attr->usage != AUDIO_USAGE_MEDIA) {
4918 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4919 return BAD_VALUE;
4920 }
4921 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4922 if (deviceDescriptor == nullptr) {
4923 ALOGE("%s the requested device is currently unavailable", __func__);
4924 return BAD_VALUE;
4925 }
4926 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4927 ALOGE("%s(%d), type=%d, is not a usb output device",
4928 __func__, portId, deviceDescriptor->type());
4929 return BAD_VALUE;
4930 }
4931
4932 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4933 audio_flags_to_audio_output_flags(attr->flags, &flags);
4934 flags = (audio_output_flags_t) (flags |
4935 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4936 sp<IOProfile> profile = nullptr;
4937 DeviceVector devices(deviceDescriptor);
4938 for (const auto& hwModule : mHwModules) {
4939 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4940 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004941 && curProfile->getCompatibilityScore(
4942 devices,
4943 mixerAttributes->config.sample_rate,
4944 nullptr /*updatedSamplingRate*/,
4945 mixerAttributes->config.format,
4946 nullptr /*updatedFormat*/,
4947 mixerAttributes->config.channel_mask,
4948 nullptr /*updatedChannelMask*/,
4949 flags,
4950 false /*exactMatchRequiredForInputFlags*/)
4951 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004952 profile = curProfile;
4953 break;
4954 }
4955 }
4956 }
4957 if (profile == nullptr) {
4958 ALOGE("%s, there is no compatible profile found", __func__);
4959 return BAD_VALUE;
4960 }
4961
4962 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4963 sp<PreferredMixerAttributesInfo>::make(
4964 uid, portId, profile, flags, *mixerAttributes);
4965 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4966 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4967
4968 // If 1) there is any client from the preferred mixer configuration owner that is currently
4969 // active and matches the strategy and 2) current output is on the preferred device and the
4970 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4971 // configuration.
4972 std::vector<audio_io_handle_t> outputsToReopen;
4973 for (size_t i = 0; i < mOutputs.size(); i++) {
4974 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004975 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4976 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004977 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004978 } else {
4979 for (const auto &client: output->getActiveClients()) {
4980 if (client->uid() == uid && client->strategy() == strategy) {
4981 client->setIsInvalid();
4982 outputsToReopen.push_back(output->mIoHandle);
4983 }
jiabina84c3d32022-12-02 18:59:55 +00004984 }
4985 }
4986 }
4987 }
4988 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4989 config.sample_rate = mixerAttributes->config.sample_rate;
4990 config.channel_mask = mixerAttributes->config.channel_mask;
4991 config.format = mixerAttributes->config.format;
4992 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004993 sp<SwAudioOutputDescriptor> desc =
4994 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4995 if (desc == nullptr) {
4996 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4997 continue;
4998 }
jiabin220eea12024-05-17 17:55:20 +00004999 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005000 }
5001
5002 return NO_ERROR;
5003}
5004
5005sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005006 audio_port_handle_t devicePortId,
5007 product_strategy_t strategy,
5008 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005009 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5010 if (it == mPreferredMixerAttrInfos.end()) {
5011 return nullptr;
5012 }
jiabind9a58d32023-06-01 17:57:30 +00005013 if (activeBitPerfectPreferred) {
5014 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005015 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005016 return info;
5017 }
5018 }
jiabina84c3d32022-12-02 18:59:55 +00005019 }
jiabind9a58d32023-06-01 17:57:30 +00005020 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5021 return strategyMatchedMixerAttrInfoIt == it->second.end()
5022 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005023}
5024
5025status_t AudioPolicyManager::getPreferredMixerAttributes(
5026 const audio_attributes_t *attr,
5027 audio_port_handle_t portId,
5028 audio_mixer_attributes_t* mixerAttributes) {
5029 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5030 portId, mEngine->getProductStrategyForAttributes(*attr));
5031 if (info == nullptr) {
5032 return NAME_NOT_FOUND;
5033 }
5034 *mixerAttributes = info->getMixerAttributes();
5035 return NO_ERROR;
5036}
5037
5038status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5039 audio_port_handle_t portId,
5040 uid_t uid) {
5041 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5042 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5043 if (preferredMixerAttrInfo == nullptr) {
5044 return NAME_NOT_FOUND;
5045 }
5046 if (preferredMixerAttrInfo->getUid() != uid) {
5047 ALOGE("%s, requested uid=%d, owned uid=%d",
5048 __func__, uid, preferredMixerAttrInfo->getUid());
5049 return PERMISSION_DENIED;
5050 }
5051 mPreferredMixerAttrInfos[portId].erase(strategy);
5052 if (mPreferredMixerAttrInfos[portId].empty()) {
5053 mPreferredMixerAttrInfos.erase(portId);
5054 }
5055
5056 // Reconfig existing output
5057 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5058 for (size_t i = 0; i < mOutputs.size(); i++) {
5059 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5060 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5061 }
5062 }
5063 for (const auto output : potentialOutputsToReopen) {
5064 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5065 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5066 preferredMixerAttrInfo->getFlags())) {
5067 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5068 }
5069 }
5070 return NO_ERROR;
5071}
5072
Eric Laurent6a94d692014-05-20 11:18:06 -07005073status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5074 audio_port_type_t type,
5075 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005076 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005077 unsigned int *generation)
5078{
jiabin19cdba52020-11-24 11:28:58 -08005079 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5080 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 return BAD_VALUE;
5082 }
5083 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005084 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 *num_ports = 0;
5086 }
5087
5088 size_t portsWritten = 0;
5089 size_t portsMax = *num_ports;
5090 *num_ports = 0;
5091 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005092 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5093 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005094 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005095 for (const auto& dev : mAvailableOutputDevices) {
5096 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005097 continue;
5098 }
5099 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005100 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005101 }
5102 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005103 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 }
5105 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005106 for (const auto& dev : mAvailableInputDevices) {
5107 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005108 continue;
5109 }
5110 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005111 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005112 }
5113 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 }
5116 }
5117 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5118 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5119 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5120 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5121 }
5122 *num_ports += mInputs.size();
5123 }
5124 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005125 size_t numOutputs = 0;
5126 for (size_t i = 0; i < mOutputs.size(); i++) {
5127 if (!mOutputs[i]->isDuplicated()) {
5128 numOutputs++;
5129 if (portsWritten < portsMax) {
5130 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5131 }
5132 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005133 }
Eric Laurent84c70242014-06-23 08:46:27 -07005134 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005135 }
5136 }
jiabina84c3d32022-12-02 18:59:55 +00005137
Eric Laurent6a94d692014-05-20 11:18:06 -07005138 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005139 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005140 return NO_ERROR;
5141}
5142
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005143status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5144 std::vector<media::AudioPortFw>* _aidl_return) {
5145 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5146 audio_port_v7 port;
5147 dev->toAudioPort(&port);
5148 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5149 _aidl_return->push_back(std::move(aidlPort));
5150 return OK;
5151 };
5152
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005153 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005154 for (const auto& dev : module->getDeclaredDevices()) {
5155 if (role == media::AudioPortRole::NONE ||
5156 ((role == media::AudioPortRole::SOURCE)
5157 == audio_is_input_device(dev->type()))) {
5158 RETURN_STATUS_IF_ERROR(pushPort(dev));
5159 }
5160 }
5161 }
5162 return OK;
5163}
5164
jiabin19cdba52020-11-24 11:28:58 -08005165status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005166{
Eric Laurent99fcae42018-05-17 16:59:18 -07005167 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5168 return BAD_VALUE;
5169 }
5170 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5171 if (dev != 0) {
5172 dev->toAudioPort(port);
5173 return NO_ERROR;
5174 }
5175 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5176 if (dev != 0) {
5177 dev->toAudioPort(port);
5178 return NO_ERROR;
5179 }
5180 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5181 if (out != 0) {
5182 out->toAudioPort(port);
5183 return NO_ERROR;
5184 }
5185 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5186 if (in != 0) {
5187 in->toAudioPort(port);
5188 return NO_ERROR;
5189 }
5190 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005191}
5192
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005193status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5194 audio_patch_handle_t *handle,
5195 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005196{
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 if (handle == NULL || patch == NULL) {
5199 return BAD_VALUE;
5200 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005201 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005202 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005203 return BAD_VALUE;
5204 }
5205 // only one source per audio patch supported for now
5206 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 return INVALID_OPERATION;
5208 }
Eric Laurent874c42872014-08-08 15:13:39 -07005209 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 return INVALID_OPERATION;
5211 }
Eric Laurent874c42872014-08-08 15:13:39 -07005212 for (size_t i = 0; i < patch->num_sinks; i++) {
5213 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5214 return INVALID_OPERATION;
5215 }
5216 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005217
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005218 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5219 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5220 if (srcDevice == nullptr || sinkDevice == nullptr) {
5221 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5222 return BAD_VALUE;
5223 }
5224 ALOGV("%s between source %s and sink %s", __func__,
5225 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5226 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5227 // Default attributes, default volume priority, not to infer with non raw audio patches.
5228 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5229 const struct audio_port_config *source = &patch->sources[0];
5230 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005231 new SourceClientDescriptor(
5232 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5233 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005234 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005235 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005236
5237 status_t status =
5238 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5239
5240 if (status != NO_ERROR) {
5241 return INVALID_OPERATION;
5242 }
5243 mAudioSources.add(portId, sourceDesc);
5244 return NO_ERROR;
5245}
5246
5247status_t AudioPolicyManager::connectAudioSourceToSink(
5248 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5249 const struct audio_patch *patch,
5250 audio_patch_handle_t &handle,
5251 uid_t uid, uint32_t delayMs)
5252{
5253 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5254 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5255 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5256 return INVALID_OPERATION;
5257 }
5258 sourceDesc->connect(handle, sinkDevice);
5259 if (isMsdPatch(handle)) {
5260 return NO_ERROR;
5261 }
5262 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5263 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5264 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5265 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5266 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5267 goto FailurePatchAdded;
5268 }
5269 status = swOutput->start();
5270 if (status != NO_ERROR) {
5271 goto FailureSourceAdded;
5272 }
5273 swOutput->addClient(sourceDesc);
5274 status = startSource(swOutput, sourceDesc, &delayMs);
5275 if (status != NO_ERROR) {
5276 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5277 goto FailureSourceActive;
5278 }
5279 if (delayMs != 0) {
5280 usleep(delayMs * 1000);
5281 }
5282 return NO_ERROR;
5283
5284FailureSourceActive:
5285 swOutput->stop();
5286 releaseOutput(sourceDesc->portId());
5287FailureSourceAdded:
5288 sourceDesc->setSwOutput(nullptr);
5289FailurePatchAdded:
5290 releaseAudioPatchInternal(handle);
5291 return INVALID_OPERATION;
5292}
5293
5294status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5295 audio_patch_handle_t *handle,
5296 uid_t uid, uint32_t delayMs,
5297 const sp<SourceClientDescriptor>& sourceDesc)
5298{
5299 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 sp<AudioPatch> patchDesc;
5301 ssize_t index = mAudioPatches.indexOfKey(*handle);
5302
François Gaffieafd4cea2019-11-18 15:50:22 +01005303 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5304 patch->sources[0].role,
5305 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005306#if LOG_NDEBUG == 0
5307 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005308 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5309 patch->sinks[i].role,
5310 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005311 }
5312#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005313
5314 if (index >= 0) {
5315 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5317 __func__, mUidCached, patchDesc->getUid(), uid);
5318 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 return INVALID_OPERATION;
5320 }
5321 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005322 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 }
5324
5325 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005326 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005328 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 return BAD_VALUE;
5330 }
Eric Laurent84c70242014-06-23 08:46:27 -07005331 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5332 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 if (patchDesc != 0) {
5334 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005335 ALOGV("%s source id differs for patch current id %d new id %d",
5336 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 return BAD_VALUE;
5338 }
5339 }
Eric Laurent874c42872014-08-08 15:13:39 -07005340 DeviceVector devices;
5341 for (size_t i = 0; i < patch->num_sinks; i++) {
5342 // Only support mix to devices connection
5343 // TODO add support for mix to mix connection
5344 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005345 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005346 return INVALID_OPERATION;
5347 }
5348 sp<DeviceDescriptor> devDesc =
5349 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5350 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005351 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005352 return BAD_VALUE;
5353 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005354
jiabin66acc432024-02-06 00:57:36 +00005355 if (outputDesc->mProfile->getCompatibilityScore(
5356 DeviceVector(devDesc),
5357 patch->sources[0].sample_rate,
5358 nullptr, // updatedSamplingRate
5359 patch->sources[0].format,
5360 nullptr, // updatedFormat
5361 patch->sources[0].channel_mask,
5362 nullptr, // updatedChannelMask
5363 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005364 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005365 return INVALID_OPERATION;
5366 }
5367 devices.add(devDesc);
5368 }
5369 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 return INVALID_OPERATION;
5371 }
Eric Laurent874c42872014-08-08 15:13:39 -07005372
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 ALOGV("%s setting device %s on output %d",
5375 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305376 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005377 index = mAudioPatches.indexOfKey(*handle);
5378 if (index >= 0) {
5379 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005380 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005381 }
5382 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005383 patchDesc->setUid(uid);
5384 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005385 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005386 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 return INVALID_OPERATION;
5388 }
5389 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5390 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5391 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005392 // only one sink supported when connecting an input device to a mix
5393 if (patch->num_sinks > 1) {
5394 return INVALID_OPERATION;
5395 }
François Gaffie53615e22015-03-19 09:24:12 +01005396 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 if (inputDesc == NULL) {
5398 return BAD_VALUE;
5399 }
5400 if (patchDesc != 0) {
5401 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5402 return BAD_VALUE;
5403 }
5404 }
François Gaffie11d30102018-11-02 16:09:09 +01005405 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005406 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005407 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 return BAD_VALUE;
5409 }
5410
jiabin66acc432024-02-06 00:57:36 +00005411 if (inputDesc->mProfile->getCompatibilityScore(
5412 DeviceVector(device),
5413 patch->sinks[0].sample_rate,
5414 nullptr, /*updatedSampleRate*/
5415 patch->sinks[0].format,
5416 nullptr, /*updatedFormat*/
5417 patch->sinks[0].channel_mask,
5418 nullptr, /*updatedChannelMask*/
5419 // FIXME for the parameter type,
5420 // and the NONE
5421 (audio_output_flags_t)
5422 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005423 return INVALID_OPERATION;
5424 }
5425 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005426 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005427 device->toString().c_str(), inputDesc->mIoHandle);
5428 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005429 index = mAudioPatches.indexOfKey(*handle);
5430 if (index >= 0) {
5431 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005432 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005433 }
5434 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005435 patchDesc->setUid(uid);
5436 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005437 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005438 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005439 return INVALID_OPERATION;
5440 }
5441 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5442 // device to device connection
5443 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005444 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005445 return BAD_VALUE;
5446 }
5447 }
François Gaffie11d30102018-11-02 16:09:09 +01005448 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005449 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005450 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005451 return BAD_VALUE;
5452 }
Eric Laurent874c42872014-08-08 15:13:39 -07005453
Eric Laurent6a94d692014-05-20 11:18:06 -07005454 //update source and sink with our own data as the data passed in the patch may
5455 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005456 PatchBuilder patchBuilder;
5457 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005458
5459 // if first sink is to MSD, establish single MSD patch
5460 if (getMsdAudioOutDevices().contains(
5461 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5462 ALOGV("%s patching to MSD", __FUNCTION__);
5463 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5464 goto installPatch;
5465 }
5466
François Gaffieafd4cea2019-11-18 15:50:22 +01005467 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5468 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005469
Eric Laurent874c42872014-08-08 15:13:39 -07005470 for (size_t i = 0; i < patch->num_sinks; i++) {
5471 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005472 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005473 return INVALID_OPERATION;
5474 }
François Gaffie11d30102018-11-02 16:09:09 +01005475 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005476 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005477 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005478 return BAD_VALUE;
5479 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005480 audio_port_config sinkPortConfig = {};
5481 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5482 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005483
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005484 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5485 // volume management purpose (tracking activity)
5486 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5487 // in config XML to reach the sink so that is can be declared as available.
5488 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005489 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005490 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005491 // take care of dynamic routing for SwOutput selection,
5492 audio_attributes_t attributes = sourceDesc->attributes();
5493 audio_stream_type_t stream = sourceDesc->stream();
5494 audio_attributes_t resultAttr;
5495 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5496 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005497 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5498 config.channel_mask =
5499 (audio_channel_mask_get_representation(sourceMask)
5500 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5501 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005502 config.format = sourceDesc->config().format;
5503 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5504 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5505 bool isRequestedDeviceForExclusiveUse = false;
5506 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005507 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005508 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005509 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5510 &stream, sourceDesc->uid(), &config, &flags,
5511 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005512 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005513 if (output == AUDIO_IO_HANDLE_NONE) {
5514 ALOGV("%s no output for device %s",
5515 __FUNCTION__, sinkDevice->toString().c_str());
5516 return INVALID_OPERATION;
5517 }
5518 outputDesc = mOutputs.valueFor(output);
5519 if (outputDesc->isDuplicated()) {
5520 ALOGE("%s output is duplicated", __func__);
5521 return INVALID_OPERATION;
5522 }
François Gaffie7e39df22022-04-26 12:48:49 +02005523 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5524 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005525 } else {
5526 // Same for "raw patches" aka created from createAudioPatch API
5527 SortedVector<audio_io_handle_t> outputs =
5528 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5529 // if the sink device is reachable via an opened output stream, request to
5530 // go via this output stream by adding a second source to the patch
5531 // description
5532 output = selectOutput(outputs);
5533 if (output == AUDIO_IO_HANDLE_NONE) {
5534 ALOGE("%s no output available for internal patch sink", __func__);
5535 return INVALID_OPERATION;
5536 }
5537 outputDesc = mOutputs.valueFor(output);
5538 if (outputDesc->isDuplicated()) {
5539 ALOGV("%s output for device %s is duplicated",
5540 __func__, sinkDevice->toString().c_str());
5541 return INVALID_OPERATION;
5542 }
François Gaffie7e39df22022-04-26 12:48:49 +02005543 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005544 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005545 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005546 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005547 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005548 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005549 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5550 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005551 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5552 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005553 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005554 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005555 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005556 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005557 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005558 return INVALID_OPERATION;
5559 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005560 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005561 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005562 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005563 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005564 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005565 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005566 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005567 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5568 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005570 }
Eric Laurent83b88082014-06-20 18:31:16 -07005571 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005572 }
5573 // TODO: check from routing capabilities in config file and other conflicting patches
5574
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005575installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005576 status_t status = installPatch(
5577 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005578 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005579 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005580 return INVALID_OPERATION;
5581 }
5582 } else {
5583 return BAD_VALUE;
5584 }
5585 } else {
5586 return BAD_VALUE;
5587 }
5588 return NO_ERROR;
5589}
5590
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005591status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005592{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005593 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005594 ssize_t index = mAudioPatches.indexOfKey(handle);
5595
5596 if (index < 0) {
5597 return BAD_VALUE;
5598 }
5599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005600 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5601 __func__, mUidCached, patchDesc->getUid(), uid);
5602 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005603 return INVALID_OPERATION;
5604 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005605 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5606 for (size_t i = 0; i < mAudioSources.size(); i++) {
5607 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5608 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5609 portId = sourceDesc->portId();
5610 break;
5611 }
5612 }
5613 return portId != AUDIO_PORT_HANDLE_NONE ?
5614 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005615}
Eric Laurent6a94d692014-05-20 11:18:06 -07005616
François Gaffieafd4cea2019-11-18 15:50:22 +01005617status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005618 uint32_t delayMs,
5619 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005620{
5621 ALOGV("%s patch %d", __func__, handle);
5622 if (mAudioPatches.indexOfKey(handle) < 0) {
5623 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5624 return BAD_VALUE;
5625 }
5626 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005627 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005628 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005629 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005630 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005631 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005632 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005633 return BAD_VALUE;
5634 }
5635
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305636 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005637 getNewOutputDevices(outputDesc, true /*fromCache*/),
5638 true,
5639 0,
5640 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005641 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5642 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005643 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005644 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005645 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005646 return BAD_VALUE;
5647 }
5648 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005649 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005650 true,
5651 NULL);
5652 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005653 status_t status =
5654 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5655 ALOGV("%s patch panel returned %d patchHandle %d",
5656 __func__, status, patchDesc->getAfHandle());
5657 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005658 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005659 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005660 // SW or HW Bridge
5661 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5662 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005663 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005664 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5665 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5666 outputDesc = sourceDesc->swOutput().promote();
5667 }
5668 if (outputDesc == nullptr) {
5669 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5670 // releaseOutput has already called closeOutput in case of direct output
5671 return NO_ERROR;
5672 }
François Gaffie7e39df22022-04-26 12:48:49 +02005673 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005674 // While using a HwBridge, force reconsidering device only if not reusing an existing
5675 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005676 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005677 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5678 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5679 // Reconsider device only for cases:
5680 // 1 / Active Output
5681 // 2 / Inactive Output previously hosting HwBridge
5682 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5683 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5684 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305685 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005686 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5687 outputDesc->devices(),
5688 force,
5689 0,
5690 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005691 } else {
5692 return BAD_VALUE;
5693 }
5694 } else {
5695 return BAD_VALUE;
5696 }
5697 return NO_ERROR;
5698}
5699
5700status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5701 struct audio_patch *patches,
5702 unsigned int *generation)
5703{
François Gaffie53615e22015-03-19 09:24:12 +01005704 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005705 return BAD_VALUE;
5706 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005707 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005708 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005709}
5710
Eric Laurente1715a42014-05-20 11:30:42 -07005711status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005712{
Eric Laurente1715a42014-05-20 11:30:42 -07005713 ALOGV("setAudioPortConfig()");
5714
5715 if (config == NULL) {
5716 return BAD_VALUE;
5717 }
5718 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5719 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005720 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5721 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005722 }
5723
Eric Laurenta121f902014-06-03 13:32:54 -07005724 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005725 if (config->type == AUDIO_PORT_TYPE_MIX) {
5726 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005727 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005728 if (outputDesc == NULL) {
5729 return BAD_VALUE;
5730 }
Eric Laurent84c70242014-06-23 08:46:27 -07005731 ALOG_ASSERT(!outputDesc->isDuplicated(),
5732 "setAudioPortConfig() called on duplicated output %d",
5733 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005734 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005735 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005736 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005737 if (inputDesc == NULL) {
5738 return BAD_VALUE;
5739 }
Eric Laurenta121f902014-06-03 13:32:54 -07005740 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005741 } else {
5742 return BAD_VALUE;
5743 }
5744 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5745 sp<DeviceDescriptor> deviceDesc;
5746 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5747 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5748 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5749 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5750 } else {
5751 return BAD_VALUE;
5752 }
5753 if (deviceDesc == NULL) {
5754 return BAD_VALUE;
5755 }
Eric Laurenta121f902014-06-03 13:32:54 -07005756 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005757 } else {
5758 return BAD_VALUE;
5759 }
5760
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005761 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005762 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5763 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005764 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005765 audioPortConfig->toAudioPortConfig(&newConfig, config);
5766 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005767 }
Eric Laurenta121f902014-06-03 13:32:54 -07005768 if (status != NO_ERROR) {
5769 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005770 }
Eric Laurente1715a42014-05-20 11:30:42 -07005771
5772 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005773}
5774
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005775void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5776{
Eric Laurentd60560a2015-04-10 11:31:20 -07005777 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005778 clearAudioPatches(uid);
5779 clearSessionRoutes(uid);
5780}
5781
Eric Laurent6a94d692014-05-20 11:18:06 -07005782void AudioPolicyManager::clearAudioPatches(uid_t uid)
5783{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005784 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005785 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005786 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005787 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005788 }
5789 }
5790}
5791
François Gaffiec005e562018-11-06 15:04:49 +01005792void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005793{
François Gaffiec005e562018-11-06 15:04:49 +01005794 // Take the first attributes following the product strategy as it is used to retrieve the routed
5795 // device. All attributes wihin a strategy follows the same "routing strategy"
5796 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5797 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005798 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005799 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005800 for (size_t j = 0; j < mOutputs.size(); j++) {
5801 if (mOutputs.keyAt(j) == ouptutToSkip) {
5802 continue;
5803 }
5804 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005805 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005806 continue;
5807 }
5808 // If the default device for this strategy is on another output mix,
5809 // invalidate all tracks in this strategy to force re connection.
5810 // Otherwise select new device on the output mix.
5811 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005812 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005813 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005814 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005815 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005816 // If the device is using preferred mixer attributes, the output need to reopen
5817 // with default configuration when the new selected devices are different from
5818 // current routing devices.
5819 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5820 continue;
5821 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305822 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005823 }
5824 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005825 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005826}
5827
5828void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5829{
5830 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005831 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005832 for (size_t i = 0; i < mOutputs.size(); i++) {
5833 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005834 for (const auto& client : outputDesc->getClientIterable()) {
5835 if (client->hasPreferredDevice() && client->uid() == uid) {
5836 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005837 auto clientStrategy = client->strategy();
5838 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5839 end(affectedStrategies)) {
5840 continue;
5841 }
5842 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005843 }
5844 }
5845 }
5846 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005847 for (const auto& strategy : affectedStrategies) {
5848 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005849 }
5850
5851 // remove input routes associated with this uid
5852 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005853 for (size_t i = 0; i < mInputs.size(); i++) {
5854 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005855 for (const auto& client : inputDesc->getClientIterable()) {
5856 if (client->hasPreferredDevice() && client->uid() == uid) {
5857 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5858 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005859 }
5860 }
5861 }
5862 // reroute inputs if necessary
5863 SortedVector<audio_io_handle_t> inputsToClose;
5864 for (size_t i = 0; i < mInputs.size(); i++) {
5865 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005866 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005867 inputsToClose.add(inputDesc->mIoHandle);
5868 }
5869 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005870 for (const auto& input : inputsToClose) {
5871 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005872 }
5873}
5874
Eric Laurentd60560a2015-04-10 11:31:20 -07005875void AudioPolicyManager::clearAudioSources(uid_t uid)
5876{
5877 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005878 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5879 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005880 stopAudioSource(mAudioSources.keyAt(i));
5881 }
5882 }
5883}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005884
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005885status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5886 audio_io_handle_t *ioHandle,
5887 audio_devices_t *device)
5888{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005889 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5890 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005891 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005892 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5893 if (deviceDesc == nullptr) {
5894 return INVALID_OPERATION;
5895 }
5896 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005897
François Gaffiedf372692015-03-19 10:43:27 +01005898 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005899}
5900
Eric Laurentd60560a2015-04-10 11:31:20 -07005901status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005902 const audio_attributes_t *attributes,
5903 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005904 uid_t uid) {
5905 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005906 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005907}
5908
5909status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5910 const audio_attributes_t *attributes,
5911 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005912 uid_t uid, bool internal, bool isCallRx,
5913 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005914{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005915 ALOGV("%s", __FUNCTION__);
5916 *portId = AUDIO_PORT_HANDLE_NONE;
5917
5918 if (source == NULL || attributes == NULL || portId == NULL) {
5919 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5920 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 return BAD_VALUE;
5922 }
5923
Eric Laurentd60560a2015-04-10 11:31:20 -07005924 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5925 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005926 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5927 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005928 return INVALID_OPERATION;
5929 }
5930
François Gaffie11d30102018-11-02 16:09:09 +01005931 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005932 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005933 String8(source->ext.device.address),
5934 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005935 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005936 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005937 return BAD_VALUE;
5938 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005939
jiabin4ef93452019-09-10 14:29:54 -07005940 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005941
François Gaffieaaac0fd2018-11-22 17:56:39 +01005942 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005943 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005944 mEngine->getStreamTypeForAttributes(*attributes),
5945 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005946 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005947
David Lif85c5e32024-07-01 13:14:10 +00005948 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005949 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005950 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005951 }
5952 return status;
5953}
5954
David Lif85c5e32024-07-01 13:14:10 +00005955status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5956 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005957{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005958 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005959
5960 // make sure we only have one patch per source.
5961 disconnectAudioSource(sourceDesc);
5962
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005963 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005964 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5965 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5966 sourceDesc->srcDevice()->type(),
5967 String8(sourceDesc->srcDevice()->address().c_str()),
5968 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005969 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005970 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005971 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005972 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005973 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5974 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5975 return INVALID_OPERATION;
5976 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005977 PatchBuilder patchBuilder;
5978 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5979 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005980
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005981 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00005982 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005983}
5984
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005985status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005986{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005987 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5988 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005989 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005990 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005991 return BAD_VALUE;
5992 }
5993 status_t status = disconnectAudioSource(sourceDesc);
5994
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005995 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005996 return status;
5997}
5998
Andy Hung2ddee192015-12-18 17:34:44 -08005999status_t AudioPolicyManager::setMasterMono(bool mono)
6000{
6001 if (mMasterMono == mono) {
6002 return NO_ERROR;
6003 }
6004 mMasterMono = mono;
6005 // if enabling mono we close all offloaded devices, which will invalidate the
6006 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6007 // for recreating the new AudioTrack as non-offloaded PCM.
6008 //
6009 // If disabling mono, we leave all tracks as is: we don't know which clients
6010 // and tracks are able to be recreated as offloaded. The next "song" should
6011 // play back offloaded.
6012 if (mMasterMono) {
6013 Vector<audio_io_handle_t> offloaded;
6014 for (size_t i = 0; i < mOutputs.size(); ++i) {
6015 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6016 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6017 offloaded.push(desc->mIoHandle);
6018 }
6019 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006020 for (const auto& handle : offloaded) {
6021 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006022 }
6023 }
6024 // update master mono for all remaining outputs
6025 for (size_t i = 0; i < mOutputs.size(); ++i) {
6026 updateMono(mOutputs.keyAt(i));
6027 }
6028 return NO_ERROR;
6029}
6030
6031status_t AudioPolicyManager::getMasterMono(bool *mono)
6032{
6033 *mono = mMasterMono;
6034 return NO_ERROR;
6035}
6036
Eric Laurentac9cef52017-06-09 15:46:26 -07006037float AudioPolicyManager::getStreamVolumeDB(
6038 audio_stream_type_t stream, int index, audio_devices_t device)
6039{
Vlad Popa9d482762024-06-21 16:40:23 -07006040 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6041 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006042}
6043
jiabin81772902018-04-02 17:52:27 -07006044status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6045 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006046 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006047{
Kriti Dang6537def2021-03-02 13:46:59 +01006048 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6049 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006050 return BAD_VALUE;
6051 }
Kriti Dang6537def2021-03-02 13:46:59 +01006052 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6053 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006054
6055 size_t formatsWritten = 0;
6056 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006057
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006058 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006059 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6060 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006061 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006062 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006063 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006064 bool formatEnabled = true;
6065 switch (forceUse) {
6066 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006067 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006068 break;
6069 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6070 formatEnabled = false;
6071 break;
6072 default: // AUTO or ALWAYS => true
6073 break;
jiabin81772902018-04-02 17:52:27 -07006074 }
6075 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6076 }
jiabin81772902018-04-02 17:52:27 -07006077 }
6078 return NO_ERROR;
6079}
6080
Kriti Dang6537def2021-03-02 13:46:59 +01006081status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6082 audio_format_t *surroundFormats) {
6083 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6084 return BAD_VALUE;
6085 }
6086 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6087 __func__, *numSurroundFormats, surroundFormats);
6088
6089 size_t formatsWritten = 0;
6090 size_t formatsMax = *numSurroundFormats;
6091 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6092
6093 // Return formats from all device profiles that have already been resolved by
6094 // checkOutputsForDevice().
6095 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6096 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6097 audio_devices_t deviceType = device->type();
6098 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6099 // returns formats reported by HDMI devices.
6100 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6101 continue;
6102 }
6103 // Formats reported by sink devices
6104 std::unordered_set<audio_format_t> formatset;
6105 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6106 formatset.insert(it->second.begin(), it->second.end());
6107 }
6108
6109 // Formats hard-coded in the in policy configuration file (if any).
6110 FormatVector encodedFormats = device->encodedFormats();
6111 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6112 // Filter the formats which are supported by the vendor hardware.
6113 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006114 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006115 formats.insert(*it);
6116 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006117 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006118 if (pair.second.count(*it) != 0) {
6119 formats.insert(pair.first);
6120 break;
6121 }
6122 }
6123 }
6124 }
6125 }
6126 *numSurroundFormats = formats.size();
6127 for (const auto& format: formats) {
6128 if (formatsWritten < formatsMax) {
6129 surroundFormats[formatsWritten++] = format;
6130 }
6131 }
6132 return NO_ERROR;
6133}
6134
jiabin81772902018-04-02 17:52:27 -07006135status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6136{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006137 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006138 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6139 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006140 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006141 return BAD_VALUE;
6142 }
6143
Mikhail Naganov100f0122018-11-29 11:22:16 -08006144 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6145 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006146 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006147 return INVALID_OPERATION;
6148 }
6149
Mikhail Naganov100f0122018-11-29 11:22:16 -08006150 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006151 return NO_ERROR;
6152 }
6153
Mikhail Naganov100f0122018-11-29 11:22:16 -08006154 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006155 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006156 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006157 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006158 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006159 }
6160 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006161 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006162 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006163 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006164 }
6165 }
6166
6167 sp<SwAudioOutputDescriptor> outputDesc;
6168 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006169 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6170 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006171 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6172 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006173 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006174 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006175 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6176 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
6181 continue;
6182 }
6183 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6184 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6185 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006186 name.c_str(),
6187 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006188 profileUpdated |= (status == NO_ERROR);
6189 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006190 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006191 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006192 AUDIO_DEVICE_IN_HDMI);
6193 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6194 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006195 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006196 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006197 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6198 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
6203 continue;
6204 }
6205 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6206 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6207 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006208 name.c_str(),
6209 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006210 profileUpdated |= (status == NO_ERROR);
6211 }
6212
jiabin81772902018-04-02 17:52:27 -07006213 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006214 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006215 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006216 }
6217
6218 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6219}
6220
Eric Laurent5ada82e2019-08-29 17:53:54 -07006221void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006222{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006223 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006224 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006225 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006226 }
6227}
6228
jiabin6012f912018-11-02 17:06:30 -07006229bool AudioPolicyManager::isHapticPlaybackSupported()
6230{
6231 for (const auto& hwModule : mHwModules) {
6232 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6233 for (const auto &outProfile : outputProfiles) {
6234 struct audio_port audioPort;
6235 outProfile->toAudioPort(&audioPort);
6236 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6237 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6238 return true;
6239 }
6240 }
6241 }
6242 }
6243 return false;
6244}
6245
Carter Hsu325a8eb2022-01-19 19:56:51 +08006246bool AudioPolicyManager::isUltrasoundSupported()
6247{
6248 bool hasUltrasoundOutput = false;
6249 bool hasUltrasoundInput = false;
6250 for (const auto& hwModule : mHwModules) {
6251 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6252 if (!hasUltrasoundOutput) {
6253 for (const auto &outProfile : outputProfiles) {
6254 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6255 hasUltrasoundOutput = true;
6256 break;
6257 }
6258 }
6259 }
6260
6261 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6262 if (!hasUltrasoundInput) {
6263 for (const auto &inputProfile : inputProfiles) {
6264 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6265 hasUltrasoundInput = true;
6266 break;
6267 }
6268 }
6269 }
6270
6271 if (hasUltrasoundOutput && hasUltrasoundInput)
6272 return true;
6273 }
6274 return false;
6275}
6276
Atneya Nair698f5ef2022-12-15 16:15:09 -08006277bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6278{
6279 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6280 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6281 for (const auto& hwModule : mHwModules) {
6282 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6283 for (const auto &inputProfile : inputProfiles) {
6284 if ((inputProfile->getFlags() & mask) == mask) {
6285 return true;
6286 }
6287 }
6288 }
6289 return false;
6290}
6291
Eric Laurent8340e672019-11-06 11:01:08 -08006292bool AudioPolicyManager::isCallScreenModeSupported()
6293{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006294 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006295}
6296
6297
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006298status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006299{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006300 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006301 if (!sourceDesc->isConnected()) {
6302 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6303 return NO_ERROR;
6304 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006305 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6306 if (swOutput != 0) {
6307 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006308 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006309 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006310 }
jiabinbce0c1d2020-10-05 11:20:18 -07006311 if (releaseOutput(sourceDesc->portId())) {
6312 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6313 // no need to release audio patch here but just return NO_ERROR.
6314 return NO_ERROR;
6315 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006316 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006317 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006318 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006319 // close Hwoutput and remove from mHwOutputs
6320 } else {
6321 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6322 }
6323 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006324 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006325 sourceDesc->disconnect();
6326 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006327}
6328
François Gaffiec005e562018-11-06 15:04:49 +01006329sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6330 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006331{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006332 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006333 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006334 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006335 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006336 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6337 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006338 source = sourceDesc;
6339 break;
6340 }
6341 }
6342 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006343}
6344
Eric Laurentb4f42a92022-01-17 17:37:31 +01006345bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006346 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006347 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006348{
6349 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6350 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006351 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006352 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006353 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6354 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6355 return false;
6356 }
6357 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6358 return false;
6359 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006360 }
6361
Eric Laurentd332bc82023-08-04 11:45:23 +02006362 // The caller can have the audio config criteria ignored by either passing a null ptr or
6363 // the AUDIO_CONFIG_INITIALIZER value.
6364 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006365 // some positional channel masks and PCM format and for stereo if low latency performance
6366 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006367
6368 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurentb16eac52024-08-02 16:46:08 +00006369 static const bool stereo_spatialization_prop_enabled =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006370 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006371 const bool channel_mask_spatialized =
Eric Laurentb16eac52024-08-02 16:46:08 +00006372 (stereo_spatialization_prop_enabled
6373 && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006374 ? audio_channel_mask_contains_stereo(config->channel_mask)
6375 : audio_is_channel_mask_spatialized(config->channel_mask);
6376 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006377 return false;
6378 }
6379 if (!audio_is_linear_pcm(config->format)) {
6380 return false;
6381 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006382 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6383 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6384 return false;
6385 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006386 }
6387
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006388 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006389 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006390 if (profile == nullptr) {
6391 return false;
6392 }
6393
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006394 return true;
6395}
6396
Shunkai Yao4c3af932024-04-26 04:12:21 +00006397// The Spatializer output is compatible with Haptic use cases if:
6398// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6399// with client if client haptic channel bits were set, or
6400// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6401// including the haptic bits or creating the HapticGenerator effect for same session.
6402bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6403 const audio_config_t* config, audio_session_t sessionId) const {
6404 const auto clientHapticChannel =
6405 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6406 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6407 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6408
6409 if (threadOutputHapticChannel) {
6410 // check format and sampleRate match if client haptic channel mask exist
6411 if (clientHapticChannel) {
6412 return mSpatializerOutput->getFormat() == config->format &&
6413 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6414 }
6415 return true;
6416 } else {
6417 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6418 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6419 // HapticGenerator effect for this session) are not supported.
6420 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006421 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006422 }
6423}
6424
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006425void AudioPolicyManager::checkVirtualizerClientRoutes() {
6426 std::set<audio_stream_type_t> streamsToInvalidate;
6427 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006428 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6429 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006430 audio_attributes_t attr = client->attributes();
6431 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6432 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6433 audio_config_base_t clientConfig = client->config();
6434 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006435 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006436 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006437 streamsToInvalidate.insert(client->stream());
6438 }
6439 }
6440 }
6441
jiabinc44b3462022-12-08 12:52:31 -08006442 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006443}
6444
Eric Laurente191d1b2022-04-15 11:59:25 +02006445
6446bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6447 const sp<SwAudioOutputDescriptor>& outputDesc) {
6448 if (outputDesc->isDuplicated()) {
6449 return false;
6450 }
6451 DeviceVector devices = outputDesc->supportedDevices();
6452 for (size_t i = 0; i < mOutputs.size(); i++) {
6453 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6454 if (desc == outputDesc || desc->isDuplicated()) {
6455 continue;
6456 }
6457 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6458 if (!sharedDevices.isEmpty()
6459 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6460 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6461 return false;
6462 }
6463 }
6464 return true;
6465}
6466
6467
Eric Laurentfa0f6742021-08-17 18:39:44 +02006468status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006469 const audio_attributes_t *attr,
6470 audio_io_handle_t *output) {
6471 *output = AUDIO_IO_HANDLE_NONE;
6472
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006473 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6474 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6475 audio_config_t *configPtr = nullptr;
6476 audio_config_t config;
6477 if (mixerConfig != nullptr) {
6478 config = audio_config_initializer(mixerConfig);
6479 configPtr = &config;
6480 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006481 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006482 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006483 return BAD_VALUE;
6484 }
6485
6486 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006487 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006488 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006489 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006490 return BAD_VALUE;
6491 }
6492
Eric Laurente191d1b2022-04-15 11:59:25 +02006493 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006494 for (size_t i = 0; i < mOutputs.size(); i++) {
6495 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006496 if (!desc->isDuplicated()
6497 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6498 spatializerOutputs.push_back(desc);
6499 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006500 }
6501 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006502 mSpatializerOutput.clear();
6503 bool outputsChanged = false;
6504 for (const auto& desc : spatializerOutputs) {
6505 if (desc->mProfile == profile
6506 && (configPtr == nullptr
6507 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6508 mSpatializerOutput = desc;
6509 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6510 } else {
6511 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6512 " and devices %s", __func__, desc->mIoHandle,
6513 configPtr != nullptr ? configPtr->channel_mask : 0,
6514 devices.toString().c_str());
6515 closeOutput(desc->mIoHandle);
6516 outputsChanged = true;
6517 }
Eric Laurent39095982021-08-24 18:29:27 +02006518 }
6519
Eric Laurente191d1b2022-04-15 11:59:25 +02006520 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006521 sp<SwAudioOutputDescriptor> desc =
6522 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006523 if (desc != nullptr) {
6524 mSpatializerOutput = desc;
6525 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006526 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006527 }
6528
6529 checkVirtualizerClientRoutes();
6530
Eric Laurente191d1b2022-04-15 11:59:25 +02006531 if (outputsChanged) {
6532 mPreviousOutputs = mOutputs;
6533 mpClientInterface->onAudioPortListUpdate();
6534 }
6535
6536 if (mSpatializerOutput == nullptr) {
6537 ALOGV("%s could not open spatializer output with requested config", __func__);
6538 return BAD_VALUE;
6539 }
Eric Laurent39095982021-08-24 18:29:27 +02006540 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006541 ALOGV("%s returning new spatializer output %d", __func__, *output);
6542 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006543}
6544
Eric Laurentfa0f6742021-08-17 18:39:44 +02006545status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6546 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006547 return INVALID_OPERATION;
6548 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006549 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006550 return BAD_VALUE;
6551 }
Eric Laurent39095982021-08-24 18:29:27 +02006552
Eric Laurente191d1b2022-04-15 11:59:25 +02006553 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6554 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6555 closeOutput(mSpatializerOutput->mIoHandle);
6556 //from now on mSpatializerOutput is null
6557 checkVirtualizerClientRoutes();
6558 }
Eric Laurent39095982021-08-24 18:29:27 +02006559
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006560 return NO_ERROR;
6561}
6562
Eric Laurente552edb2014-03-10 17:42:56 -07006563// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006564// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006565// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006566uint32_t AudioPolicyManager::nextAudioPortGeneration()
6567{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006568 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006569}
6570
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006571AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006572 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006573 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006574 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006575 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006576 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006577 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006578 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006579 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006580 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006581 mAudioPortGeneration(1),
6582 mBeaconMuteRefCount(0),
6583 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006584 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006585 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006586 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006587 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006588{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006589}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006590
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006591status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006592 if (mEngine == nullptr) {
6593 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006594 }
6595 mEngine->setObserver(this);
6596 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006597 if (status != NO_ERROR) {
6598 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6599 return status;
6600 }
François Gaffie2110e042015-03-24 08:41:51 +01006601
jiabin29230182023-04-04 21:02:36 +00006602 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6603 // at the end of this function.
6604 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006605 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6606 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6607
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006608 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006609 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006610 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006611
Eric Laurent3a4311c2014-03-17 12:00:47 -07006612 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006613 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6614 defaultOutputDevice == nullptr ||
6615 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6616 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6617 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006618 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006619 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006620 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006621
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006622 // Silence ALOGV statements
6623 property_set("log.tag." LOG_TAG, "D");
6624
Eric Laurente552edb2014-03-10 17:42:56 -07006625 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006626 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006627}
6628
Eric Laurente0720872014-03-11 09:30:41 -07006629AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006630{
Eric Laurente552edb2014-03-10 17:42:56 -07006631 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006632 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006633 }
6634 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006635 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006636 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006637 mAvailableOutputDevices.clear();
6638 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006639 mOutputs.clear();
6640 mInputs.clear();
6641 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006642 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006643 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006644}
6645
Eric Laurente0720872014-03-11 09:30:41 -07006646status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006647{
Eric Laurent87ffa392015-05-22 10:32:38 -07006648 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006649}
6650
Eric Laurente552edb2014-03-10 17:42:56 -07006651// ---
6652
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006653void AudioPolicyManager::onNewAudioModulesAvailable()
6654{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006655 DeviceVector newDevices;
6656 onNewAudioModulesAvailableInt(&newDevices);
6657 if (!newDevices.empty()) {
6658 nextAudioPortGeneration();
6659 mpClientInterface->onAudioPortListUpdate();
6660 }
6661}
6662
6663void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6664{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006665 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006666 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6667 continue;
6668 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006669 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006670 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6671 handle != AUDIO_MODULE_HANDLE_NONE) {
6672 hwModule->setHandle(handle);
6673 } else {
6674 ALOGW("could not load HW module %s", hwModule->getName());
6675 continue;
6676 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006677 }
6678 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006679 // open all output streams needed to access attached devices.
6680 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006681 // This also validates mAvailableOutputDevices list
6682 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6683 if (!outProfile->canOpenNewIo()) {
6684 ALOGE("Invalid Output profile max open count %u for profile %s",
6685 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6686 continue;
6687 }
6688 if (!outProfile->hasSupportedDevices()) {
6689 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6690 continue;
6691 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006692 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6693 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006694 mTtsOutputAvailable = true;
6695 }
6696
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006697 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006698 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006699 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006700 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6701 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006702 } else {
6703 // choose first device present in profile's SupportedDevices also part of
6704 // mAvailableOutputDevices.
6705 if (availProfileDevices.isEmpty()) {
6706 continue;
6707 }
6708 supportedDevice = availProfileDevices.itemAt(0);
6709 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006710 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006711 continue;
6712 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306713
6714 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6715 && availProfileDevices.areAllDevicesAttached()) {
6716 ALOGV("%s skip opening output for mmap profile %s", __func__,
6717 outProfile->getTagName().c_str());
6718 continue;
6719 }
6720
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006721 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6722 mpClientInterface);
6723 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006724 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006725 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6726 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006727 AUDIO_STREAM_DEFAULT,
Haofan Wangf6e304f2024-07-09 23:06:58 -07006728 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006729 if (status != NO_ERROR) {
6730 ALOGW("Cannot open output stream for devices %s on hw module %s",
6731 supportedDevice->toString().c_str(), hwModule->getName());
6732 continue;
6733 }
6734 for (const auto &device : availProfileDevices) {
6735 // give a valid ID to an attached device once confirmed it is reachable
6736 if (!device->isAttached()) {
6737 device->attach(hwModule);
6738 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006739 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006740 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006741 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6742 }
6743 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006744 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006745 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6746 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006747 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006748 }
Eric Laurent39095982021-08-24 18:29:27 +02006749 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006750 outputDesc->close();
6751 } else {
6752 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306753 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006754 DeviceVector(supportedDevice),
6755 true,
6756 0,
6757 NULL);
6758 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006759 }
6760 // open input streams needed to access attached devices to validate
6761 // mAvailableInputDevices list
6762 for (const auto& inProfile : hwModule->getInputProfiles()) {
6763 if (!inProfile->canOpenNewIo()) {
6764 ALOGE("Invalid Input profile max open count %u for profile %s",
6765 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6766 continue;
6767 }
6768 if (!inProfile->hasSupportedDevices()) {
6769 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6770 continue;
6771 }
6772 // chose first device present in profile's SupportedDevices also part of
6773 // available input devices
6774 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006775 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006776 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006777 ALOGV("%s: Input device list is empty! for profile %s",
6778 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006779 continue;
6780 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306781
6782 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6783 && availProfileDevices.areAllDevicesAttached()) {
6784 ALOGV("%s skip opening input for mmap profile %s", __func__,
6785 inProfile->getTagName().c_str());
6786 continue;
6787 }
6788
Eric Laurentc71b11b2024-06-03 12:54:53 +00006789 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6790 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006791
6792 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6793 status_t status = inputDesc->open(nullptr,
6794 availProfileDevices.itemAt(0),
6795 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306796 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006797 &input);
6798 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306799 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6800 __func__, availProfileDevices.toString().c_str(),
6801 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006802 continue;
6803 }
6804 for (const auto &device : availProfileDevices) {
6805 // give a valid ID to an attached device once confirmed it is reachable
6806 if (!device->isAttached()) {
6807 device->attach(hwModule);
6808 device->importAudioPortAndPickAudioProfile(inProfile, true);
6809 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006810 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006811 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6812 }
6813 }
6814 inputDesc->close();
6815 }
6816 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006817
6818 // Check if spatializer outputs can be closed until used.
6819 // mOutputs vector never contains duplicated outputs at this point.
6820 std::vector<audio_io_handle_t> outputsClosed;
6821 for (size_t i = 0; i < mOutputs.size(); i++) {
6822 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6823 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6824 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6825 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006826 nextAudioPortGeneration();
6827 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6828 if (index >= 0) {
6829 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6830 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6831 patchDesc->getAfHandle(), 0);
6832 mAudioPatches.removeItemsAt(index);
6833 mpClientInterface->onAudioPatchListUpdate();
6834 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006835 desc->close();
6836 }
6837 }
6838 for (auto output : outputsClosed) {
6839 removeOutput(output);
6840 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006841}
6842
Eric Laurent98e38192018-02-15 18:31:53 -08006843void AudioPolicyManager::addOutput(audio_io_handle_t output,
6844 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006845{
Eric Laurent1c333e22014-05-20 10:48:17 -07006846 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006847 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006848 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006849 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006850 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006851}
6852
François Gaffie53615e22015-03-19 09:24:12 +01006853void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6854{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006855 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6856 ALOGV("%s: removing primary output", __func__);
6857 mPrimaryOutput = nullptr;
6858 }
François Gaffie53615e22015-03-19 09:24:12 +01006859 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006860 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006861}
6862
Eric Laurent98e38192018-02-15 18:31:53 -08006863void AudioPolicyManager::addInput(audio_io_handle_t input,
6864 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006865{
Eric Laurent1c333e22014-05-20 10:48:17 -07006866 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006867 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006868}
Eric Laurente552edb2014-03-10 17:42:56 -07006869
François Gaffie11d30102018-11-02 16:09:09 +01006870status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006871 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006872 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006873{
François Gaffie11d30102018-11-02 16:09:09 +01006874 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006875 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006876 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006877
François Gaffie11d30102018-11-02 16:09:09 +01006878 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006879 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006880 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006881 }
Eric Laurente552edb2014-03-10 17:42:56 -07006882
Eric Laurent3b73df72014-03-11 09:06:29 -07006883 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006884 // first call getAudioPort to get the supported attributes from the HAL
6885 struct audio_port_v7 port = {};
6886 device->toAudioPort(&port);
6887 status_t status = mpClientInterface->getAudioPort(&port);
6888 if (status == NO_ERROR) {
6889 device->importAudioPort(port);
6890 }
6891
6892 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006893 for (size_t i = 0; i < mOutputs.size(); i++) {
6894 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006895 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006896 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006897 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6898 mOutputs.keyAt(i), device->toString().c_str());
6899 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006900 }
6901 }
6902 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006903 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006904 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006905 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6906 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006907 if (profile->supportsDevice(device)) {
6908 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306909 ALOGV("%s(): adding profile %s from module %s",
6910 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006911 }
6912 }
6913 }
6914
Eric Laurent7b279bb2015-12-14 10:18:23 -08006915 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006916
Eric Laurente552edb2014-03-10 17:42:56 -07006917 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006918 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006919 return BAD_VALUE;
6920 }
6921
6922 // open outputs for matching profiles if needed. Direct outputs are also opened to
6923 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6924 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006925 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006926
6927 // nothing to do if one output is already opened for this profile
6928 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006929 for (j = 0; j < outputs.size(); j++) {
6930 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006931 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006932 // matching profile: save the sample rates, format and channel masks supported
6933 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006934 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006935 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006936 }
Eric Laurente552edb2014-03-10 17:42:56 -07006937 break;
6938 }
6939 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006940 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006941 continue;
6942 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306943 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6944 ALOGV("%s skip opening output for mmap profile %s",
6945 __func__, profile->getTagName().c_str());
6946 continue;
6947 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006948 if (!profile->canOpenNewIo()) {
6949 ALOGW("Max Output number %u already opened for this profile %s",
6950 profile->maxOpenCount, profile->getTagName().c_str());
6951 continue;
6952 }
6953
Eric Laurent83efe1c2017-07-09 16:51:08 -07006954 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006955 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006956 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6957 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006958 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006959 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006960 profiles.removeAt(profile_index);
6961 profile_index--;
6962 } else {
6963 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006964 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006965 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006966 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6967 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006968 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006969 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006970
François Gaffie11d30102018-11-02 16:09:09 +01006971 if (device_distinguishes_on_address(deviceType)) {
6972 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6973 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306974 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6975 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006976 }
Eric Laurente552edb2014-03-10 17:42:56 -07006977 ALOGV("checkOutputsForDevice(): adding output %d", output);
6978 }
6979 }
6980
6981 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006982 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006983 return BAD_VALUE;
6984 }
Eric Laurentd4692962014-05-05 18:13:44 -07006985 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006986 // check if one opened output is not needed any more after disconnecting one device
6987 for (size_t i = 0; i < mOutputs.size(); i++) {
6988 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006989 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006990 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006991 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006992 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006993 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006994 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006995 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6996 mOutputs.keyAt(i));
6997 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006998 }
Eric Laurente552edb2014-03-10 17:42:56 -07006999 }
7000 }
Eric Laurentd4692962014-05-05 18:13:44 -07007001 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007002 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007003 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7004 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007005 if (!profile->supportsDevice(device)) {
7006 continue;
7007 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307008 ALOGV("%s(): clearing direct output profile %s on module %s",
7009 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007010 profile->clearAudioProfiles();
7011 if (!profile->hasDynamicAudioProfile()) {
7012 continue;
7013 }
7014 // When a device is disconnected, if there is an IOProfile that contains dynamic
7015 // profiles and supports the disconnected device, call getAudioPort to repopulate
7016 // the capabilities of the devices that is supported by the IOProfile.
7017 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7018 if (supportedDevice == device ||
7019 !mAvailableOutputDevices.contains(supportedDevice)) {
7020 continue;
7021 }
7022 struct audio_port_v7 port;
7023 supportedDevice->toAudioPort(&port);
7024 status_t status = mpClientInterface->getAudioPort(&port);
7025 if (status == NO_ERROR) {
7026 supportedDevice->importAudioPort(port);
7027 }
Eric Laurente552edb2014-03-10 17:42:56 -07007028 }
7029 }
7030 }
7031 }
7032 return NO_ERROR;
7033}
7034
François Gaffie11d30102018-11-02 16:09:09 +01007035status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007036 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007037{
François Gaffie11d30102018-11-02 16:09:09 +01007038 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007039 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007040 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007041 }
7042
Eric Laurentd4692962014-05-05 18:13:44 -07007043 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007044 sp<AudioInputDescriptor> desc;
7045
jiabinbf5f4262023-04-12 21:48:34 +00007046 // first call getAudioPort to get the supported attributes from the HAL
7047 struct audio_port_v7 port = {};
7048 device->toAudioPort(&port);
7049 status_t status = mpClientInterface->getAudioPort(&port);
7050 if (status == NO_ERROR) {
7051 device->importAudioPort(port);
7052 }
7053
Eric Laurent0dd51852019-04-19 18:18:58 -07007054 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007055 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007056 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007057 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007058 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007059 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007060 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007061
François Gaffie11d30102018-11-02 16:09:09 +01007062 if (profile->supportsDevice(device)) {
7063 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307064 ALOGV("%s : adding profile %s from module %s", __func__,
7065 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007066 }
7067 }
7068 }
7069
Eric Laurent0dd51852019-04-19 18:18:58 -07007070 if (profiles.isEmpty()) {
7071 ALOGW("%s: No input profile available for device %s",
7072 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007073 return BAD_VALUE;
7074 }
7075
7076 // open inputs for matching profiles if needed. Direct inputs are also opened to
7077 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7078 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7079
Eric Laurent1c333e22014-05-20 10:48:17 -07007080 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007081
Eric Laurentd4692962014-05-05 18:13:44 -07007082 // nothing to do if one input is already opened for this profile
7083 size_t input_index;
7084 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7085 desc = mInputs.valueAt(input_index);
7086 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007087 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007088 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007089 }
Eric Laurentd4692962014-05-05 18:13:44 -07007090 break;
7091 }
7092 }
7093 if (input_index != mInputs.size()) {
7094 continue;
7095 }
7096
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307097 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7098 ALOGV("%s skip opening input for mmap profile %s",
7099 __func__, profile->getTagName().c_str());
7100 continue;
7101 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007102 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307103 ALOGW("%s Max Input number %u already opened for this profile %s",
7104 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007105 continue;
7106 }
7107
Eric Laurentc71b11b2024-06-03 12:54:53 +00007108 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007109 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307110 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307111 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7112 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007113
Eric Laurentcf2c0212014-07-25 16:20:43 -07007114 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007115 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007116 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007117 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007118 mpClientInterface->setParameters(input, String8(param));
7119 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007120 }
jiabin12537fc2023-10-12 17:56:08 +00007121 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007122 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307123 ALOGW("%s direct input missing param for profile %s", __func__,
7124 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007125 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007126 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007127 }
7128
Eric Laurent0dd51852019-04-19 18:18:58 -07007129 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007130 addInput(input, desc);
7131 }
7132 } // endif input != 0
7133
Eric Laurentcf2c0212014-07-25 16:20:43 -07007134 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307135 ALOGW("%s could not open input for device %s on profile %s", __func__,
7136 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007137 profiles.removeAt(profile_index);
7138 profile_index--;
7139 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007140 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007141 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007142 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307143 ALOGV("%s: adding input %d for profile %s", __func__,
7144 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007145
7146 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307147 ALOGV("%s: closing input %d for profile %s", __func__,
7148 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007149 closeInput(input);
7150 }
Eric Laurentd4692962014-05-05 18:13:44 -07007151 }
7152 } // end scan profiles
7153
7154 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007155 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007156 return BAD_VALUE;
7157 }
7158 } else {
7159 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007160 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007161 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007162 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007163 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007164 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007165 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007166 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307167 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7168 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007169 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007170 }
7171 }
7172 }
7173 } // end disconnect
7174
7175 return NO_ERROR;
7176}
7177
7178
Eric Laurente0720872014-03-11 09:30:41 -07007179void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007180{
7181 ALOGV("closeOutput(%d)", output);
7182
François Gaffie1c878552018-11-22 16:53:21 +01007183 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7184 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007185 ALOGW("closeOutput() unknown output %d", output);
7186 return;
7187 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007188 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007189 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007190
Eric Laurente552edb2014-03-10 17:42:56 -07007191 // look for duplicated outputs connected to the output being removed.
7192 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007193 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7194 if (dupOutput->isDuplicated() &&
7195 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7196 sp<SwAudioOutputDescriptor> remainingOutput =
7197 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007198 // As all active tracks on duplicated output will be deleted,
7199 // and as they were also referenced on the other output, the reference
7200 // count for their stream type must be adjusted accordingly on
7201 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007202 const bool wasActive = remainingOutput->isActive();
7203 // Note: no-op on the closing output where all clients has already been set inactive
7204 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007205 // stop() will be a no op if the output is still active but is needed in case all
7206 // active streams refcounts where cleared above
7207 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007208 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007209 }
Eric Laurente552edb2014-03-10 17:42:56 -07007210 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7211 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7212
7213 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007214 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007215 }
7216 }
7217
Eric Laurent05b90f82014-08-27 15:32:29 -07007218 nextAudioPortGeneration();
7219
François Gaffie1c878552018-11-22 16:53:21 +01007220 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007221 if (index >= 0) {
7222 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007223 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7224 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007225 mAudioPatches.removeItemsAt(index);
7226 mpClientInterface->onAudioPatchListUpdate();
7227 }
7228
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007229 if (closingOutputWasActive) {
7230 closingOutput->stop();
7231 }
François Gaffie1c878552018-11-22 16:53:21 +01007232 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007233 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007234 for (const auto device : closingOutput->devices()) {
7235 device->setPreferredConfig(nullptr);
7236 }
7237 }
Eric Laurente552edb2014-03-10 17:42:56 -07007238
François Gaffie53615e22015-03-19 09:24:12 +01007239 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007240 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007241 if (closingOutput == mSpatializerOutput) {
7242 mSpatializerOutput.clear();
7243 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007244
7245 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7246 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007247 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007248 bool directOutputOpen = false;
7249 for (size_t i = 0; i < mOutputs.size(); i++) {
7250 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7251 directOutputOpen = true;
7252 break;
7253 }
7254 }
7255 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007256 ALOGV("no direct outputs open, reset MSD patches");
7257 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7258 // how output devices for patching are resolved. Avoid by caching and reusing the
7259 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7260 // devices to patch to. This may be complicated by the fact that devices may become
7261 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007262 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007263 }
7264 }
jiabin220eea12024-05-17 17:55:20 +00007265
7266 if (closingOutput->mPreferredAttrInfo != nullptr) {
7267 closingOutput->mPreferredAttrInfo->resetActiveClient();
7268 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007269}
7270
7271void AudioPolicyManager::closeInput(audio_io_handle_t input)
7272{
7273 ALOGV("closeInput(%d)", input);
7274
7275 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7276 if (inputDesc == NULL) {
7277 ALOGW("closeInput() unknown input %d", input);
7278 return;
7279 }
7280
Eric Laurent6a94d692014-05-20 11:18:06 -07007281 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007282
François Gaffie11d30102018-11-02 16:09:09 +01007283 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007284 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007285 if (index >= 0) {
7286 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007287 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7288 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007289 mAudioPatches.removeItemsAt(index);
7290 mpClientInterface->onAudioPatchListUpdate();
7291 }
7292
François Gaffie6ebbce02023-07-19 13:27:53 +02007293 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007294 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007295 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007296
François Gaffie11d30102018-11-02 16:09:09 +01007297 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7298 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007299 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007300 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007301 }
Eric Laurente552edb2014-03-10 17:42:56 -07007302}
7303
François Gaffie11d30102018-11-02 16:09:09 +01007304SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7305 const DeviceVector &devices,
7306 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007307{
7308 SortedVector<audio_io_handle_t> outputs;
7309
François Gaffie11d30102018-11-02 16:09:09 +01007310 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007311 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007312 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007313 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007314 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007315 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007316 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007317 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007318 outputs.add(openOutputs.keyAt(i));
7319 }
7320 }
7321 return outputs;
7322}
7323
Mikhail Naganov37977152018-07-11 15:54:44 -07007324void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7325{
7326 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7327 // output is suspended before any tracks are moved to it
7328 checkA2dpSuspend();
7329 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007330 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007331 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007332 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007333 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007334 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7335 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7336 // configuration changes will ultimately be rerouted correctly. We can still avoid
7337 // unnecessary rerouting by caching and reusing the arguments to
7338 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7339 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007340 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007341 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007342 // an event that changed routing likely occurred, inform upper layers
7343 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007344}
7345
François Gaffiec005e562018-11-06 15:04:49 +01007346bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7347 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007348{
François Gaffiec005e562018-11-06 15:04:49 +01007349 return mEngine->getProductStrategyForAttributes(lAttr) ==
7350 mEngine->getProductStrategyForAttributes(rAttr);
7351}
7352
Francois Gaffieff1eb522020-05-06 18:37:04 +02007353void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7354{
7355 for (size_t i = 0; i < mAudioSources.size(); i++) {
7356 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7357 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007358 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007359 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007360 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007361 }
7362 }
7363}
7364
7365void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7366{
7367 for (size_t i = 0; i < mAudioSources.size(); i++) {
7368 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7369 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7370 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7371 disconnectAudioSource(sourceDesc);
7372 }
7373 }
7374}
7375
François Gaffiec005e562018-11-06 15:04:49 +01007376void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7377{
7378 auto psId = mEngine->getProductStrategyForAttributes(attr);
7379
7380 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7381 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007382
François Gaffie11d30102018-11-02 16:09:09 +01007383 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7384 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007385
Eric Laurentc209fe42020-06-05 18:11:23 -07007386 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007387 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007388 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007389 // take into account dynamic audio policies related changes: if a client is now associated
7390 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007391 // invalidate clients on outputs that do not support all the newly selected devices for the
7392 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007393 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007394 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007395 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007396 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007397 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007398
Eric Laurentc209fe42020-06-05 18:11:23 -07007399 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7400 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7401 continue;
7402 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007403 if (!desc->supportsAllDevices(newDevices)) {
7404 invalidatedOutputs.push_back(desc);
7405 break;
7406 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007407 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007408 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007409 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7410 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7411 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007412 if (status == OK) {
7413 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7414 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7415 maxLatency = desc->latency();
7416 }
7417 invalidatedOutputs.push_back(desc);
7418 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007419 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007420 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007421 }
7422 }
7423
Eric Laurent56ed8842022-11-15 16:04:41 +01007424 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007425 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7426 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007427 for (audio_io_handle_t srcOut : srcOutputs) {
7428 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007429 if (desc == nullptr) continue;
7430
7431 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007432 maxLatency = desc->latency();
7433 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007434
Eric Laurent56ed8842022-11-15 16:04:41 +01007435 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007436 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007437 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007438 // a client on a non direct outputs has necessarily a linear PCM format
7439 // so we can call selectOutput() safely
7440 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7441 client->flags(),
7442 client->config().format,
7443 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007444 client->config().sample_rate,
7445 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007446 if (newOutput != srcOut) {
7447 invalidate = true;
7448 break;
7449 }
7450 } else {
7451 sp<IOProfile> profile = getProfileForOutput(newDevices,
7452 client->config().sample_rate,
7453 client->config().format,
7454 client->config().channel_mask,
7455 client->flags(),
7456 true /* directOnly */);
7457 if (profile != desc->mProfile) {
7458 invalidate = true;
7459 break;
7460 }
7461 }
7462 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007463 // mute strategy while moving tracks from one output to another
7464 if (invalidate) {
7465 invalidatedOutputs.push_back(desc);
7466 if (desc->isStrategyActive(psId)) {
7467 setStrategyMute(psId, true, desc);
7468 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7469 newDevices.types());
7470 }
Eric Laurente552edb2014-03-10 17:42:56 -07007471 }
François Gaffiec005e562018-11-06 15:04:49 +01007472 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007473 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007474 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007475 }
Eric Laurente552edb2014-03-10 17:42:56 -07007476 }
7477
Eric Laurent56ed8842022-11-15 16:04:41 +01007478 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7479 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7480 std::to_string(srcOutputs[0]).c_str(),
7481 std::to_string(dstOutputs[0]).c_str());
7482
François Gaffiec005e562018-11-06 15:04:49 +01007483 // Move effects associated to this stream from previous output to new output
7484 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007485 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007486 }
François Gaffiec005e562018-11-06 15:04:49 +01007487 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007488 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007489 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007490 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007491 desc->setTracksInvalidatedStatusByStrategy(psId);
7492 }
Eric Laurente552edb2014-03-10 17:42:56 -07007493 }
7494 }
7495}
7496
Eric Laurente0720872014-03-11 09:30:41 -07007497void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007498{
François Gaffiec005e562018-11-06 15:04:49 +01007499 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7500 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7501 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007502 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007503 }
Eric Laurente552edb2014-03-10 17:42:56 -07007504}
7505
Kevin Rocard153f92d2018-12-18 18:33:28 -08007506void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007507 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007508 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007509 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007510 for (size_t i = 0; i < mOutputs.size(); i++) {
7511 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7512 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007513 sp<AudioPolicyMix> primaryMix;
7514 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007515 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007516 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7517 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7518 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007519 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7520 for (auto &secondaryMix : secondaryMixes) {
7521 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7522 if (outputDesc != nullptr &&
7523 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7524 secondaryDescs.push_back(outputDesc);
7525 }
7526 }
7527
jiabinc44b3462022-12-08 12:52:31 -08007528 if (status != OK &&
7529 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7530 // When it failed to query secondary output, only invalidate the client that is not
7531 // MMAP. The reason is that MMAP stream will not support secondary output.
7532 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007533 } else if (!std::equal(
7534 client->getSecondaryOutputs().begin(),
7535 client->getSecondaryOutputs().end(),
7536 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007537 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7538 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007539 // If the format is not PCM, the tracks should be invalidated to get correct
7540 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007541 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007542 } else {
7543 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7544 std::vector<audio_io_handle_t> secondaryOutputIds;
7545 for (const auto &secondaryDesc: secondaryDescs) {
7546 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7547 weakSecondaryDescs.push_back(secondaryDesc);
7548 }
7549 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7550 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007551 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007552 }
7553 }
7554 }
jiabin10a03f12021-05-07 23:46:28 +00007555 if (!trackSecondaryOutputs.empty()) {
7556 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7557 }
jiabinc44b3462022-12-08 12:52:31 -08007558 if (!clientsToInvalidate.empty()) {
7559 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7560 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007561 }
7562}
7563
Eric Laurent2517af32020-11-25 15:31:27 +01007564bool AudioPolicyManager::isScoRequestedForComm() const {
7565 AudioDeviceTypeAddrVector devices;
7566 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7567 for (const auto &device : devices) {
7568 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7569 return true;
7570 }
7571 }
7572 return false;
7573}
7574
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007575bool AudioPolicyManager::isHearingAidUsedForComm() const {
7576 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7577 true /*fromCache*/);
7578 for (const auto &device : devices) {
7579 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7580 return true;
7581 }
7582 }
7583 return false;
7584}
7585
7586
Eric Laurente0720872014-03-11 09:30:41 -07007587void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007588{
François Gaffie53615e22015-03-19 09:24:12 +01007589 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007590 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007591 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007592 return;
7593 }
7594
Eric Laurent3a4311c2014-03-17 12:00:47 -07007595 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007596 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7597 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007598 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007599
7600 // if suspended, restore A2DP output if:
7601 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007602 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007603 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007604 //
Eric Laurentf732e072016-08-03 19:30:28 -07007605 // if not suspended, suspend A2DP output if:
7606 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007607 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007608 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007609 //
7610 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007611 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007612 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007613 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007614 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007615
7616 mpClientInterface->restoreOutput(a2dpOutput);
7617 mA2dpSuspended = false;
7618 }
7619 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007620 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007621 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007622 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007623 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007624
7625 mpClientInterface->suspendOutput(a2dpOutput);
7626 mA2dpSuspended = true;
7627 }
7628 }
7629}
7630
François Gaffie11d30102018-11-02 16:09:09 +01007631DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7632 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007633{
François Gaffiedb1755b2023-09-01 11:50:35 +02007634 if (outputDesc == nullptr) {
7635 return DeviceVector{};
7636 }
François Gaffie11d30102018-11-02 16:09:09 +01007637
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007638 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007639 if (index >= 0) {
7640 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007641 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007642 ALOGV("%s device %s forced by patch %d", __func__,
7643 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7644 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007645 }
7646 }
7647
Dean Wheatley514b4312020-06-17 21:45:00 +10007648 // Do not retrieve engine device for outputs through MSD
7649 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7650 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7651 return outputDesc->devices();
7652 }
7653
Eric Laurent97ac8712018-07-27 18:59:02 -07007654 // Honor explicit routing requests only if no client using default routing is active on this
7655 // input: a specific app can not force routing for other apps by setting a preferred device.
7656 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007657 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007658 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007659 if (device != nullptr) {
7660 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007661 }
7662
François Gaffiea807ef92018-11-05 10:44:33 +01007663 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7664 // of setForceUse / Default Bus device here
7665 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7666 if (device != nullptr) {
7667 return DeviceVector(device);
7668 }
7669
François Gaffiedb1755b2023-09-01 11:50:35 +02007670 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007671 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7672 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307673 auto hasStreamActive = [&](auto stream) {
7674 return hasStream(streams, stream) && isStreamActive(stream, 0);
7675 };
Eric Laurent484e9272018-06-07 17:29:23 -07007676
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307677 auto doGetOutputDevicesForVoice = [&]() {
7678 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007679 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307680 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007681 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7682 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307683 };
7684
7685 // With low-latency playing on speaker, music on WFD, when the first low-latency
7686 // output is stopped, getNewOutputDevices checks for a product strategy
7687 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007688 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307689 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7690 // stream is associated to the output descriptor.
7691 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7692 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7693 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7694 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007695 // Retrieval of devices for voice DL is done on primary output profile, cannot
7696 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007697 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007698 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7699 break;
7700 }
Eric Laurente552edb2014-03-10 17:42:56 -07007701 }
François Gaffiec005e562018-11-06 15:04:49 +01007702 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007703 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007704}
7705
François Gaffie11d30102018-11-02 16:09:09 +01007706sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7707 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007708{
François Gaffie11d30102018-11-02 16:09:09 +01007709 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007710
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007711 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007712 if (index >= 0) {
7713 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007714 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007715 ALOGV("getNewInputDevice() device %s forced by patch %d",
7716 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7717 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007718 }
7719 }
7720
Eric Laurent97ac8712018-07-27 18:59:02 -07007721 // Honor explicit routing requests only if no client using default routing is active on this
7722 // input: a specific app can not force routing for other apps by setting a preferred device.
7723 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007724 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7725 if (device != nullptr) {
7726 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007727 }
7728
Eric Laurentdc95a252018-04-12 12:46:56 -07007729 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007730 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007731 audio_attributes_t attributes;
7732 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007733 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007734 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7735 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007736 attributes = topClient->attributes();
7737 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007738 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007739 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007740 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7741 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007742 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007743 }
7744
Francois Gaffie716e1432019-01-14 16:58:59 +01007745 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7746 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007747 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007748 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007749 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007750 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007751
Eric Laurente552edb2014-03-10 17:42:56 -07007752 return device;
7753}
7754
Eric Laurent794fde22016-03-11 09:50:45 -08007755bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7756 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007757 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007758}
7759
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007760status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007761 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007762 if (devices == nullptr) {
7763 return BAD_VALUE;
7764 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007765
Andy Hung6d23c0f2022-02-16 09:37:15 -08007766 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007767 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7768 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007769 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007770 for (const auto& device : curDevices) {
7771 devices->push_back(device->getDeviceTypeAddr());
7772 }
7773 return NO_ERROR;
7774}
7775
Eric Laurente0720872014-03-11 09:30:41 -07007776void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007777 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007778 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007779 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007780 updateDevicesAndOutputs();
7781 break;
7782 default:
7783 break;
7784 }
7785}
7786
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007787uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007788
7789 // skip beacon mute management if a dedicated TTS output is available
7790 if (mTtsOutputAvailable) {
7791 return 0;
7792 }
7793
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007794 switch(event) {
7795 case STARTING_OUTPUT:
7796 mBeaconMuteRefCount++;
7797 break;
7798 case STOPPING_OUTPUT:
7799 if (mBeaconMuteRefCount > 0) {
7800 mBeaconMuteRefCount--;
7801 }
7802 break;
7803 case STARTING_BEACON:
7804 mBeaconPlayingRefCount++;
7805 break;
7806 case STOPPING_BEACON:
7807 if (mBeaconPlayingRefCount > 0) {
7808 mBeaconPlayingRefCount--;
7809 }
7810 break;
7811 }
7812
7813 if (mBeaconMuteRefCount > 0) {
7814 // any playback causes beacon to be muted
7815 return setBeaconMute(true);
7816 } else {
7817 // no other playback: unmute when beacon starts playing, mute when it stops
7818 return setBeaconMute(mBeaconPlayingRefCount == 0);
7819 }
7820}
7821
7822uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7823 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7824 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7825 // keep track of muted state to avoid repeating mute/unmute operations
7826 if (mBeaconMuted != mute) {
7827 // mute/unmute AUDIO_STREAM_TTS on all outputs
7828 ALOGV("\t muting %d", mute);
7829 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007830 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7831 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7832 ALOGV("\t no tts volume source available");
7833 return 0;
7834 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007835 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007836 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007837 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007838 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007839 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007840 maxLatency = latency;
7841 }
7842 }
7843 mBeaconMuted = mute;
7844 return maxLatency;
7845 }
7846 return 0;
7847}
7848
Eric Laurente0720872014-03-11 09:30:41 -07007849void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007850{
François Gaffiec005e562018-11-06 15:04:49 +01007851 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007852 mPreviousOutputs = mOutputs;
7853}
7854
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007855uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007856 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007857 uint32_t delayMs)
7858{
7859 // mute/unmute strategies using an incompatible device combination
7860 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7861 // if unmuting, unmute only after the specified delay
7862 if (outputDesc->isDuplicated()) {
7863 return 0;
7864 }
7865
7866 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007867 DeviceVector devices = outputDesc->devices();
7868 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007869
François Gaffiec005e562018-11-06 15:04:49 +01007870 auto productStrategies = mEngine->getOrderedProductStrategies();
7871 for (const auto &productStrategy : productStrategies) {
7872 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7873 DeviceVector curDevices =
7874 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7875 curDevices = curDevices.filter(outputDesc->supportedDevices());
7876 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007877 bool doMute = false;
7878
François Gaffiec005e562018-11-06 15:04:49 +01007879 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007880 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007881 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7882 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007883 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007884 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007885 }
Eric Laurent99401132014-05-07 19:48:15 -07007886 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007887 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007888 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007889 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007890 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007891 continue;
7892 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307893 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007894 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7895 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7896 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007897 if (mute) {
7898 // FIXME: should not need to double latency if volume could be applied
7899 // immediately by the audioflinger mixer. We must account for the delay
7900 // between now and the next time the audioflinger thread for this output
7901 // will process a buffer (which corresponds to one buffer size,
7902 // usually 1/2 or 1/4 of the latency).
7903 if (muteWaitMs < desc->latency() * 2) {
7904 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007905 }
7906 }
7907 }
7908 }
7909 }
7910 }
7911
Eric Laurent99401132014-05-07 19:48:15 -07007912 // temporary mute output if device selection changes to avoid volume bursts due to
7913 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007914 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007915 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007916
Eric Laurentdc462862016-07-19 12:29:53 -07007917 if (muteWaitMs < tempMuteWaitMs) {
7918 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007919 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007920
7921 // If recommended duration is defined, replace temporary mute duration to avoid
7922 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7923 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7924 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7925 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7926 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7927
François Gaffieaaac0fd2018-11-22 17:56:39 +01007928 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7929 // make sure that we do not start the temporary mute period too early in case of
7930 // delayed device change
7931 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7932 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007933 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007934 }
7935 }
7936
Eric Laurente552edb2014-03-10 17:42:56 -07007937 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7938 if (muteWaitMs > delayMs) {
7939 muteWaitMs -= delayMs;
7940 usleep(muteWaitMs * 1000);
7941 return muteWaitMs;
7942 }
7943 return 0;
7944}
7945
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307946uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7947 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007948 const DeviceVector &devices,
7949 bool force,
7950 int delayMs,
7951 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007952 bool requiresMuteCheck, bool requiresVolumeCheck,
7953 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007954{
jiabin3ff8d7d2022-12-13 06:27:44 +00007955 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307956 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7957 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7958 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007959 uint32_t muteWaitMs;
7960
7961 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307962 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007963 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307964 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007965 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007966 return muteWaitMs;
7967 }
Eric Laurente552edb2014-03-10 17:42:56 -07007968
7969 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007970 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007971 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007972 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007973
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307974 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7975 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007976
7977 if (!filteredDevices.isEmpty()) {
7978 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007979 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007980
7981 // if the outputs are not materially active, there is no need to mute.
7982 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007983 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007984 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307985 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7986 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007987 muteWaitMs = 0;
7988 }
Eric Laurente552edb2014-03-10 17:42:56 -07007989
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007990 bool outputRouted = outputDesc->isRouted();
7991
Eric Laurent79ea9582020-06-11 18:49:24 -07007992 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7993 // output profile or if new device is not supported AND previous device(s) is(are) still
7994 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007995 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307996 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7997 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007998 // restore previous device after evaluating strategy mute state
7999 outputDesc->setDevices(prevDevices);
8000 return muteWaitMs;
8001 }
8002
Eric Laurente552edb2014-03-10 17:42:56 -07008003 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008004 // the requested device is AUDIO_DEVICE_NONE
8005 // OR the requested device is the same as current device
8006 // AND force is not specified
8007 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008008 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008009 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308010 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8011 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8012 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008013 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308014 ALOGV("%s %s setting same device on routed output, force apply volumes",
8015 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008016 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8017 }
Eric Laurente552edb2014-03-10 17:42:56 -07008018 return muteWaitMs;
8019 }
8020
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308021 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8022 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008023
Eric Laurente552edb2014-03-10 17:42:56 -07008024 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008025 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008026 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008027 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008028 PatchBuilder patchBuilder;
8029 patchBuilder.addSource(outputDesc);
8030 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8031 for (const auto &filteredDevice : filteredDevices) {
8032 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008033 }
8034
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008035 // Add half reported latency to delayMs when muteWaitMs is null in order
8036 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008037 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8038 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8039 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008040 }
Eric Laurente552edb2014-03-10 17:42:56 -07008041
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008042 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8043 if (!skipMuteDelay) {
8044 // update stream volumes according to new device
8045 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8046 }
Eric Laurente552edb2014-03-10 17:42:56 -07008047
8048 return muteWaitMs;
8049}
8050
Eric Laurentc75307b2015-03-17 15:29:32 -07008051status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008052 int delayMs,
8053 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008054{
Eric Laurent6a94d692014-05-20 11:18:06 -07008055 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008056 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8057 return INVALID_OPERATION;
8058 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008059 if (patchHandle) {
8060 index = mAudioPatches.indexOfKey(*patchHandle);
8061 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008062 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008063 }
8064 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008065 return INVALID_OPERATION;
8066 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008067 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008068 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008069 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008070 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008071 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008072 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008073 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008074 return status;
8075}
8076
8077status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008078 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008079 bool force,
8080 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008081{
8082 status_t status = NO_ERROR;
8083
Eric Laurent1f2f2232014-06-02 12:01:23 -07008084 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008085 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8086 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008087
François Gaffie11d30102018-11-02 16:09:09 +01008088 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008089 PatchBuilder patchBuilder;
8090 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008091 // AUDIO_SOURCE_HOTWORD is for internal use only:
8092 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008093 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8094 auto result = usecase;
8095 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8096 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8097 }
8098 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008099 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008100 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008101 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008102 }
8103 }
8104 return status;
8105}
8106
Eric Laurent6a94d692014-05-20 11:18:06 -07008107status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8108 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008109{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008110 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008111 ssize_t index;
8112 if (patchHandle) {
8113 index = mAudioPatches.indexOfKey(*patchHandle);
8114 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008115 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008116 }
8117 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008118 return INVALID_OPERATION;
8119 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008120 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008121 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008122 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008123 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008124 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008125 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008126 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008127 return status;
8128}
8129
François Gaffie11d30102018-11-02 16:09:09 +01008130sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008131 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008132 audio_format_t& format,
8133 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008134 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008135{
8136 // Choose an input profile based on the requested capture parameters: select the first available
8137 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008138 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008139
Atneya Nair0f0a8032022-12-12 16:20:12 -08008140 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8141 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8142 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8143
8144 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008145
jiabin2fd710d2022-05-02 23:20:22 +00008146 for (;;) {
8147 sp<IOProfile> firstInexact = nullptr;
8148 uint32_t updatedSamplingRate = 0;
8149 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8150 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8151 for (const auto& hwModule : mHwModules) {
8152 for (const auto& profile : hwModule->getInputProfiles()) {
8153 // profile->log();
8154 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008155 if (profile->getCompatibilityScore(
8156 DeviceVector(device),
8157 samplingRate,
8158 &updatedSamplingRate,
8159 format,
8160 &updatedFormat,
8161 channelMask,
8162 &updatedChannelMask,
8163 // FIXME ugly cast
8164 (audio_output_flags_t) flags,
8165 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8166 samplingRate = updatedSamplingRate;
8167 format = updatedFormat;
8168 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008169 return profile;
8170 }
jiabin66acc432024-02-06 00:57:36 +00008171 if (firstInexact == nullptr
8172 && profile->getCompatibilityScore(
8173 DeviceVector(device),
8174 samplingRate,
8175 &updatedSamplingRate,
8176 format,
8177 &updatedFormat,
8178 channelMask,
8179 &updatedChannelMask,
8180 // FIXME ugly cast
8181 (audio_output_flags_t) flags,
8182 false /*exactMatchRequiredForInputFlags*/)
8183 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008184 firstInexact = profile;
8185 }
8186 }
8187 }
8188
8189 if (firstInexact != nullptr) {
8190 samplingRate = updatedSamplingRate;
8191 format = updatedFormat;
8192 channelMask = updatedChannelMask;
8193 return firstInexact;
8194 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8195 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8196 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8197 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8198 flags = AUDIO_INPUT_FLAG_NONE;
8199 } else { // fail
8200 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8201 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8202 samplingRate, format, channelMask, oriFlags);
8203 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008204 }
8205 }
jiabin2fd710d2022-05-02 23:20:22 +00008206
8207 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008208}
8209
Vlad Popa87e0e582024-05-20 18:49:20 -07008210float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8211 VolumeSource volumeSource,
8212 int index,
8213 const DeviceTypeSet &deviceTypes)
8214{
8215 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8216 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8217 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8218
8219 if (com_android_media_audio_abs_volume_index_fix()) {
8220 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8221 mAbsoluteVolumeDrivingStreams.end()) {
8222 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8223 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8224 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8225 ALOGD("%s: no group matching with %s", __FUNCTION__,
8226 toString(attributesToDriveAbs).c_str());
8227 return volumeDb;
8228 }
8229
8230 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8231 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8232 if (vsToDriveAbs == volumeSource) {
8233 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008234 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008235 } else {
8236 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8237 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8238 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8239 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8240 curvesAbs.getVolumeIndexMax());
8241 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8242 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8243 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8244 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8245 return newVolumeDb;
8246 }
8247 }
8248 return volumeDb;
8249 } else {
8250 return volumeDb;
8251 }
8252}
8253
François Gaffieaaac0fd2018-11-22 17:56:39 +01008254float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8255 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008256 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008257 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008258 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008259 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008260{
Vlad Popa9d482762024-06-21 16:40:23 -07008261 float volumeDb;
8262 if (adjustAttenuation) {
8263 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8264 } else {
8265 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8266 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008267 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8268 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8269
8270 if (!computeInternalInteraction) {
8271 return volumeDb;
8272 }
8273
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008274 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8275 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8276 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8277 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008278 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8279 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8280 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8281 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8282 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008283 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008284 mOutputs.isActive(ringVolumeSrc, 0)) {
8285 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008286 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008287 adjustAttenuation,
8288 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008289 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008290 }
8291
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008292 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008293 if ((volumeSource != callVolumeSrc && (isInCall() ||
8294 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008295 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008296 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8297 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008298 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8299 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8300 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008301 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008302 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008303 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008304 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008305 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008306 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008307 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008308 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8309 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8310 // programmatically muted.
8311 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8312 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8313 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008314 bool exemptFromCapping =
8315 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8316 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008317 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8318 volumeSource, volumeDb);
8319 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008320 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8321 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8322 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008323 }
8324 }
Eric Laurente552edb2014-03-10 17:42:56 -07008325 // if a headset is connected, apply the following rules to ring tones and notifications
8326 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008327 // - always attenuate notifications volume by 6dB
8328 // - attenuate ring tones volume by 6dB unless music is not playing and
8329 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008330 // - if music is playing, always limit the volume to current music volume,
8331 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008332 if (!Intersection(deviceTypes,
8333 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8334 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008335 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8336 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008337 ((volumeSource == alarmVolumeSrc ||
8338 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008339 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8340 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8341 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008342 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8343 curves.canBeMuted()) {
8344
Eric Laurente552edb2014-03-10 17:42:56 -07008345 // when the phone is ringing we must consider that music could have been paused just before
8346 // by the music application and behave as if music was active if the last music track was
8347 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008348 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8349 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008350 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008351 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008352 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8353 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008354 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008355 float musicVolDb = computeVolume(musicCurves,
8356 musicVolumeSrc,
8357 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008358 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008359 adjustAttenuation,
8360 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008361 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8362 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8363 if (volumeDb > minVolDb) {
8364 volumeDb = minVolDb;
8365 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008366 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008367 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8368 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008369 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8370 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8371 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8372 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008373 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008374 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008375 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8376 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008377 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8378 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008379 }
8380 }
jiabin9a3361e2019-10-01 09:38:30 -07008381 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008382 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008383 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008384 }
8385 }
8386
François Gaffie43c73442018-11-08 08:21:55 +01008387 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008388}
8389
Eric Laurent3839bc02018-07-10 18:33:34 -07008390int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008391 VolumeSource fromVolumeSource,
8392 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008393{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008394 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008395 return srcIndex;
8396 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008397 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8398 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008399 float minSrc = (float)srcCurves.getVolumeIndexMin();
8400 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8401 float minDst = (float)dstCurves.getVolumeIndexMin();
8402 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008403
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008404 // preserve mute request or correct range
8405 if (srcIndex < minSrc) {
8406 if (srcIndex == 0) {
8407 return 0;
8408 }
8409 srcIndex = minSrc;
8410 } else if (srcIndex > maxSrc) {
8411 srcIndex = maxSrc;
8412 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008413 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8414}
8415
François Gaffieaaac0fd2018-11-22 17:56:39 +01008416status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8417 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008418 int index,
8419 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008420 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008421 int delayMs,
8422 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008423{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008424 // do not change actual attributes volume if the attributes is muted
8425 if (outputDesc->isMuted(volumeSource)) {
8426 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8427 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008428 return NO_ERROR;
8429 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008430
Eric Laurentae6e88c2024-01-10 14:42:57 +01008431 bool isVoiceVolSrc;
8432 bool isBtScoVolSrc;
8433 if (!isVolumeConsistentForCalls(
8434 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008435 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008436 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008437 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008438 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008439
jiabin9a3361e2019-10-01 09:38:30 -07008440 if (deviceTypes.empty()) {
8441 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008442 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008443 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008444 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008445 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008446
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008447 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8448 ALOGE("invalid volume index range");
8449 return BAD_VALUE;
8450 }
8451
jiabin9a3361e2019-10-01 09:38:30 -07008452 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8453 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008454 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008455 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008456 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8457 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008458 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008459 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008460 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008461 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8462 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008463
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008464 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008465 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8466 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8467 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008468 }
Eric Laurente552edb2014-03-10 17:42:56 -07008469 return NO_ERROR;
8470}
8471
Eric Laurentae6e88c2024-01-10 14:42:57 +01008472void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008473 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008474 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008475 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008476 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008477 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008478 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8479 } else {
8480 voiceVolume = index == 0 ? 0.0 : 1.0;
8481 }
8482 if (voiceVolume != mLastVoiceVolume) {
8483 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8484 mLastVoiceVolume = voiceVolume;
8485 }
8486}
8487
8488bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8489 const DeviceTypeSet& deviceTypes,
8490 bool& isVoiceVolSrc,
8491 bool& isBtScoVolSrc,
8492 const char* caller) {
8493 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008494 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8495
Eric Laurentae6e88c2024-01-10 14:42:57 +01008496 const bool isScoRequested = isScoRequestedForComm();
8497 const bool isHAUsed = isHearingAidUsedForComm();
8498
Vlad Popa695b76b2024-06-14 16:49:25 -07008499 if (com_android_media_audio_replace_stream_bt_sco()) {
8500 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8501 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8502 (isScoRequested || isHAUsed);
8503 return true;
8504 }
8505
8506 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008507 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8508
8509 if ((callVolSrc != btScoVolSrc) &&
8510 ((isVoiceVolSrc && isScoRequested) ||
8511 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8512 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8513 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8514 volumeSource, isScoRequested ? " " : " not ");
8515 return false;
8516 }
8517 return true;
8518}
8519
Eric Laurentc75307b2015-03-17 15:29:32 -07008520void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008521 const DeviceTypeSet& deviceTypes,
8522 int delayMs,
8523 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008524{
jiabincd510522020-01-22 09:40:55 -08008525 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008526 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8527 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8528 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008529 curves.getVolumeIndex(deviceTypes),
8530 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008531 }
8532}
8533
François Gaffiec005e562018-11-06 15:04:49 +01008534void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8535 bool on,
8536 const sp<AudioOutputDescriptor>& outputDesc,
8537 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008538 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008539{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008540 std::vector<VolumeSource> sourcesToMute;
8541 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8542 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8543 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008544 VolumeSource source = toVolumeSource(attributes, false);
8545 if ((source != VOLUME_SOURCE_NONE) &&
8546 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8547 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008548 sourcesToMute.push_back(source);
8549 }
Eric Laurente552edb2014-03-10 17:42:56 -07008550 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008551 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008552 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008553 }
8554
Eric Laurente552edb2014-03-10 17:42:56 -07008555}
8556
François Gaffieaaac0fd2018-11-22 17:56:39 +01008557void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8558 bool on,
8559 const sp<AudioOutputDescriptor>& outputDesc,
8560 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008561 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008562{
jiabin9a3361e2019-10-01 09:38:30 -07008563 if (deviceTypes.empty()) {
8564 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008565 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008566 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008567 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008568 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008569 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008570 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008571 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8572 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008573 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008574 }
8575 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008576 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8577 // ignored
8578 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008579 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008580 if (!outputDesc->isMuted(volumeSource)) {
8581 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008582 return;
8583 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008584 if (outputDesc->decMuteCount(volumeSource) == 0) {
8585 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008586 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008587 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008588 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008589 delayMs);
8590 }
8591 }
8592}
8593
François Gaffie53615e22015-03-19 09:24:12 +01008594bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8595{
François Gaffiec005e562018-11-06 15:04:49 +01008596 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008597 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8598 return true;
8599 }
8600
8601 // has known usage?
8602 switch (paa->usage) {
8603 case AUDIO_USAGE_UNKNOWN:
8604 case AUDIO_USAGE_MEDIA:
8605 case AUDIO_USAGE_VOICE_COMMUNICATION:
8606 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8607 case AUDIO_USAGE_ALARM:
8608 case AUDIO_USAGE_NOTIFICATION:
8609 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8610 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8611 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8612 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8613 case AUDIO_USAGE_NOTIFICATION_EVENT:
8614 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8615 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8616 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8617 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008618 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008619 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008620 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008621 case AUDIO_USAGE_EMERGENCY:
8622 case AUDIO_USAGE_SAFETY:
8623 case AUDIO_USAGE_VEHICLE_STATUS:
8624 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008625 break;
8626 default:
8627 return false;
8628 }
8629 return true;
8630}
8631
François Gaffie2110e042015-03-24 08:41:51 +01008632audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8633{
8634 return mEngine->getForceUse(usage);
8635}
8636
Eric Laurent96d1dda2022-03-14 17:14:19 +01008637bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008638 return isStateInCall(mEngine->getPhoneState());
8639}
8640
Eric Laurent96d1dda2022-03-14 17:14:19 +01008641bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008642 return is_state_in_call(state);
8643}
8644
Eric Laurentf9cccec2022-11-16 19:12:00 +01008645bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008646 audio_mode_t mode = mEngine->getPhoneState();
8647 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008648 || (mode == AUDIO_MODE_CALL_SCREEN)
8649 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008650}
8651
Eric Laurentf9cccec2022-11-16 19:12:00 +01008652bool AudioPolicyManager::isInCallOrScreening() const {
8653 audio_mode_t mode = mEngine->getPhoneState();
8654 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8655}
8656
Eric Laurentd60560a2015-04-10 11:31:20 -07008657void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8658{
8659 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008660 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008661 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008662 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008663 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008664 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008665 }
8666 }
8667
8668 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8669 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8670 bool release = false;
8671 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8672 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8673 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8674 source->ext.device.type == deviceDesc->type()) {
8675 release = true;
8676 }
8677 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008678 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008679 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8680 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8681 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008682 sink->ext.device.type == deviceDesc->type() &&
8683 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8684 || strncmp(sink->ext.device.address, address,
8685 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008686 release = true;
8687 }
8688 }
8689 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008690 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8691 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008692 }
8693 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008694
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008695 mInputs.clearSessionRoutesForDevice(deviceDesc);
8696
Francois Gaffie716e1432019-01-14 16:58:59 +01008697 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008698}
8699
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008700void AudioPolicyManager::modifySurroundFormats(
8701 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008702 std::unordered_set<audio_format_t> enforcedSurround(
8703 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008704 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008705 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008706 allSurround.insert(pair.first);
8707 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8708 }
Phil Burk09bc4612016-02-24 15:58:15 -08008709
8710 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8711 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008712 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008713 // This is the resulting set of formats depending on the surround mode:
8714 // 'all surround' = allSurround
8715 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8716 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8717 // 'manual surround' = mManualSurroundFormats
8718 // AUTO: formats v 'enforced surround'
8719 // ALWAYS: formats v 'all surround' v 'enforced surround'
8720 // NEVER: formats ^ 'non-surround'
8721 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008722
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008723 std::unordered_set<audio_format_t> formatSet;
8724 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8725 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008726 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008727 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008728 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008729 formatSet.insert(*formatIter);
8730 }
8731 }
8732 } else {
8733 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8734 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008735 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008736
jiabin81772902018-04-02 17:52:27 -07008737 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008738 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008739 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8740 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8741 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008742 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008743 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8744 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8745 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008746 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008747 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008748 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008749 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008750 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008751 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008752}
8753
jiabin06e4bab2019-07-29 10:13:34 -07008754void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8755 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008756 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8757 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8758
8759 // If NEVER, then remove support for channelMasks > stereo.
8760 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008761 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8762 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008763 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008764 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008765 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008766 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008767 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008768 }
8769 }
jiabin81772902018-04-02 17:52:27 -07008770 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8771 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8772 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008773 bool supports5dot1 = false;
8774 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008775 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008776 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8777 supports5dot1 = true;
8778 break;
8779 }
8780 }
8781 // If not then add 5.1 support.
8782 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008783 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008784 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008785 }
Phil Burk09bc4612016-02-24 15:58:15 -08008786 }
8787}
8788
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008789void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008790 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008791 const sp<IOProfile>& profile) {
8792 if (!profile->hasDynamicAudioProfile()) {
8793 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008794 }
François Gaffie112b0af2015-11-19 16:13:25 +01008795
jiabin12537fc2023-10-12 17:56:08 +00008796 audio_port_v7 devicePort;
8797 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008798
jiabin12537fc2023-10-12 17:56:08 +00008799 audio_port_v7 mixPort;
8800 profile->toAudioPort(&mixPort);
8801 mixPort.ext.mix.handle = ioHandle;
8802
8803 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8804 if (status != NO_ERROR) {
8805 ALOGE("%s failed to query the attributes of the mix port", __func__);
8806 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008807 }
jiabin12537fc2023-10-12 17:56:08 +00008808
8809 std::set<audio_format_t> supportedFormats;
8810 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8811 supportedFormats.insert(mixPort.audio_profiles[i].format);
8812 }
8813 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8814 mReportedFormatsMap[devDesc] = formats;
8815
8816 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8817 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8818 modifySurroundFormats(devDesc, &formats);
8819 size_t modifiedNumProfiles = 0;
8820 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8821 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8822 formats.end()) {
8823 // Skip the format that is not present after modifying surround formats.
8824 continue;
8825 }
8826 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8827 sizeof(struct audio_profile));
8828 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8829 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8830 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8831 modifySurroundChannelMasks(&channels);
8832 std::copy(channels.begin(), channels.end(),
8833 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8834 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8835 }
8836 mixPort.num_audio_profiles = modifiedNumProfiles;
8837 }
8838 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008839}
Eric Laurentd60560a2015-04-10 11:31:20 -07008840
Mikhail Naganovdc769682018-05-04 15:34:08 -07008841status_t AudioPolicyManager::installPatch(const char *caller,
8842 audio_patch_handle_t *patchHandle,
8843 AudioIODescriptorInterface *ioDescriptor,
8844 const struct audio_patch *patch,
8845 int delayMs)
8846{
8847 ssize_t index = mAudioPatches.indexOfKey(
8848 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8849 *patchHandle : ioDescriptor->getPatchHandle());
8850 sp<AudioPatch> patchDesc;
8851 status_t status = installPatch(
8852 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8853 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008854 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008855 }
8856 return status;
8857}
8858
8859status_t AudioPolicyManager::installPatch(const char *caller,
8860 ssize_t index,
8861 audio_patch_handle_t *patchHandle,
8862 const struct audio_patch *patch,
8863 int delayMs,
8864 uid_t uid,
8865 sp<AudioPatch> *patchDescPtr)
8866{
8867 sp<AudioPatch> patchDesc;
8868 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8869 if (index >= 0) {
8870 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008871 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008872 }
8873
8874 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8875 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8876 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8877 if (status == NO_ERROR) {
8878 if (index < 0) {
8879 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008880 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008881 } else {
8882 patchDesc->mPatch = *patch;
8883 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008884 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008885 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008886 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008887 }
8888 nextAudioPortGeneration();
8889 mpClientInterface->onAudioPatchListUpdate();
8890 }
8891 if (patchDescPtr) *patchDescPtr = patchDesc;
8892 return status;
8893}
8894
jiabinbce0c1d2020-10-05 11:20:18 -07008895bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8896{
8897 const TrackClientVector activeClients = output->getActiveClients();
8898 if (activeClients.empty()) {
8899 return true;
8900 }
8901 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8902 if (index < 0) {
8903 ALOGE("%s, no audio patch found while there are active clients on output %d",
8904 __func__, output->getId());
8905 return false;
8906 }
8907 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8908 DeviceVector routedDevices;
8909 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8910 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8911 patchDesc->mPatch.sinks[i].id);
8912 if (device == nullptr) {
8913 ALOGE("%s, no audio device found with id(%d)",
8914 __func__, patchDesc->mPatch.sinks[i].id);
8915 return false;
8916 }
8917 routedDevices.add(device);
8918 }
8919 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008920 if (client->isInvalid()) {
8921 // No need to take care about invalidated clients.
8922 continue;
8923 }
jiabinbce0c1d2020-10-05 11:20:18 -07008924 sp<DeviceDescriptor> preferredDevice =
8925 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8926 if (mEngine->getOutputDevicesForAttributes(
8927 client->attributes(), preferredDevice, false) == routedDevices) {
8928 return false;
8929 }
8930 }
8931 return true;
8932}
8933
8934sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008935 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008936 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8937 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008938{
8939 for (const auto& device : devices) {
8940 // TODO: This should be checking if the profile supports the device combo.
8941 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008942 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8943 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008944 return nullptr;
8945 }
8946 }
8947 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8948 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07008949 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008950 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07008951 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008952 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008953 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008954 return nullptr;
8955 }
jiabin14b50cc2023-12-13 19:01:52 +00008956 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8957 auto portConfig = desc->getConfig();
8958 for (const auto& device : devices) {
8959 device->setPreferredConfig(&portConfig);
8960 }
8961 }
jiabinbce0c1d2020-10-05 11:20:18 -07008962
8963 // Here is where the out_set_parameters() for card & device gets called
8964 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8965 const audio_devices_t deviceType = device->type();
8966 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008967 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008968 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8969 mpClientInterface->setParameters(output, String8(param));
8970 free(param);
8971 }
jiabin12537fc2023-10-12 17:56:08 +00008972 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008973 if (!profile->hasValidAudioProfile()) {
8974 ALOGW("%s() missing param", __func__);
8975 desc->close();
8976 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008977 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8978 // Reopen the output with the best audio profile picked by APM when the profile supports
8979 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008980 desc->close();
8981 output = AUDIO_IO_HANDLE_NONE;
8982 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8983 profile->pickAudioProfile(
8984 config.sample_rate, config.channel_mask, config.format);
8985 config.offload_info.sample_rate = config.sample_rate;
8986 config.offload_info.channel_mask = config.channel_mask;
8987 config.offload_info.format = config.format;
8988
Haofan Wangf6e304f2024-07-09 23:06:58 -07008989 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8990 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008991 if (status != NO_ERROR) {
8992 return nullptr;
8993 }
8994 }
8995
8996 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008997 setOutputDevices(__func__, desc,
8998 devices,
8999 true,
9000 0,
9001 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00009002 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9003 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9004
jiabinbce0c1d2020-10-05 11:20:18 -07009005 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9006 sp<AudioPolicyMix> policyMix;
9007 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9008 policyMix->setOutput(desc);
9009 desc->mPolicyMix = policyMix;
9010 } else {
9011 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009012 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009013 }
9014
baek.kim -61c20122022-07-27 10:05:32 +00009015 } else if (hasPrimaryOutput() && speaker != nullptr
9016 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009017 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9018 // no duplicated output for:
9019 // - direct outputs
9020 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009021 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009022 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9023
9024 //TODO: configure audio effect output stage here
9025
9026 // open a duplicating output thread for the new output and the primary output
9027 sp<SwAudioOutputDescriptor> dupOutputDesc =
9028 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9029 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9030 if (status == NO_ERROR) {
9031 // add duplicated output descriptor
9032 addOutput(duplicatedOutput, dupOutputDesc);
9033 } else {
9034 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9035 mPrimaryOutput->mIoHandle, output);
9036 desc->close();
9037 removeOutput(output);
9038 nextAudioPortGeneration();
9039 return nullptr;
9040 }
9041 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009042 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9043 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9044 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009045 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009046 }
jiabinbce0c1d2020-10-05 11:20:18 -07009047 return desc;
9048}
9049
jiabinf1c73972022-04-14 16:28:52 -07009050status_t AudioPolicyManager::getDevicesForAttributes(
9051 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
9052 // Devices are determined in the following precedence:
9053 //
9054 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9055 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9056 //
9057 // If no such dynamic policy then
9058 // 2) Devices containing an active client using setPreferredDevice
9059 // with same strategy as the attributes.
9060 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9061 //
9062 // If no corresponding active client with setPreferredDevice then
9063 // 3) Devices associated with the strategy determined by the attributes
9064 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9065 //
9066 // See related getOutputForAttrInt().
9067
9068 // check dynamic policies but only for primary descriptors (secondary not used for audible
9069 // audio routing, only used for duplication for playback capture)
9070 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009071 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009072 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009073 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9074 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9075 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009076 if (status != OK) {
9077 return status;
9078 }
9079
9080 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9081 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9082 // as they are unaffected by device/stream volume
9083 // (per SwAudioOutputDescriptor::isFixedVolume()).
9084 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9085 ) {
9086 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9087 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9088 devices.add(deviceDesc);
9089 } else {
9090 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9091 // which selects setPreferredDevice if active. This means forVolume call
9092 // will take an active setPreferredDevice, if such exists.
9093
9094 devices = mEngine->getOutputDevicesForAttributes(
9095 attr, nullptr /* preferredDevice */, false /* fromCache */);
9096 }
9097
9098 if (forVolume) {
9099 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9100 // for single volume control in AudioService (such relationship should exist if
9101 // SPEAKER_SAFE is present).
9102 //
9103 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9104 DeviceVector speakerSafeDevices =
9105 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9106 if (!speakerSafeDevices.isEmpty()) {
9107 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9108 devices.remove(speakerSafeDevices);
9109 }
9110 }
9111
9112 return NO_ERROR;
9113}
9114
9115status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9116 AudioProfileVector& audioProfiles,
9117 uint32_t flags,
9118 bool isInput) {
9119 for (const auto& hwModule : mHwModules) {
9120 // the MSD module checks for different conditions
9121 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9122 continue;
9123 }
9124 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9125 : hwModule->getOutputProfiles();
9126 for (const auto& profile : ioProfiles) {
9127 if (!profile->areAllDevicesSupported(devices) ||
9128 !profile->isCompatibleProfileForFlags(
9129 flags, false /*exactMatchRequiredForInputFlags*/)) {
9130 continue;
9131 }
9132 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9133 }
9134 }
9135
9136 if (!isInput) {
9137 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9138 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9139 if (msdModule != nullptr) {
9140 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9141 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9142 for (const auto &profile: msdModule->getOutputProfiles()) {
9143 if (!profile->asAudioPort()->isDirectOutput()) {
9144 continue;
9145 }
9146 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9147 }
9148 } else {
9149 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9150 }
9151 }
9152 }
9153
9154 return NO_ERROR;
9155}
9156
jiabin3ff8d7d2022-12-13 06:27:44 +00009157sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9158 const audio_config_t *config,
9159 audio_output_flags_t flags,
9160 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009161 closeOutput(outputDesc->mIoHandle);
9162 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9163 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9164 if (preferredOutput == nullptr) {
9165 ALOGE("%s failed to reopen output device=%d, caller=%s",
9166 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009167 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009168 return preferredOutput;
9169}
9170
9171void AudioPolicyManager::reopenOutputsWithDevices(
9172 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9173 for (const auto& [output, devices] : outputsToReopen) {
9174 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9175 closeOutput(output);
9176 openOutputWithProfileAndDevice(desc->mProfile, devices);
9177 }
jiabina84c3d32022-12-02 18:59:55 +00009178}
9179
jiabinc44b3462022-12-08 12:52:31 -08009180PortHandleVector AudioPolicyManager::getClientsForStream(
9181 audio_stream_type_t streamType) const {
9182 PortHandleVector clients;
9183 for (size_t i = 0; i < mOutputs.size(); ++i) {
9184 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9185 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9186 }
9187 return clients;
9188}
9189
9190void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9191 PortHandleVector clients;
9192 for (auto stream : streams) {
9193 PortHandleVector clientsForStream = getClientsForStream(stream);
9194 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9195 }
9196 mpClientInterface->invalidateTracks(clients);
9197}
9198
jiabin220eea12024-05-17 17:55:20 +00009199void AudioPolicyManager::updateClientsInternalMute(
9200 const sp<android::SwAudioOutputDescriptor> &desc) {
9201 if (!desc->isBitPerfect() ||
9202 !com::android::media::audioserver::
9203 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9204 // This is only used for bit perfect output now.
9205 return;
9206 }
9207 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9208 bool bitPerfectClientInternalMute = false;
9209 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9210 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9211 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9212 bitPerfectClient = client;
9213 continue;
9214 }
9215 bool muted = false;
9216 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9217 // System sound is muted.
9218 muted = true;
9219 } else {
9220 bitPerfectClientInternalMute = true;
9221 }
9222 if (client->setInternalMute(muted)) {
9223 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9224 if (!result.ok()) {
9225 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9226 continue;
9227 }
9228 media::TrackInternalMuteInfo info;
9229 info.portId = result.value();
9230 info.muted = client->getInternalMute();
9231 clientsInternalMute.push_back(std::move(info));
9232 }
9233 }
9234 if (bitPerfectClient != nullptr &&
9235 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9236 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9237 if (result.ok()) {
9238 media::TrackInternalMuteInfo info;
9239 info.portId = result.value();
9240 info.muted = bitPerfectClient->getInternalMute();
9241 clientsInternalMute.push_back(std::move(info));
9242 } else {
9243 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9244 __func__, bitPerfectClient->portId());
9245 }
9246 }
9247 if (!clientsInternalMute.empty()) {
9248 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9249 status != NO_ERROR) {
9250 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9251 }
9252 }
9253}
9254
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009255} // namespace android